JavaScript examples of the difference between null and undefined

  • 2020-03-30 03:58:32
  • OfStack

So undefined:

Variables in Javascript are weakly typed, so you only need to use the var keyword when declaring variables. In a strongly typed language like C, if you declare a variable without specifying an initial value, you give it a default value, such as 0 for an int. But in a weakly typed language like Javascript, there's no way to determine what the default value is for a variable like this, like if I declare a variable

Var v1.

False or 0, or "" ?

Because there is no type, it cannot be determined. In Javascript, for a variable that does not have a given initial value after this life, give it an undefined value. But the premise is that the variable must have been declared, and if you don't declare an identifier, you get an error. Take a look at the code below.

Vo = "vo"; Global variables are created without the var keyword, and if no value is assigned, an error will be reported, as shown below
/ / v1. / / complains
Var v2. / / undeifned
Var v3 = ""; / / null
Alert (vo);
/ / alert (v1); //
Alert (v2).
Alert (v3);

Null:

Javscript has several basic types, Number,String,Boolean, Object. For variables of type Object, he has two cases, one is an instance of an Object, and the other is an empty reference null, which should be easy for those familiar with object-oriented languages like Java to understand. In both cases, their type is Object. A variable in Javascript, when it's assigned a value
It determines its type, like this.

The code is as follows:


var v1 = 1; 
var v2 = true; 

alert(typeof v1); //number 
alert(typeof v2); //boolean 

v2 = new Date(); 
alert(typeof v2); //object 

v2 = "str"; 
alert(typeof v2); //string 

v2 = null; 
alert(typeof v2); //object

As you can see, null in Javascript represents a special value of type Object, which is used to represent the concept of empty references. If you want to declare an identifier as type Object, but do not give it an instance for now, you can initialize it to null for later use.
This is not always true. Simply put, for all variables, as long as the initial value has not been specified after the declaration, it is undefined. If the Object type is used to represent the concept of an empty reference, it is null.

Here are some additions:

Null: no value;
Undefined: represents an undeclared variable, or a declared but unassigned variable, or an object property that does not exist. The == operator treats the two as equal. If you want to distinguish between the two, use the === or typeof operator. Use the if (! Object){} contains both.


Related articles: