Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct way of comparing string jquery operator =

Tags:

jquery

Is this the correct way? I want the statement to run if the value of somevar equals the string?

if (somevar = '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}
like image 727
Prometheus Avatar asked Sep 21 '12 09:09

Prometheus


People also ask

Can we use == to compare strings in JavaScript?

In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.

Can we compare strings using operator?

Compare two strings using the Equal to (==) operator in C++ Equal To (==) operator: It is used to check the equality of the first string with the second string.

How do I compare two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.

How is string comparison done?

The algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second. We're done.


2 Answers

NO, when you are using only one "=" you are assigning the variable.

You must use "==" : You must use "===" :

if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
 $("#code").text(data.DATA[0].ID);
}

You could use fonction like .toLowerCase() to avoid case problem if you want

like image 25
sdespont Avatar answered Sep 21 '22 17:09

sdespont


No. = sets somevar to have that value. use === to compare value and type which returns a boolean that you need.

Never use or suggest == instead of ===. its a recipe for disaster. e.g 0 == "" is true but "" == '0' is false and many more.

More information also in this great answer

like image 153
Ali Habibzadeh Avatar answered Sep 23 '22 17:09

Ali Habibzadeh