JavaScript offers eight basic data types:
To easily remember them, learn the mnemonic: NUNBBOSS, which stands for Null, Undefined, Number, Boolean, BigInt, Object, String, Symbol.
Now that we know there are eight data types, let's explore what these data types are used for:
/* | |
NULL: | |
- Used to represent "nothing", "value unknown" or "empty". | |
- We use null intentionally for missing values. | |
- Null is not used to reference a "non existing object" | |
*/ | |
let address = null; | |
/* | |
UNDEFINED: | |
- The meaning of undefined is "value is not assigned". | |
- We use undefined intentionally for missing values. | |
*/ | |
let age; | |
/* | |
Number: | |
- Represent both integer(whole numbers) and floating point numbers (decimals). | |
- Used for math calculations. | |
- There are some special numeric values: Infinity, -Infinity, NaN (Not a Number). | |
*/ | |
let weight = 150; | |
weight = 150.55; | |
/* | |
Boolean: | |
- Has two possible values: true or false | |
- used for logical operations | |
*/ | |
let isChecked = true; | |
var isVerified = false; | |
/* | |
BigInt: | |
- Number cannot represent values larger than 2^53 - 1 or smaller than -2^53 - 1. | |
- BigInt allow us to use really large numbers without limitations. | |
- We create a BigInt by appending 'n' to the end of an integer. | |
*/ | |
const bigNumber = 987654321987654321987654321n; | |
/* | |
Object: | |
- Objects are used to store collections of data by using keys and values. | |
*/ | |
let user = { | |
name: "John", | |
age: 31, | |
occupation: "Software Developer", | |
}; | |
/* | |
String: | |
- Used for text and represented by quotes | |
- Strings can be represented by "", '', `` | |
*/ | |
let name = "Chris"; | |
/* | |
Symbol: | |
- Used for unique identifiers | |
- Often used to add unique property keys to an object | |
*/ | |
const symbol = Symbol("foo"); |
Of the eight data types, seven are primitive. The term “primitive” means that a data type can contain only a single value. All primitive types are immutable, and we cannot set properties on them.
Objects are the only non-primitive type because they are used to store collections of data and more complex entities.
You might be thinking, “Hey, but I heard that everything in JavaScript is an object! If a string is not an object, how come I can do the following:
"hi".toUpperCase(); // HI |
This logic makes the string “hi” appear as if it were an object because we are using a method on it. This is an illusion! JavaScript creates a temporary object when we want to use a method for a primitive type and then immediately discards it!