JavaScript primitive data types
Dawx
Posted on November 1, 2021
Every programming language has data types. In JavaScript, there are 8 data types that can be grouped into two categories: primitive values and objects.
Primitive values are data types that are immutable (can't be changed). If you come from another programming language like C, this might be something new to you.
For example, in C you learned that string is an array of chars, and you could change each char. Code below in C would change string to "boop", but in JavaScript stays "loop" because the string is a primitive value that can not be changed.
Here is the list of all primitive values:
- Boolean
- Null
- Undefined
- Number
- BigInt
- String
- Symbol
Everything that doesn't have type one of the primitive values is type of object. For example, common mistake is checking type of date, which doesn't exist and is always false.
As you can see, date is actually type of object.
Boolean
Boolean is a logical data type that can have two values: true
or false
. Its mostly used in if statements and loops to conditionally execute code based on truthness of an expression.
Note that expressions are also type of boolean (2>3) and can be true or false.
Also true and false aren't same as "true" and "false", later ones are type of string.
Null and undefined
Null represents the intentional absence of object value. If you check it's type you will notice it actually isn't type of null, but actually type of object. Its used when you expect an object returned, but instead you get returned nothing.
On the other hand, undefined is assigned to variables that have just been declared. It represent lack of value. Unlike null, its type if actually same as its name - undefined.
Number and BigInt
There are two numeric types in JavaScript: number and BigInt.
There aren't other types of numbers in JavaScript. If you come from other programming languages, you probably used float, decimal, double...
In JavaScript, all of those mentioned above are type of number:
The maximum number of decimals is 17 and integers are accurate up to 15 digits.
BigInt represents integers with arbitrary precision, it is used to store and do operations on large integers (larger than type number supports).
It is created by adding "n" at the end of an integer.
String
A String is used for textual data, it is a set of values, just like in other programming languages. The difference being they are immutable. Despite that, you can still access each element of the string. Each element has an index, starting from 0 to n-1, n being the length of a string.
Symbol
A Symbol is a unique and immutable primitive value and may be used as the key of an Object property.
const person = {name: "Jon"};
In the example above, "name" is the key of the "person" object and it has a value pair of "Jon".
Thank you for reading this article!
Posted on November 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.