SoFunction
Updated on 2025-03-05

6 simple data types for ECMAScript

Preface

This article is a JSRedBook data type, mainly aboutECMAScriptThree of the 6 simple data types (primitive types) of  :UndefinedNullBooleanand commonly used operators.

ECMAScript’s data types are very flexible, and one data type can be used as multiple data types.

typeof operator

The typeof operator is used to determine (detect) the data type of any variable

Type detection

Use a valuetypeofThe operator returns one of the following strings:

Data Type Test results
undefined Indicates that the value is undefined
boolean Indicates that the value is a boolean value
string Indicates that the value is a string
number The value is numerical
symbol Indicates that the value is a symbol
function Represents the value as a function
object Indicates that the value is an object or null

Instructions for use

The following is the usetypeofExamples of operators:

 const message = "Hello"
 (typeof(msssage)) // "string"
 (typeof 99 ) // "number"

Notice:becausetypeofis an operator rather than a function, so no parameters are needed (but parameters can be used)

Small knowledge

Calltypeof nullThe return is "object". This is because of the special valuenullConsidered a reference to an empty object

Notice:Strictly speaking, the function isECMAScriptis considered an object and does not represent a data type; but functions also have their own special properties, so it is necessary to passtypeofOperators to distinguish functions from other objects.

Undefined Type

Undefined type has only one value, which is a special value undefined

The purpose of increasing this special value is to formally clarify the empty object pointer (null) and uninitialized variables

Practice scene

When a variable is declared using var or let but not initialized, it is equivalent to assigning an undefined value to the variable, as follows:

 let message; 
 (message == undefined); // true 

The variable message is not initialized at the time of declaration, so when comparing the literal values ​​of it and undefined, the two are equal.

Let's take a look at the following example:

 let message = undefined; 
 (message == undefined); // true

This is an unnecessary predefined, because by default any uninitialized variable will be obtainedundefinedValue.

Notice:Generally speaking, you never need to explicitly set a variable.undefinedValue, literal valueundefinedMainly used for comparison, and inECMA-262 Edition 3It did not exist before.

The difference between undefined and not defined

IncludeundefinedThere is a difference between the variable of the value and the undefined variable.as follows:

 let message;   // This variable is declared, but the value is undefined // let age; make sure that this variable has not been declared ​
 (message); // "undefined" 
 (age); // Report an error;

In the above example, the first oneBecause the variable message has no value defined, it is "undefined"; and the second oneTo output the value of an undeclared variable age, it will cause an error.

Notice:Only one useful operation can be performed for an undeclared variable is to call ittypeof. (Call to undeclared variablesdeleteThere will be no errors, but this operation is useless. In fact, an error will be thrown in strict mode)

Use typeof to detect undefined

Calling uninitialized variablestypeofWhen  , the result returned is "undefined", but when calling it on an undeclared variable, the result returned is still "undefined", which is a bit incomprehensible. For example, the following example:

 let message; //This variable is declared, but the value is undefined // Make sure that this variable has not been declared ​
 // let age 
 (typeof message); // "undefined"
 (typeof age); // "undefined"

This is strange (⊙ˍ⊙), why, whether it is declared or not,typeofWhat are returned are the string "undefined"? .

Because strictly speaking, there are fundamental differences between these two variables, but neither of them can perform actual operations, so both returnundefined

Notice:Even if uninitialized variables are automatically assignedundefinedvalue, but it is still recommended to initialize while declaring variables. This waytypeofWhen you return "undefined", you will know that it is because the given variable has not been declared, not declared but not initialized.

Small knowledge

undefined is a false value.

However, there are many other values ​​that may also be false values, so you must make sure that what you want to detect is the literal value of undefined, not just false values, as follows:

 let message; // This variable is declared, but the value is undefined ​
 if (message) { 
  // This block will not be executed } 
 ​
 if (!message) { 
  // This block will be executed } 
 ​
 if (age) { // age has no declaration  // An error will be reported here }

Null Type

nullValue represents an empty object pointer

Practice scene

Because its value represents an empty object pointer,typeofPass onenullThe object will be returned as follows:

 const test = null;
 (typeof test);   // "object"  

suggestion:When defining variables to save object values ​​in the future, it is recommended to usenullTo initialize, do not use other values;

In this way, just check whether the value of this variable isnullYou can know whether this variable was later reassigned to an object, as follows:

 if (car != null) { 
  // car is a reference to an object } 

Notice:Compare null and undefined with equal operator (==) always return true

becauseundefinedThe value is derived from the null value, soECMA-262Define them as surface equality, as follows:

 (null == undefined); // true 

Small knowledge

even thoughnullandundefinedIt has something to do, and their uses are completely different.

As mentioned earlier, it is never necessary to explicitly set the variable value toundefined,butnullNot so; at any time,As long as the variable needs to save the object, and there is no object to save at that time, you must use it.nullTo fill this variable; This will keepnullis the semantics of an empty object pointer and further distinguishes it from undefined.

Another point:nullIt is also a false value, and the detection method is as followsundefinedConsistent

Boolean Type

Boolean(Bolean value) type isECMAScriptOne of the most frequently used types in  has two literal values:trueandfalse

  • These two Boolean values ​​are different from numeric values, so true does not equal 1 and false does not equal 0.

Practice scene

Boolean literals true and false are case sensitive

Therefore True and False (and other mixed-case forms) are valid identifiers, but not boolean values, as follows:

 const a = true; // ✅
 const b = false; // ✅
 const c = True; // Report an error:True is not defined

Type conversion

Although there are only two boolean values, all the othersECMAScriptValues ​​of types have equivalent forms of corresponding boolean values

To convert a value of another type to a Boolean, you can call a specificBoolean() transformation function,as follows:

 const message = "Hello juejin";
 const remessage = Boolean(message); // true

In the above example, the stringmessageWill be converted to a boolean value and saved in a variableremessagemiddle.

Conversion table

Boolean() transformation functionCan be called on any type of data, and always return a boolean value; what value can be converted totrueorfalseThe rules depend on the data type and the actual value.

The following table summarizes the conversion rules between different types and boolean values:

Data Type Convert to true value Convert to false value
Boolean true false
String Non-empty string "" (empty string)
Number Non-zero value (including infinite value) 0,NaN
Object Any object null
Undefined N/A (not present) undefined

This table is very important, and basic Boolean conversions have to rely on this table

Conversion in if

pictureifThe isoflow control statement will automatically perform the conversion of other types of values ​​to boolean values.,as follows:

 const test = "Hey";
 if (test) { 
     ("Value is True");
 }
 // "Value is True"

In the above example, stringtestIt will be automatically converted to equivalent booleantrue, so the output is successful"Value is True"

Due to this automatic conversion, it is important to understand what variables are used in the control flow statement, and using objects incorrectly instead of booleans will significantly change the execution flow of the application.

Summarize

  • typeofOperators are used to determine the data type of any variable
  • undefinedAttributes indicate that the variable has not been assigned or has not been declared at all.
  • undefinedLiteral values ​​are mainly used for comparison
  • nullValue represents an empty object pointer
  • nullUsed to fill a variable to save an object, but there was no object to save at that time.
  • BooleanTwo literal values:trueandfalse, generally refers to correct and wrong;
  • Boolean() transformation functionCan be called on any type of data and always return a boolean value.

This is the end of this article about 6 simple data types of ECMAScript. For more related ECMAScript data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!