Javascript difference between "=" and "===" [duplicate] - javascript

This question already has answers here:
Difference between == and === in JavaScript [duplicate]
(2 answers)
Closed 7 years ago.
I struggle to understand the function below. I didn't know why my script wasn't working until I changed = with === in the if statement, as shown below. Why does === work while = doesn't?
var testTest = function(answer) {
if (answer === "doggies") {
return "My favorite animal!";
} else {
return "Tested";
}
};
testTest("doggies")
When I type doggies, it shows me My favorite animal! With anything else, it returns Tested as it should.
However, when I change the === in the if statement with =, the else part doesn't work.
var testTest = function(answer) {
if (answer = "doggies") {
return "My favorite animal!";
} else {
return "Tested";
}
};
testTest("elephant")

You need to use == or === for equality checking. = is the assignment operator.
You can read about assignment operators here on MDN.

As a quick reference as you are learning JS:
= assignment operator
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type

I assume you know that = is for assignment, after all, you are using assignment already in the first line:
var testTest = function(answer) {
and I don't think you think that this would compare anything here (or do you?).
The question remains though, why does = in if (answer = "doggies") "not work"?
An assignment is an expression. The result of that expression is the value that was assigned. Here, the result of answer = "doggies" is "doggies", i.e. you essentially running if ("doggies").
JavaScript performs type coercion. That means it automatically converts values of one data type to values of a different data type if necessary, according to specific rules.
The condition of an if statement has to resolve to a Boolean value. But here you are using a string value as condition. The String -> Boolean conversion rules are pretty simple:
The empty string converts to false.
A non-empty string converts to true.
So, after type conversion, the statement is equivalent to if (true), hence it will always execute the first block, never the else block.

Related

How can I pass label value as variable for if else case? [duplicate]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I was trying to compare a variable to a value and accidently ended up using '=' in place of '==' hence the code looked like:
var test = 1;
if(test = 2) {
console.log(test);
}
instead of:
var test = 1;
if(test == 2) {
console.log(test);
}
I assume the value was successfully assigned to the variable , hence the condition returned truthy and console.log() was executed. Is my assumption correct? What is a good coding practice to avoid such mistakes besides Yoda Condition reference
Lint it. There are tools that can automatically analyze your Javascript and catch common errors like this.
The assignment operator (=) in JavaScript evaluates to the right-side value of the expression, which means that test = 2 evaluates to 2 and since all values that aren't falsey (0, false, null, undefined, '', NaN) are thruthy by definition, the if condition was entered.
A good practice would be to always use the === sign when checking for equality and !== for inequality and there are tools that will help you enforcing those rules, like JSHint
Use if (a === b) { do stuff ; } that's three equals, ===
In Javascript you often need three equals, ===, as this requires primitives to have both the same type and value, and will not perform type coercion which, although you don't mention it, can be another source of confusion.
If you leave off an equals, it becomes two equals comparison, a == b, which might not work quite as expected if you are a beginner or unaware of the quirks of this comparison in Javascript, but at least is not an assignment.
The answer in JavaScript is pretty easy: always use strict comparison. This will avoid not only assignment errors, but also some non-intuitive behavior that can come from JavaScript's weak comparison rules.
Edit: Didn't see the questioners requirement to avoid this method.
Use strict comparison operator (===). You can also change the order of the values being compared which will fail if you use assignment statement rather than comparison operator.
Fails:
var test = 1;
if(2 = test) {
console.log(test);
}
The above code will throw an exception since you can't assign a value to the constant value.
Works:
var test = 1;
if(2 == test) {
console.log(test);
}
a = b is an assignment. Meaning a will equal to b.
a == b is a comparison. Meaning does a equal to b.
a === b is the same as == however no type conversion is done. Meaning does a equal to b, but also is it the same object/type?
Where your going wrong with your code is
var test = 1;
if(test = 2) { //this is true, because test now equals 2.
console.log(test);
}
When you assign something the value returned isn't representative of whether or not the assignment was successful, it actually just returns the right hand side of the assignment (e.g, the test = 2 in if (test = 2) would return 2 which is "truthy" in JavaScript, thus causing console.log(test) to evaluate. This can actually be quite useful in certain cases. For example:
while ((value = retrieveSomeValue()) !== null) {
console.log(value);
}
The code above continually assigns some variable value to the result of some function retrieveSomeValue, tests the resulting value to make sure it isn't null, and executes the while body.
To answer your question though: The === operator is more easily distinguished from the = operator and probably behaves more like what you would expect out of ==. Which equals operator (== vs ===) should be used in JavaScript comparisons?

JavaScript - returning true even though condition is not fulfilled [duplicate]

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 5 years ago.
I have the following code:
console.log(usernameExists);
if (usernameExists = true) {
console.log("returning true");
return true;
} else if (looped = true) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
The first console.log(usernameExists) is returning false, but still I am getting a console message of "returning true", and the function in which this is, is returning true! I simply can't figure this out.
The condition is always true, because you assign this value to the variable and this is the value which is evaluated for the if clause.
But you could use a direct check without a compare value (and without assigning this value).
Beside that, you could change the else part to only an if part, becaue you exit the function with return, so no more else happen in this case.
if (usernameExists) {
console.log("returning true");
return true;
}
if (looped) {
console.log(usernameExists+" is returned");
looped = null;
return false;
}
= is an assignment, so you're setting the variable to true, which itself makes the if statement true. What you want is to check if the variable is set to true. In order to do that, use the == or === operators.
For checking conditions, you need to use '==' operator. '=' means assignment operator.
Whereas a '===' checks for value and type.
Hope that is the issue.
In your conditions you are using a single equal!!!
Therefore, it is a assignation operation that is done instead of comparison! So you are not checking that your variable is equal to true but you are assigning it to true and since your assignement operation was successful your condition is at the same time fulfilled.
Change it with two or tree equals == or === instead of =
Usage and differences between == and === are explained very well here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?

Is there a reason to not assign a variable in the while block declaration? [duplicate]

This question already has answers here:
Why would you use an assignment in a condition?
(12 answers)
Closed 8 years ago.
Whenever I do something like this...
var obj;
while (obj = doSomething()) {
// something with obj
}
JSHint tells me warning 84| Expected a conditional expression and instead saw an assignment.. However, doing obj = doSomething() returns the value that doSomething() returns during assignment, so it makes sense to write a while loop in this fashion.
Is there a specific reason that JSHint warns me, and more importantly, are there reasons to not do this? Or can I tell JSHint to ignore those lines for that specific warning?
That warning is to make sure that you have not mistyped = instead of == or ===.
Instead, you can get the boolean value of the evaluated result, like this
while (!!(obj = doSomething())) {
The single = assigns value and is not a comparison operator. Use the below:
while (obj == doSomething()) {
// something with obj
}
Refer: http://www.w3schools.com/js/js_comparisons.asp

Why Constant first in an if condition [duplicate]

This question already has answers here:
Order in conditional statements [duplicate]
(2 answers)
Closed 9 years ago.
I often see if structures being coded like this:
if (true == a)
if (false == a)
Why do they put the constant value first and not the variable? as in this example:
if (a == true)
if (b == true)
This is called yoda syntax or yoda conditions.
It is used to help prevent accidental assignments.
If you forget an equals sign it will fail
if(false = $a) fails to compile
if($a = true) assigns the value of true to the variable $a and evaluates as true
The Wordpress Coding Standards mention this specifically:
if ( true == $the_force ) {
$victorious = you_will( $be );
}
When doing logical comparisons, always put the variable on the right
side, constants or literals on the left.
In the above example, if you omit an equals sign (admit it, it happens
even to the most seasoned of us), you’ll get a parse error, because
you can’t assign to a constant like true. If the statement were the
other way around ( $the_force = true ), the assignment would be
perfectly valid, returning 1, causing the if statement to evaluate to
true, and you could be chasing that bug for a while.
A little bizarre, it is, to read. Get used to it, you will.
This is an example of YODA Style of coding
if (var a == true){
}
is less safer than
if (true == var a){
}
because when you forget that second = mark, you'll get an invalid assignment error, and can catch it at compile time.

What does a !! in JavaScript mean? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
myVar = !!someOtherVar
What does the !! operator (double exclamation point) mean in JavaScript?
Came across this line of code
strict = !!argStrict
... here and wondered what effect the !! has on the line? Pretty new to JS!
It converts your value to a boolean type:
var x = '1';
var y = !!x;
// (typeof y === 'boolean')
Also note the following:
var x = 0;
var y = '0'; // non empty string is truthy
var z = '';
console.log(!!x); // false
console.log(!!y); // true
console.log(!!z); // false
It converts the value to a value of the boolean type by negating it twice. It's used when you want to make sure that a value is a boolean value, and not a value of another type.
In JS everything that deals with booleans accepts values of other types, and some can even return non-booleans (for instance, || and &&). ! however always returns a boolean value so it can be used to convert things to boolean.
It is a pair of logical not operators.
It converts a falsey value (such as 0 or false) to true and then false and a truthy value (such as true or "hello") to false and then true.
The net result is you get a boolean version of whatever the value is.
It converts to boolean
Its a "not not" arg
commonly used to convert (shortcut) string values to bool
like this..
if(!!'true') { alert('its true')}

Categories