0
difference between null and undefined?
please describe with an example. thanks in advanced
1 Odpowiedź
+ 4
Javascript is a mess man. Both mean 'nothing' so in practice there's not much of a difference, and it's ok to be confused about the two.
Technically though, variables are `undefined` if they have been declared but haven't been assigned a value yet. undefined also gets it's own type, "undefined".
var a;
console.log(a); // undefined
console.log(typeof(a)); // "undefined"
If variables haven't even been declared, using them throws.
console.log(b); // Uncaught ReferenceError: b is not defined
`null` is an actual thing you assign to variables.
var a;
a = null;
console.log(a); // null
console.log(typeof(a)); // "object"
`null` is not a real object though, as you know when you try to access a property of it:
var a = null;
console.log(a.lol); // Uncaught TypeError: cannot read property 'lol' of null
You can also assign `undefined` to a variable so that muddies the water a bit, and I don't really recommend it.
var a = 4;
a = undefined;
console.log(typeof(a)); // "undefined"
Bottom line: use undefined for undefined checks (eg `if(a === undefined)`) and null for everything else, especially never assign undefined to a variable.
Also note that `null == undefined`, but `null !== undefined`.