DEV Community

M.Ark
M.Ark

Posted on

JavaScript Data Types

JavaScript has the primitive data types:

  1. null
  2. undefined
  3. boolean
  4. number
  5. string
  6. symbol – available from ES2015
  7. bigint – available from ES2020 and a complex data type object.

Image description

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
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (0)