JavaScript Data Types
Every value in JavaScript has a data type. JavaScript is dynamically typed, which means a variable can hold any type, and the type can change.
Primitive types
| Type | Example |
|---|---|
| String | "Hello", 'Hi', `Hey` |
| Number | 42, 3.14, -7 |
| Boolean | true, false |
| Undefined | A variable with no value yet |
| Null | An empty value on purpose |
| BigInt | 12345678901234567890n |
| Symbol | A unique identifier (advanced) |
Objects
Everything that is not a primitive is an object: arrays, functions, dates and plain objects.
let name = "Robin"; // string
let age = 25; // number
let isStudent = true; // boolean
let city; // undefined
let empty = null; // null
let colors = ["red", "green"]; // object (array)
let user = { name: "Robin", age: 25 }; // object
The typeof operator
console.log(typeof "Hello");
console.log(typeof 42);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof [1, 2]);
console.log(typeof { a: 1 });
console.log(typeof function () {});
console.log(typeof 10n);
Output of the above program is
string
number
boolean
undefined
object
object
object
function
bigint
Notice two surprises. typeof null gives "object", which is an old bug of the language. And an array also gives "object". To check for an array use Array.isArray().
console.log(Array.isArray([1, 2]));
console.log(Array.isArray({ a: 1 }));
Output of the above program is
true
false
undefined and null
undefinedmeans “no value has been given yet”.nullmeans “there is no value”, set by the programmer.
Note:
JavaScript has only one number type for both integers and decimals. Learn more in Numbers and Math.
Summary
- Primitive types: string, number, boolean, undefined, null, bigint, symbol.
- Arrays, functions and objects are objects.
- Use
typeofto check a type, andArray.isArray()for arrays. - Next: JavaScript Type Conversion.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write a JavaScript program to add two numbers |
| Write a JavaScript program to swap two variables |