How JS engine distinguish null from undefined [duplicate] - javascript

This question already has answers here:
What is the difference between null and undefined in JavaScript?
(38 answers)
JavaScript checking for null vs. undefined and difference between == and ===
(8 answers)
Closed 4 years ago.
In below code snippet a==b return true, i.e they point to same memory location, hence they will have same value.
I would like to know, how JS engine knows a===b is false.
How is type information determined when 2 different types point to same memory location?
Edit 1: From comments it looks like my question might not be clear. I totally understand difference between == and === in terms of usage in JS language. I am more interested in knowing how JS engine saves type information for null and undefined. As per my understanding variables a & b point to same memory location that is why I get a==b, if this understanding is wrong, please correct me.
Edit 2: Ok I will put my question in another way. How typeof operator knows a is object and b is undefined despite having a==b.
var a = null;
var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(typeof a);
console.log(typeof b);

In the code snippet added in the question:
var a = null; var b = undefined;
console.log(a==b);
console.log(a===b);
console.log(a==b) returns true because == uses type coercion to check the equality of both the variables. Therefore, null and undefined are thought of as equals.
console.log(a===b) returns false because === does not use type coercion. For ===, null and undefined are not same types and it doesn't care about checking deep equality when the operands aren't of the same type.
This has got nothing to do with memory locations.

a = null, b= undefined;
a == b /* only check their values */
a === b /* also check their types + values */
typeof a == typeof b // false
typeof "variable" gives the type of the variable.

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: String vs. Object [duplicate]

This question already has answers here:
Why does ("foo" === new String("foo")) evaluate to false in JavaScript?
(5 answers)
Closed 6 years ago.
I've looked all the questions and answers on stackoverflow, but couldn't find the simple answer to this.
What is exactly the difference between string and object?
For example, if I have this code:
var a = 'Tim';
var b = new String('Tim');
What exactly is the difference?
I understand that new complicates the code, and new String slows it down.
Also, I understand a==b is true, but going more strictly a===b is false. Why?
I seem to fail to understand the process behind the object and string creation.
For example:
var a = new String ('Tim');
var b = new String ('Tim');
a==b is false
a is of type string, whereas b is of type object.
=== includes typechecking and cause string is not an object
a === b will give you a false
new String ('Tim') === new String ('Tim') will evaluate to false too, because both are different objects
For normal strings there is no need to create an object, just create your variable and assign it a value.
And as far as your question regarding why == is true and === is false it's because:
== Compares values
=== Compares values AND type (One is a string, one is an object).
Another example of this is:
var a = 1;
var b = '1';
a == b //True as they both have the same value
a === b //false as one is a string and one is an integer
You can do the following to see the difference:
var a = "foo";
var b = new String("foo");
console.log(a);
console.log(b);
The first one is a string literal and the second is a String object. That's why when you compare them they are not equal but when you compare their values they are. You can read more about literals here.

Object is not null and not undefined. What is better - double inversion `!!` or strict equillity `!==` in JavaScript [duplicate]

This question already has answers here:
JavaScript checking for null vs. undefined and difference between == and ===
(8 answers)
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 7 years ago.
Very often we check our objects if they are not null and not undefined. I always use condition if (obj !== null && obj !== undefined). Few days ago my colleague shown me the syntax of double inversion !! and now I can use condition if (!!obj). This syntax is less.
I'm not a person who are only learning js, but I have a little interest.
So is there any difference between these two ways of object validation? Performance difference? Semantic difference? Any difference?
There isn’t any particularly good reason to ever use if (!!obj), as it’s equivalent to if (obj). !!obj and obj !== null && obj !== undefined do different things, though, and you should use whichever’s most appropriate.
obj !== null && obj !== undefined (surprise, surprise) results in false for null and undefined.
!!obj results in false for anything falsy, including null, undefined, '', 0, NaN, and false.
!!foo is used to force coerce a value into its Boolean value. This is, in my experience, often used in APIs that want to return a Boolean value for a value that contains sensitive data. For example, to return whether or not a password is entered you might say return !!password rather than return password.
Continuing on that, if (!!obj) is not the same as if (obj !== null && obj !== undefined) for many values you can think of! Such as false.

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

Keep original value with "variable = NEWVAR || variable;" [duplicate]

This question already exists:
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 9 years ago.
Is this a legitimate way to update variables and keep the original value if the new value is undefined?
variable = NEWVAR || variable;
I created a Fiddle and so far it looks fine, but I don't want to get any nasty surprises.
Here is a test case:
var test = "hello";
test = undefined || test;
alert('"' + test + '"');
I would say, yes, i use it quite often. But you have to keep in mind that
Douglas Crockford: Javascript The Good Parts (p. 40)
The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the
value of the second operand.
So if NEWVAR contains any falsy (false,null,undefined,NaN,0,"") value, the second opertand is evaluated.
As long as you are aware of this you can always use the || operator to get default values
Douglas Crockford: Javascript The Good Parts (p. 51)
The || operator can be used to fill in default values:
var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";
Yes and no. It technically works, but you have to be careful of falsy values because if NEWVAR is 0, false, "", or any other falsy value, it won't be assigned. A wiser way to do this would be to check whether or not NEWVAR is defined, perhaps with a tertiary operator:
variable = (typeof NEWVAR === "undefined") ? variable : NEWVAR;

Categories