0
for(i=0;i<contacts.length;i++){
    if((contacts[i].lname.toUpperCase().charAt(0))===(lastName.toUpperCase()))
        window.alert("already exists");
}

Am I doing correct? It is not working even if lastName already exists! Is there any other way to compare Strings in Javascript?

6
  • 1
    What is not working? Commented Mar 4, 2016 at 17:11
  • 4
    .charAt(0)? are you comparing first character with lastName? Commented Mar 4, 2016 at 17:11
  • What are the strings? What does your debugger say? Commented Mar 4, 2016 at 17:11
  • You're comparing the first character lname to the entire lastName string. Remove the charAt call. Commented Mar 4, 2016 at 17:12
  • You are right. I didn't notice charAt(0). It is working . Commented Mar 4, 2016 at 17:15

2 Answers 2

3

as pointed out i think it should be

for(i=0;i<contacts.length;i++){
    if( contacts[i].lname.toUpperCase() === lastName.toUpperCase() )
        window.alert("already exists");
}
Sign up to request clarification or add additional context in comments.

Comments

0

It should be like:

for(i=0;i<contacts.length;i++){
            if((contacts[i].lname.toUpperCase())===(lastName.toUpperCase()))
                window.alert("Last name already exists");
            else
            contacts.push(person);  
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.