Javascript Data Types
In Javascript, there are total of 8 data types.
String, Number, Boolean, BigInt, Undefined, Null, Object, and Symbol.
We can put different data types in the same variable. A variable can be a string and in another line, it can become a number. Javascript is a dynamically typed language that allows us to do that.
1. String
string
in Javascript is surrounded by quotes. And they are immutable.
In Javascript, we can write strings in different ways.
Double Quotes
let doubleQuotes = "Hello World";
Single Quotes
let singleQuotes = 'hello World';
Backticks
let backTicks = `hello World`;
A special feature of backticks is it lets you use variables and expressions inside a string by wrapping them in ${}
let str = `hello`;
let special = `${str} World`;
console.log(special); //hello World
2. Number
number
type lets you store integer and floating point numbers.
let integerNum = 123;
let floatingPoint = 123.4;
You can do various math operations with numbers e.g addition, subtraction, multiplication, and division. You can store special numeric values too like infinity
, -Infinity
and NaN
which is short for Not a Number.
3. Boolean
The boolean
type has only two values true
and false
. true
means correct and false
means incorrect.
let a = 3;
let b = 4;
console.log(a > b); //false
4. BigInt
In Javascript, a number
type cannot safely store a number larger than (253-1) or less than -(253-1) . To store a bigInt value append n to the end of an integer.
let bigInt = 3453453453453453463465465654654n;
5. Null
null
type in Javascript is a special data type as its name suggests. It means null, nothing, empty.
let nullType = null;
6. Undefined
Just like null undefined
is also special. Any variable which is declared but isn't assigned any value is undefined.
let undefinedValue;
console.log(undefinedValue); //undefined
7. Object
Objects are keyed collections of various data. The above data types we learned are called primitive data types because they can store only one type but the object is a little different. Objects can store values of different types.
let obj = {
name: 'John', //string
age: 30, //number
};
```
You can only use ```string```, and ```Symbols``` as object property keys.
Using any other type gets converted to a string.
```
let obj2 = {
name: 'John',
1: 30,
};
console.log( obj2['1']) //30
console.log(obj2[1]) //30 same as '1';
```
## 8. Symbols
Symbols are used to make unique identifiers.
Symbol type can be made using ``` Symbol()```
we can give descriptions in Symbols.
```
let sym = Symbol('description');
```
Even if two symbol store the same description they are not equal.
```
let a = Symbol('id');
let b = Symbol('id');
console.log(a === b); //false
```