JavaScript has the primitive data types:
- null
- undefined
- boolean
- number
- string
- symbol – available from ES2015
- bigint – available from ES2020 and a complex data type object.
JavaScript is a dynamically typed language. It means that a variable doesn’t associate with a type. In other words, a variable can hold a value of different types. For example:
let counter = 20; // counter is a number
counter = false; // counter is now a boolean
counter = "foo"; // counter is now a string
To get the current type of the value that the variable stores, you use the typeof operator:
let counter = 20;
console.log(typeof(counter)); // "number"
counter = false;
console.log(typeof(counter)); // "boolean"
counter = "Hi";
console.log(typeof(counter)); // "string"
The output is
"number"
"boolean"
"string"
The undefined type
The undefined type is a primitive type that has only one value undefined. By default, when a variable is declared but not initialized, it is assigned the value of undefined.
For example:
let counter;
console.log(counter); // undefined
console.log(typeof counter); // undefined
In this example, the counter is a variable. Since counter hasn’t been initialized, it is assigned the value undefined. The type of counter is also undefined.
It’s important to note that the typeof operator also returns undefined when you call it on a variable that hasn’t been declared:
console.log(typeof undeclaredVar); // undefined
Top comments (0)