The data type

There are seven JavaScript data types.

Six simple types: Undefined, Null, Boolean, Number, String, Symbol

One complex type: Object

BigInt and function are controversial, treated as new data types in some places and as special objects in others.

The typeof operator

The typeof operator can return the data typeof a variable. It can return 7:

  • “Undefined” means undefined;
  • “Boolean” means Boolean;
  • “String” means string;
  • “Number” means number;
  • “Symbol” means symbol;
  • “Object” indicates the value object or NULL.
  • “Function” means the value is a function;

Null is recognized as object because it is considered an empty object.

Undefined

Undefined has only one value, which is the special value Undefined. It was added to formalize the difference between Null and uninitialized variables.

When a var or let declares a variable without giving it an initial value, its value is undefined.

let message;
console.log(message); // undefined
Copy the code

Uninitialized variables also return undefined.

// age is not declared
console.log(age); // also undefined, only error
Copy the code

But undefined is not the same thing.

Use it as a judgment condition:

let message;

if (message) {
  // This will not be executed soon
}

if(! message) {// This will be executed soon
}

// Do not declare age
if (age) {
  // Get an error
}
Copy the code

Null

The word is pronounced [nʌl].

The null type has only one value, NULL, representing an empty object pointer.

When declaring a variable, it is best to initialize it. If you really don’t know what value to assign in the first place, NULL is a good choice.

Ecma-262 considers NULL and defined to be ostensibly equal

Because undefined is derived from null. So using == returns true.

console.log(null= =undefined); // true
Copy the code

Null is false

So it’s the same as undefined.

let message = null;

if (message) {
  // Will not be executed
}
if(! message) {/ /
}
Copy the code

Boolean

Boolean has two literals: true and false. These two Booleans are different from numbers: true does not equal 1 and false does not equal 0.

True and false must be lowercase. True and False are the other two identifiers.

All ECMAScript values have Boolean equivalents. Use Boolean() to convert.

let messageBoolean = Boolean("How are you!");
Copy the code

Rules for converting different types of values to Booleans:

The data type Conversion to true Conversion to false
String Non-empty string An empty string
Number Non-zero values (including infinity) 0, NaN
Object Any object null
Undefined N/A (non-existent) undefined

When we use if (message) judgment, the judgment condition message is converted to the corresponding Boolean value. So it’s important to remember this chart.