This post was originally published on webinuse.com
Every programming language has its own data structure. Those structures can vary from language to language. Today we are talking about JavaScript data types.
JavaScript is a loosely typed language and dynamic language. This means that any variable can hold any value, regardless of its type, and variables are not directly associated with values type. JavaScript data types are coming in two groups:
- Primitive data type
- Non-primitive data type
JavaScript Primitive data type
We can divide Primitive data types even more. We can divide them into 7 categories. Also, Primitive data types are immutable, and can not be changed. Every data type can store only single data.
1. Boolean
Boolean represents logical entities that can hold only two values: true
or false
. Usually, in JavaScript, we use it for conditionals. We can also assume those for loops.
//Simple JS if statement
if (boolean condition) {
//if boolean condition is true execute this part of code
} else {
//if boolean condition is false (not true) execute this part of code
}
for (control statement; boolean condition; incrementer) {
//only when boolean is met, this part of code will be executed
}
while (boolean condition) {
//while condition is met, this part of code will be executed
}
//
/**
* Let's set value to false
* */
let value = false;
/**
* If value is false (non-existent, binary 0, not true) set value to true,
* otherwise se it to true
* */
if (value === false) {
value = true;
} else {
value = false;
}
for (let i = 0; i < 10; i++) {
//(For as long as condition is true),
//So as long as i is less than 10, this code will be executed
}
while (i < 10) {
//while i is less than 10, this code will be executed
//(While condition is true, this code will be executed)
}
2. Null
In computer science, null represents a pointer to an empty, non-existent address in memory, usually intentionally. In JavaScript null is a little bit different than in other languages. Even though it is marked as a primitive type, it’s not always primitive. Every Object is derived from null.
if(typeof null === 'object') {
console.log('Null is JavaScript object');
} else {
console.log('Null is not JavaScript object');
}
//Result:
//Null is JavaScript object
Nevertheless, in JS, we use null to represent empty or unknown values.
let age = null;
/**
* This means that there is variable called age in our memory,
* but it is empty
* */
3. Undefined
When we create a variable and we don’t give it any value, that variable is undefined. See the example below.
let x;
console.log(x);
//Result:
//undefined
4. String
The string is, probably, the most powerful JavaScript data type, or data type in general. We can create any data type using string, but that doesn’t mean it’s good. The string is a set of “elements” of 16-bit unsigned integer values, as per MDN. The first element, in the string, is at index 0, next is at 1, and so on. The length of the string is a number of elements in the string.
There are three ways to write a string in JavaScript. The first way is using double-quotes "
, the second way is using single-quotes '
, and the third way is using backticks `
. Double and single quotes are basically the same. The only thing is that you have to pair them. So, if you start a string with double quotes, you have to end with double-quotes. And vice versa. Also, inside of double quotes you can use single quotes, and vice versa. If we want to use a variable(s) inside of any of these, you have to use concatenation.
Backticks are different. If we use backticks when we start string, we have to use them at the end, also. But, when we use backticks we can use variables without concatenations. Usually, this leads to better readability.
let hello = "hello";
console.log(hello);
//Result:
//hello
console.log(hello.length);
//Result:
//5
/**
* Let's split string into array to check index
* */
console.log(hello.split(""));
//Result:
/**
* 0: "h"
* 1: "e"
* 2: "l"
* 3: "l"
* 4: "o"
* */
/**
* Examples of using double quotes, single quotes and backticks
* */
let firstString = "String 1";
let secondString = 'String 2';
let thirdString = `String 3`;
let withQuotesInside = "String of a 'string'";
let withSQuotesInside = 'String of a "string"';
let withBackticks = `String of a 'string' of a "string"`;
/**
* Concatenation example
* */
console.log(firstString + ' ' + secondString);
//Result:
//String 1 String 2
console.log(firstString + ' ' + thirdString);
//Result:
//String 1 String 3
console.log(`${firstString} ${secondString} and finally the ${thirdString}`);
//Result:
//String 1 String 2 and finally the String 3
As we can see in the example above, when we use backticks, all we have to do is to enclose a variable in ${}
like ${variable}
.
5. Number
Another JavaScript data type is a number. We can divide Number into two types: Number
and BigInt
. The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(2^53 − 1) and 2^53 − 1). In addition to representing floating-point numbers, the number type has three symbolic values: +Infinity
, -Infinity
, and NaN
(“Not a Number”), as per MDN.
This means that we can “safely” use any number between Number.MIN_SAFE_INTERGER
(-9007199254740991) and Number.MAX_SAFE_INTERGER
(9007199254740991).
Also, the worth of mention, we write numbers without any quotation or backticks, so JS can differentiate them from strings. We can concatenate numbers and strings in JS. The result is another string. If we want to convert a “string” number to the Number we can use parseInt()
or parseFloat()
.
let x = 1;
let y = 2;
console.log(x + y);
//Result:
//3
let z = '1';
console.log(x + z);
//Result:
//11
console.log(x + parseInt(z));
//Result:
//2
6. BigInt
BigInt data type is JavaScript’s way of handling super large numbers. Average programmer, probably, will never get even close to MAX_SAFE_INTERGER
, still, there are some situations where we might need BigInt
. BigInt
is not strictly a number. Also, Number
and BigInt
can’t be used together or interchangeably. These are two different “identities”.
We create BigInt
by appending n
at the end of the integer, or by calling the constructor. We can use +
,-
,*
,/
, and %
with BigInt
just like with numbers.
let BigInt = 9007199254740991n;
//Add to BigInts
console.log(BigInt + 1n);
//Result:
//9007199254740992n
//Add a BigInt and a Number
console.log(BigInt + 1);
//Result:
//ERROR: Cannot mix BigInt and other types, use explicit conversions
7. Symbol
The symbol is a feature introduced in ECMA Script 2015. Symbol is a secret, unique, anonymous value. Symbol value represents a unique identifier, it can, also, have optional descriptions, but for debugging purposes only. Even if we create an infinite number of Symbols with the same descriptions, every one of them will be unique. We can use Symbol as an object property. For more info on Symbol click here.
let first = Symbol("Symbol");
let second = Symbol("Symbol");
/**
* Even though they are the same, they are different because
* they are Symbol type.
* */
//If we try to compare two symbols we' ll always get false
if (first === second) {
return true;
} else {
return false;
}
//Result:
//false
JavaScript non-primitive data type
Unlike primitive data types, non-primitive data type is mutable. This means that non-primitive data type can hold different data types, one or more of them, at the same time. There is only one “real” representative of non-primitive data type. It’s called Object.
Object
Usually, an object
is a value in memory that is represented by an identifier. An object
is a complex data type that allows us to store and manipulate the same and/or different data types. Also, In JavaScript, there are different types of object
.
The first type is “standard” object
. object
consists of key-value pairs, where the key is a unique identifier.
let person = {
name: 'Amer',
surname: 'Sikira',
years: 28
}
console.log(person);
//Result:
//{name: "Amer", surname: "Sikira", years: 28}
The second type of the object
is array
. array
is object
type that consists of values and we access those values using index-key. If you want to learn more about array you can check out my post JavaScript Arrays – Manipulating data.
let cars = ['Volvo', 'Ferrari', 'Audi'];
//We can have multi-level arrays
let items = [1, 'ball', false, true, 332, ['audi', 'volvo', 'train']];
There are some other object types like RegEx, Date, etc. You can read more about it on MDN.
Typeof
JavaScript data types can be pretty complicated. That is why we have typeof
operator. typeof
operator returns a string indicating the type of the operand. When we want to check if certain variable or data is right type we can use typeof
.
Also if we want to compare two (or more) operands in JavaScript, we can use double equation sign ==
. JavaScript will check if they are equal. But, if we use triple equation sign ===
JS will also check if their type is the same.
let x = 'Hello, World!';
let y = 22;
console.log(typeof x);
//string
console.log(typeof y);
//number
//Check for equality
let a = 2;
let b = '2';
let c = 2;
console.log(a==b);
//true
console.log(a===b);
//false
console.log(a===c);
//true
If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like What is JavaScript used for?
Top comments (2)
Thanks for this awesome article :)
Thank you for such kind words. I really appreciate it.