JavaScript Data types
There are 5 different types of data in JavaScript:
- String
- Number
- Boolean
- Object
- function
3 Types of Objects:
2 data types that do not contain any values:
Example:
typeof"John"Returns a string
typeof3.14return number
typeof NaNreturn number
typeofFalseReturns a Boolean
typeof [1,2,3,4]Return object
typeof {name: ' John ', Age:34} Returns the object
typeof new date () //returns Object
typeof function () {} //returns function
typeof mycar //return undefined (if myCar not declared)
typeof null //return object
< Span class= "highval" >< Span class= "highval" >< Span class= "highval" >< Span class= "highcom" >< Span class= "highele" >< Span class= "highval" > note:
- The data type of NaN is number
- The data type of the array is object
- Date data type is Object
- The data type of NULL is Object
- The data type of the undefined variable is undefined
If the object is a JavaScript Array or JavaScript Date, We cannot judge their type by typeof because it returns object.
typeof operator
You can use the TypeOf operator to detect the data type of a variable.
Example:
typeof"John"//return string
typeof 3.14 //return number
typeof false //back Boolean
typeof [1,2, 3,4] //returns object
typeof {name: //return object
Note: in javascript, An array is a special type of object. Therefore typeof [1,2,3,4] returns Object.
Null
In JavaScript, null means "nothing". Null is a special type with only one Value. Represents an empty object reference.
Example:
You can set NULL to empty the Object:
var person = null; //value is null (empty), but type is Object
You can set the object to undefined to empty:
var person = undefined; //value is undefined, type is undefined
Note: using typeof to detect null returns is an Object.
Undefined
In JavaScript, undefined is a variable that has no value set.
typeof A variable that has no value returns undefined.
Example:
var person; //value is null (empty), but is still an object
Any variable can be emptied by setting the value to undefined . The type is undefined.
person = undefined; //value is undefined, type is undefined
The difference between Undefined and Null
Example:
typeof undefined //undefined
typeof Null //object
Null = = undefined //false
Null = = undefined //true
JavaScript typeof, null, and undefined