Assignment of undefined to declared but uninitialized variables? - javascript

Is there any particular reason why the following occurs?
var newVar;
newVar; //returns "undefined"
It gets really confusing when:
newVar == undefined; //true
newVar == null; //true
I've read some threads that suggest using the typeof operator instead to detect if a variable is declared but initialized and to always initialize a declared variable with null, however:
typeof newVar //returns object
While I'm aware that (correct me if I'm wrong) null is an object placeholder and is thus an object type, the way this is handled in JavaScript is just really confusing for me.
Professional JS for Web Developers says:
In what way is null a derivative of undefined?
Sorry for the pepperage of questions - but thanks in advance to all answers.

The relation ship between undefined and null can be confusing, hopefully this clears it up:
First of all, they are values two different data types:
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.
(which also explains why the variable has the value undefined at first) and
The Null type has exactly one value, called null.
The makes more sense if you use strict comparison:
null === undefined // false
So why does null == undefined result in true? Because the specification says so:
2. If x is null and y is undefined, return true.
3. If x is undefined and y is null, return true.
So,
In what way is null a derivative of undefined?
It isn't. They are two different values of two different data types. Maybe conceptually, it is some kind of "derivative", but not from a technical point of view. The book is either over-simplifying or over-complicating it in this point.
While I'm aware that (correct me if I'm wrong) null is an object placeholder and is thus an object type, the way this is handled in JavaScript is just really confusing for me.
typeof null returns 'object', because the specification says so. It's confusing because the data type of null is in actually Null, not Object (as explained at the very top). You are right, maybe the original purpose for null was to represent the absence of an object, but in fact, it can be used to represent the absence of any value.

Related

Why is null an object in Javascript? [duplicate]

Why is null considered an object in JavaScript?
Is checking
if ( object == null )
Do something
the same as
if ( !object )
Do something
?
And also:
What is the difference between null and undefined?
(name is undefined)
You: What is name? (*)
JavaScript: name? What's a name? I don't know what you're talking about. You haven't ever mentioned any name before. Are you seeing some other scripting language on the (client-)side?
name = null;
You: What is name?
JavaScript: I don't know.
In short; undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it's not known what the value is.
One thing to remember is that null is not, conceptually, the same as false or "" or such, even if they equate after type casting, i.e.
name = false;
You: What is name?
JavaScript: Boolean false.
name = '';
You: What is name?
JavaScript: Empty string
*: name in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
The difference can be summarized into this snippet:
alert(typeof(null)); // object
alert(typeof(undefined)); // undefined
alert(null !== undefined) //true
alert(null == undefined) //true
Checking
object == null is different to check if ( !object ).
The latter is equal to ! Boolean(object), because the unary ! operator automatically cast the right operand into a Boolean.
Since Boolean(null) equals false then !false === true.
So if your object is not null, but false or 0 or "", the check will pass
because:
alert(Boolean(null)) //false
alert(Boolean(0)) //false
alert(Boolean("")) //false
null is not an object, it is a primitive value. For example, you cannot add properties to it. Sometimes people wrongly assume that it is an object, because typeof null returns "object". But that is actually a bug (that might even be fixed in ECMAScript 6).
The difference between null and undefined is as follows:
undefined: used by JavaScript and means “no value”. Uninitialized variables, missing parameters and unknown variables have that value.
> var noValueYet;
> console.log(noValueYet);
undefined
> function foo(x) { console.log(x) }
> foo()
undefined
> var obj = {};
> console.log(obj.unknownProperty)
undefined
Accessing unknown variables, however, produces an exception:
> unknownVariable
ReferenceError: unknownVariable is not defined
null: used by programmers to indicate “no value”, e.g. as a parameter to a function.
Examining a variable:
console.log(typeof unknownVariable === "undefined"); // true
var foo;
console.log(typeof foo === "undefined"); // true
console.log(foo === undefined); // true
var bar = null;
console.log(bar === null); // true
As a general rule, you should always use === and never == in JavaScript (== performs all kinds of conversions that can produce unexpected results). The check x == null is an edge case, because it works for both null and undefined:
> null == null
true
> undefined == null
true
A common way of checking whether a variable has a value is to convert it to boolean and see whether it is true. That conversion is performed by the if statement and the boolean operator ! (“not”).
function foo(param) {
if (param) {
// ...
}
}
function foo(param) {
if (! param) param = "abc";
}
function foo(param) {
// || returns first operand that can't be converted to false
param = param || "abc";
}
Drawback of this approach: All of the following values evaluate to false, so you have to be careful (e.g., the above checks can’t distinguish between undefined and 0).
undefined, null
Booleans: false
Numbers: +0, -0, NaN
Strings: ""
You can test the conversion to boolean by using Boolean as a function (normally it is a constructor, to be used with new):
> Boolean(null)
false
> Boolean("")
false
> Boolean(3-3)
false
> Boolean({})
true
> Boolean([])
true
What is the difference between null and undefined??
A property when it has no definition is undefined. a null is an object. Its type is object. null is a special value meaning "no value. undefined is not an object, its type is undefined.
You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". You can even compare a variable that is undefined to null or vice versa, and the condition will be true:
undefined == null
null == undefined
Refer to JavaScript Difference between null and undefined for more detail.
and with your new edit yes
if (object == null) does mean the same if(!object)
when testing if object is false, they both only meet the condition when testing if false, but not when true
Check here: Javascript gotcha
First part of the question:
Why is null considered an object in JavaScript?
It is a JavaScript design error they can't fix now. It should have been type null, not type object, or not have it at all. It necessitates an extra check (sometimes forgotten) when detecting real objects and is source of bugs.
Second part of the question:
Is checking
if (object == null)
Do something
the same as
if (!object)
Do something
The two checks are always both false except for:
object is undefined or null: both true.
object is primitive, and 0, "", or false: first check false, second true.
If the object is not a primitive, but a real Object, like new Number(0), new String(""), or new Boolean(false), then both checks are false.
So if 'object' is interpreted to mean a real Object then both checks are always the same. If primitives are allowed then the checks are different for 0, "", and false.
In cases like object==null, the unobvious results could be a source of bugs. Use of == is not recommended ever, use === instead.
Third part of the question:
And also:
What is the difference between null and undefined?
In JavaScript, one difference is that null is of type object and undefined is of type undefined.
In JavaScript, null==undefined is true, and considered equal if type is ignored. Why they decided that, but 0, "" and false aren't equal, I don't know. It seems to be an arbitrary opinion.
In JavaScript, null===undefined is not true since the type must be the same in ===.
In reality, null and undefined are identical, since they both represent non-existence. So do 0, and "" for that matter too, and maybe the empty containers [] and {}. So many types of the same nothing are a recipe for bugs. One type or none at all is better. I would try to use as few as possible.
'false', 'true', and '!' are another bag of worms that could be simplified, for example, if(!x) and if(x) alone are sufficient, you don't need true and false.
A declared var x is type undefined if no value is given, but it should be the same as if x was never declared at all. Another bug source is an empty nothing container. So it is best to declare and define it together, like var x=1.
People are going round and round in circles trying to figure out all these various types of nothing, but it's all just the same thing in complicated different clothes. The reality is
undefined===undeclared===null===0===""===[]==={}===nothing
And maybe all should throw exceptions.
TLDR
undefined is a primitive value in JavaScript that indicates the implicit absence of a value. Uninitialized variables automatically have this value, and functions without an explicit return statement, return undefined.
null is also a primitive value in JavaScript. It indicates the intentional absence of an object value. null in JavaScript was designed to enable interoperability with Java.
typeof null returns "object" because of a peculiarity in the design of the language, stemming from the demand that JavaScript be interoperable with Java. It does not mean null is an instance of an object. It means: given the tree of primitive types in JavaScript, null is part of the "object-type primitive" subtree. This is explained more fully below.
Details
undefined is a primitive value that represents the implicit absence of a value. Note that undefined was not directly accessible until JavaScript 1.3 in 1998. This tells us that null was intended to be the value used by programmers when explicitly indicating the absence of a value. Uninitialized variables automatically have the value undefined. undefined is a one-of-a-kind type in the ECMAScript specification.
null is a primitive value that represents the intentional absence of an object value. null is also a one-of-a-kind type in the ECMAScript specification.
null in JavaScript was designed with a view to enable interoperability with Java, both from a "look" perspective, and from a programmatic perspective (eg the LiveConnect Java/JS bridge planned for 1996). Both Brendan Eich and others have since expressed distaste at the inclusion of two "absence of value" values, but in 1995 Eich was under orders to "make [JavaScript] look like Java".
Brendan Eich:
If I didn't have "Make it look like Java" as an order from management,
and I had more time (hard to unconfound these two causal factors), then I would have preferred a Self-like "everything's an object"
approach: no Boolean, Number, String wrappers. No undefined and null.
Sigh.
In order to accommodate Java's concept of null which, due to the strongly-typed nature of Java, can only be assigned to variables typed to a reference type (rather primitives), Eich chose to position the special null value at the top of the object prototype chain (i.e. the top of the reference types), and to include the null type as part of the set of "object-type primitives".
The typeof operator was added shortly thereafter in JavaScript 1.1, released on 19th August 1996.
From the V8 blog:
typeof null returns object, and not null, despite null being a
type of its own. To understand why, consider that the set of all
JavaScript types is divided into two groups:
objects (i.e. the Object type)
primitives (i.e. any non-object value)
As such, null means “no object value”, whereas undefined means “no
value”.
Following this line of thought, Brendan Eich designed JavaScript to
make typeof return 'object' for all values on the right-hand side,
i.e. all objects and null values, in the spirit of Java. That’s why
typeof null === 'object' despite the spec having a separate null type.
So Eich designed the hierarchy of primitive types to enable interoperability with Java. This led to him positioning null along with the "object-type primitives" on the hierarchy. To reflect this, when typeof was added to the language shortly thereafter, he chose typeof null to return "object".
The surprise expressed by JavaScript developers at typeof null === "object" is the result of an impedance mismatch (or abstraction leak) between a weakly-typed language (JavaScript) that has both null and undefined, and another, strongly-typed language (Java) that only has null, and in which null is strictly defined to refer to a reference type (not a primitive type).
Note that this is all logical, reasonable and defensible. typeof null === "object" is not a bug, but a second-order effect of having to accommodate Java interoperability.
A number of imperfect backwards rationalisations and/or conventions have emerged, including that undefined indicates implicit absence of a value, and that null indicates intentional absence of a value; or that undefined is the absence of a value, and null is specifically the absence of an object value.
A relevant conversation with Brendan Eich, screenshotted for posterity:
typeof null; // object
typeof undefined; // undefined
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.
var x = null;
var y;
x is declared & defined as null
y is declared but not defined. It is declared with no value so it is undefined.
z is not declared so would also be undefined if you attempted to use z.
One way to make sense of null and undefined is to understand where each occurs.
Expect a null return value in the following situations:
Methods that query the DOM
console.log(window.document.getElementById("nonExistentElement"));
//Prints: null
JSON responses received from an Ajax request
{
name: "Bob",
address: null
}
RegEx.exec.
New functionality that is in a state of flux. The following returns null:
var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));
// But this returns undefined:
Object.getOwnPropertyDescriptor({}, "a");
All other cases of non-existence are denoted by undefined (as noted by #Axel). Each of the following prints "undefined":
var uninitalised;
console.log(uninitalised);
var obj = {};
console.log(obj.nonExistent);
function missingParam(missing){
console.log(missing);
}
missingParam();
var arr = [];
console.log(arr.pop());
Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.
A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:
if(typeof unknown !== "undefined"){
//use unknown
}
In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:
if(value === undefined){
// stuff
}
Comparison of many different null checks in JavaScript:
http://jsfiddle.net/aaronhoffman/DdRHB/5/
// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;
...trim...
http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html
To add to the answer of What is the differrence between undefined and null, from JavaScript Definitive Guide 6th Edition, p.41 on this page:
You might consider undefined to represent system-level, unexpected,
or error-like absense of value and null to represent program-level,
normal, or expected absence of value. If you need to assign one of
these values to a variable or property or pass one of these values to
a function, null is almost always the right choice.
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
Some precisions:
null and undefined are two different values. One is representing the absence of a value for a name and the other is representing the absence of a name.
What happens in an if goes as follows for if( o ):
The expression in the parentheses o is evaluated, and then the if kicks in type-coercing the value of the expression in the parentheses - in our case o.
Falsy (that will get coerced to false) values in JavaScript are: '', null, undefined, 0, and false.
The following function shows why and is capable for working out the difference:
function test() {
var myObj = {};
console.log(myObj.myProperty);
myObj.myProperty = null;
console.log(myObj.myProperty);
}
If you call
test();
You're getting
undefined
null
The first console.log(...) tries to get myProperty from myObj while it is not yet defined - so it gets back "undefined". After assigning null to it, the second console.log(...) returns obviously "null" because myProperty exists, but it has the value null assigned to it.
In order to be able to query this difference, JavaScript has null and undefined: While null is - just like in other languages an object, undefined cannot be an object because there is no instance (even not a null instance) available.
For example window.someWeirdProperty is undefined, so
"window.someWeirdProperty === null" evaluates to false while
"window.someWeirdProperty === undefined" evaluates to true.
Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.
In Javascript null is not an object type it is a primitave type.
What is the difference?
Undefined refers to a pointer that has not been set.
Null refers to the null pointer for example something has manually set a variable to be of type null
Look at this:
<script>
function f(a){
alert(typeof(a));
if (a==null) alert('null');
a?alert(true):alert(false);
}
</script>
//return:
<button onclick="f()">nothing</button> //undefined null false
<button onclick="f(null)">null</button> //object null false
<button onclick="f('')">empty</button> //string false
<button onclick="f(0)">zero</button> //number false
<button onclick="f(1)">int</button> //number true
<button onclick="f('x')">str</button> //string true
From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas
But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)
Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.
That said:
var game = null; //typeof(game) is "object"
game.score = 100;//null is not an object, what the heck!?
game instanceof Object; //false, so it's not an instance but it's type is object
//let's make this primitive variable an object;
game = {};
typeof(game);//it is an object
game instanceof Object; //true, yay!!!
game.score = 100;
Undefined case:
var score; //at this point 'score' is undefined
typeof(score); //'undefined'
var score.player = "felix"; //'undefined' is not an object
score instanceof Object; //false, oh I already knew that.
null is an object. Its type is null. undefined is not an object; its type is undefined.
The best way to think about 'null' is to recall how the similar concept is used in databases, where it indicates that a field contains "no value at all."
Yes, the item's value is known; it is 'defined.' It has been initialized.
The item's value is: "there is no value."
This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."
The other fun thing about null, compared to undefined, is that it can be incremented.
x = undefined
x++
y = null
y++
console.log(x) // NaN
console.log(y) // 0
This is useful for setting default numerical values for counters. How many times have you set a variable to -1 in its declaration?
Undefined means a variable has been declared but it has not been assigned any value while Null can be assigned to a variable representing "no value".(Null is an assignment operator)
2.Undefined is a type itself while Null is an object.
3.Javascript can itself initialize any unassigned variable to undefined but it can never set value of a variable to null. This has to be done programatically.
What is a type?
A type is a way to categorize values. Here is a table with the types in question and their typeof result.
Type
Values type contains
typeof result
Is typeof result a lie?
Undefined
Only: undefined
"undefined"
No
Null
Only: null
"object"
Yes
Object
Infinite amount of values: {}, {a: "b"}, ...
"object"
No
null is not an object, its a value of type Null.
The typeof operator is lying! It returning "object" for null is a mistake in the JavaScript language.
I wrote a chapter about this in my open-source e-book. You can read it here https://github.com/carltheperson/advanced-js-objects
Use null to define something as having no value, use undefined when you expect something might not be defined at all.
For example, if a variable has no value, assign it as null.
var weDontHaveAValue = null;
If you expect that something might be not defined at all, e.g. an optional options argument, use undefined.
if (typeof args.optionalParam !== 'undefined') { }
The main difference between null and undefined is that null represents
a missing object, while undefined represents an uninitialized state of a variable.
You can think of null as an undefined object but undefined will be undefined only
since its type is undefined.
let a;
console.log(a); //undefined, since it is declared but not initialized
console.log(null == undefined) //true
console.log(null === undefined) // false
console.log(typeof null) //object
console.log(typeof undefined) //undefined
Not defined and undefined are not the same thing happening.
age;
You: What is the value of age?
Computer: Okay, let me check my memory/reference table..... at this point (the time of you asking), i do not see any identifier named age, not in this scope/context or any parent scope/context; age is not known to me. Maybe later i will come across an instruction to add that identifier to memory, but it does not exist right now.
var age;
You: What is the value of age;
Computer: Okay, checking my memory... I see an identifier in my reference table with that name age but no value or pointer or anything was assigned to it at the time i added it, so i don't know; you can consider it (age) empty/nothing/useless.
var age = null;
You: What is the value of age;
Computer: Okay, checking my memory... i see age in my reference table: it is null. Basically, it is nothing/empty, you cannot do anything with this value; this was intentional.
Now, i probably should not explain it this way but hopefully it will make sense.
I can see why null was designed to be an object in JS, and i personally like it that way.
null and undefined practically means the same thing: empty/nothing. The difference is in how it is used conceptually.
I look at null as developer-intended nothingness; something being null was done on purpose to represent nothing. I look at undefined as computer-intended nothingness; something not having value by accident of the developer/user.
For example, if you call a function from a library/sdk and got back null, you can almost be sure that was designed on purpose by the developer/author; they specifically wanted to indicate nothingness.
Also see - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null

why undefined is a data type

I have learnt recently while debugging, that undefined is a data type and null is an object.
I think both of them comes under datatypes.
I checked the typeof undefined and typeof null. They returned "undefined" and "object" respectively.
typeof undefined
"undefined"
typeof null
"object"
Could some body explain why is this strange behaviour.
typeof null being object is an early mistake - when they tried correcting it in a Chrome nightly (to typeof null === "null" ) too many things relied on the current behavior and too much code broke.
JavaScript objects that are not set to normal values generally have three states:
Undeclared.
Undefined.
Explicitly nothing.
Undeclared
For example - this case:
y++; //I did not declare y before, this causes a reference error
y === 'undefined'; //still a reference error
typeof y; //'undefined', since typeof is an operator and not a function.
Basically, an undeclared variable is in the state 'the script does not know this variable'.
Undefined
This means that the the runtime 'knows this variable' but it wasn't set to anything yet. Or, as the language specification puts this:
undefined value - primitive value used when a variable has not been assigned a value.
For example:
var y; //y is undefined
y === undefined; //true, y defined the line above
typeof y; //undefined, but this is redundant, just do `=== undefined`
(function(x){ /* x is undefined here as it was set to nothing*/})()
Explicitly nothing
When you have something that is supposed to have a value but you want to declare that it is nothing. Or, as the language specification puts this:
null value - primitive value that represents the intentional absence of any object value.
For example, document.getElementById("foo"); returns null if the element with the given ID is not in the DOM to indicate explicitly nothing was returned. Constrast this with functions that have no return statements so they return undefined which is the default.
They have different types for the same reason that they both exist: undefined and null are conceptually not the same thing.
As this answer puts it:
undefined is the lack of a type and value, and null is the lack of a value.
But I prefer to apply a real-world analogy: matter vs dark matter.
undefined is like matter that does not exist. It has no form or substance, and therefore has no meaningful type. You set something to undefined when that thing should not be deemed as existing.
null, on the other hand, right across the realm of Computer Science, describes an object of an unknown state. It's still an object, but we don't know what object or what its value is. (In this sense it is similar to the numeric NaN which is still conceptually a number: we just don't know what number.) Nullity serves a placeholder for an unknown value, not for something that has no value. It's dark matter that does exist, in the form of an object, but no further information about its type is available since we don't have any information on it.
JavaScript understands this. So, historically, typeof null has been 'object' and typeof undefined has been 'undefined'.
Some people say this is a legacy bug since the dawn of JavaScript; I prefer to say that it's common sense from the dawn of JavaScript.
What is a bug in JavaScript is that null === null, and var o = {x:undefined}; 'x' in o; // true, neither of which should be the case.
In the documentation on MDN this is the reason they give for null being an object:
typeof null === 'object'; // This stands since the beginning of JavaScript
Yeah! That is a good reason... I guess they don't understand it themselves, and therefore a design error.

"varName" in window and varName in window both return true

In JavaScript, why do both of the following return true?
> var a;
undefined
> "a" in window;
true
> a in window;
true
Is there some kind of type coercion going on, or does JavaScript store a as both a string and as a variable in the window?
Please feel free to rewrite the title of this question - I wasn't sure exactly how to describe this confusing phenomenon.
No, you declared a variable called a, which is initialized to undefined. This variable is global, so it can be accessed as a sort-of property of the global object (window), so:
var a = {};//an obejct
var b = {};//another
b === a //false, two separate objects, of course but
window.a === a;//true
That's why 'a' in window is true. It's similar to window.hasOwnProperty('a');. Similar, not the same thing.
The second check you did (a in window) is evaluated to undefined in window, in turn the value undefined is stringified, so the expression is finally evaluated to 'undefined in window', which is always going to be true.
I admit, this is confusing, because undefined is both a value and a property, which doesn't really make sense. It's just one of the quirks in JS you have to learn to live with. You can verify this like so:
window.hasOwnProperty('undefined');//true
window.undefined;//undefined of course
window.hasOwnProperty('null');//false
typeof null;//object (really! But it is actually a primitive
typeof undefined;//undefined
null is an object for historic reasons, but I'm not going to give you "The unabridged history of ECMAScript", Just thought you might like to know that.
What you have to keep in mind is how JS resolves variable names, and expressions. I've explained this many times, see this answer and all of the links at the bottom for details on the matter
When you say
"a" in window
javascript looks for a property called a in the window object, and hence returns true.
For
a in window
a evaluates to undefined as noted by #Ootegem and hence returns true.

Speed of comparing to null vs undefined in JavaScript

I have just run a very simple JavaScript performance test (don't ask why). The test declares a variable, but doesn't assign anything to it:
var x;
It then compares the speed of comparing the value variable to null, and to undefined, in other words:
var y = (x == null); and var y = (x == undefined);.
I was expecting the comparison with undefined to be the fasted. In fact it was nowhere near. The comparison with null was far and away the fastest, around 80% faster.
The results I've described above come from running the tests in Chrome (version 13). Running them in Firefox produces results far closer to what I would have expected (the comparison with undefined is faster than with null, albeit very marginally).
So, my question is what could the cause of this be? Why does Chrome seem to favour the comparison with null so greatly?
For quick reference, here's a screenshot of the results:
null is a reserved keyword which cannot be overriden, so when you are doing a comparison against null, all you have to do is a single comparison.
However, when you are checking against undefined, the engine must do a type lookup and then a comparison, meaning that it is actually slightly more demanding.
If you need to actually check to see if something is undefined, you should use
if(typeof notSet == "undefined"){ }
Proof
Try it... and set something to null in your JavaScript console.
null = "will error";
// Errors with --> ReferenceError: invalid assignment left-hand side
However, if you try and do it with undefined, it won't error. That is not to say that you can override undefined, because you can't, but that undefined is its own primitive type.
The only real similarity between null and undefined, is that they can both be coerced into a boolean false.
if i think well, they are not the same. so you can't use null instead of undefined.
typeof !== "undefined" vs. != null
You're comparing against the lookup of a variable called undefined (which returns an undefined value), so it's not doing what you were intending.
There are ways to check whether a variable is undefined. As the other posters have mentioned, typeof x === 'undefined' is one. (There's probably another possibility that is something like hasOwnProperty('x') executed on the global object, but that doesn't check the scope chain.)
I recently discovered that this:
if (typeof this._minLat === 'undefined') {
this._minLat = Math.min(...this.points.map(point => point.lat));
}
return this._minLat;
seems to be many times faster than this:
return this._minLat || Math.min(...this.points.map(point => point.lat));

When JavaScript returns null & undefined?

I have been using JavaScript for couple of years and never cared about the difference between null & undefined earlier, I always use undefined to validate the object existence.
But recently I came through this article. Here they said
JavaScript distinguishes between null, which is an object of type 'object' that indicates a deliberate non-value, and undefined, which is an object of type 'undefined' that indicates an uninitialized value — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined.
I am completely confused now, what exactly is non-value here. How this non-value differs from undefined. And what are the circumstances javascript returns null.
I have tried the below sample
var sam;
alert(sam); // returns undefined
And
try {
//var sam;
alert(sam);
} catch(ex) { } // exception says: sam is undefined
And I am not sure about when js returning nulls. Can someone clarify me.
alert(sam); // returns undefined
Nope, that's an exception.
You get undefined when you access an unset property; you get an error when you use an unset name directly.
Global variables are interesting because they can be accessed either using a simple variable name, or by using properties of the window global object:
alert(window.sam); // undefined
alert(window['sam']); // undefined
alert('sam' in window); // false
alert(sam); // ERROR
If sam is declared but not initialised, accessing window.sam still gets you undefined, but for a different reason: there is an entry in the window object for sam, but it points to the same undefined object as you get when you access a non-existant property.
var sam;
alert(window.sam); // undefined
alert(window['sam']); // undefined
alert('sam' in window); // ** true
alert(sam); // ** undefined
This is of course a confusing bloody mess; undefined is one of the worst mistakes in the design of the JavaScript language.
null on the other hand is fine and works pretty much the same as null/nil/void/None values in other languages. It doesn't come into any of the above.
<script type="text/javascript">
// variable with an unasigned value
var a;
if (a == undefined) {
alert('a is undefined');
}
if (a == null) {
alert('a is undefined');
}
// this will produce an error
if (b == undefined) {
alert('b is undefined');
}
// this is the right way to handle not defined variables
if (typeof(c) == 'undefined') {
alert('c is blabla');
}
</script>
For a variable to receive a null value it must be assigned. null is used to indicate an unknown or don't care value. undefined on the other hand is designed to indicate that the propery being accessed has never ben assigned a value. This differs from null.
With null one is deliberately saying "I don't know what value this should have yet" or "I don't care what value this is right now". OTH in undefined is really saying "Are you sure you should be using this value it hasn't been assigned".
The way I distinguish them is undefined being "I have not defined this value," and null being "I have defined this value, but I do not know or cannot figure out what the value should be."

Categories