null vs undefined
Comparing the undefined and null Values
The undefined value is returned when you read a variable that hasn't had a value assigned to it or try to read an object property that doesn't exist.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myData = {
name : "JavaScript",
weather : "good",
};
document.writeln("Prop: " + myData.doesntexist);
</script>
</body>
</html>
null is used when you want to indicate an invalid value of object, string, number, or boolean.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myData = {
name : "JavaScript",
};
document.writeln("Var: " + myData.weather);
document.writeln("Prop: " + ("weather" in myData));
myData.weather = "Good";
document.writeln("Var: " + myData.weather);
document.writeln("Prop: " + ("weather" in myData));
myData.weather = null;
document.writeln("Var: " + myData.weather);
document.writeln("Prop: " + ("weather" in myData));
</script>
</body>
</html>
Checking Whether a Variable or Property Is null or undefined
Check whether a property is null or undefined with if statement and the negation operator (!).
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var myData = {
name : "JavaScript",
city : null
};
if (!myData.name) {
document.writeln("name IS null or undefined");
} else {
document.writeln("name is NOT null or undefined");
}
if (!myData.city) {
document.writeln("city IS null or undefined");
} else {
document.writeln("city is NOT null or undefined");
}
</script>
</body>
</html>
If a variable or property is null or undefined, the coerced boolean value is false.
Differentiating Between null and undefined
To treat undefined the same as null, you can use the equality operator (==). To differentiate between null and undefined, you need to use the identity operator (===).
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<script type="text/javascript">
var firstVal = null;
var secondVal;
var equality = firstVal == secondVal;
var identity = firstVal === secondVal;
document.writeln("Equality: " + equality);
document.writeln("Identity: " + identity);
</script>
</body>
</html>
Home
JavaScript Book
Language Basics
JavaScript Book
Language Basics
Data Types:
- JavaScript Data Types
- typeof Operator
- The Undefined Type
- null Type
- null vs undefined
- Boolean Type
- Boolean() casting function
- The Literials of Number Type
- Octal Integer
- Hexadecimal
- Floating-Point Values
- Value range
- NaN
- Number Conversions:Number(), parseInt() and parseFloat()
- Number() function
- parseInt()
- parseFloat()
- The String Type
- String Literals and Escapes
- Get the String Length
- Converting to a String with toString() method
- Convert Number to String with radix
- Convert to String with String() casting function