The Ultimate Guide to Data Types in JavaScript

The Ultimate Guide to Data Types in JavaScript

In the previous article, we studied about what variables and constants are in JavaScript, and how we declare them. In this article, let's try to go deep into data types and understand each one with examples.

Now, the basic question is, What are data types? The data type is a classification of data according to the type of value that we want to operate on.

Now, it's important to understand that JavaScript is a dynamically typed language, which means the data type is defined by the engine itself during execution, the programmer need not explicitly declare the data type during defining. JavaScript engine is powerful enough to determine the type of data that we declare.

Following are the data types of JavaScript:

  • null
  • undefined
  • boolean
  • number
  • string
  • symbol
  • object

Let's test drive...

typeof undefined==="undefined"; //true
typeof true==="boolean"; //true
typeof 90==="number"; //true
typeof "90"==="string"; //true
typeof {lucky_number:3}==="object"; //true
typeof null //object
typeof a ==="object"; //true
typeof symbol()==="symbol"; //true

In JavaScript, data types are categorised into two according to their behaviour:

  1. Primitive data type
  2. Reference data type

JavaScript Data Types

Primitive

Primitives define immutable values and were introduced lately by the ECMAScript standard. They are fundamental data types and they are built in JavaScript. Its memory is allocated in the stack, such data is very quick to access and it stores limited data.

Some widely used primitive data types are:

  • null
  • undefined
  • boolean
  • number
  • string
  • symbol

#1. Strings

A string is a primitive data type used to represent and manipulate the sequence of characters, usually text data. JavaScript strings are immutable, which means they cannot be altered. Anything enclosed between " " (double quotes) can be termed as a string. Although you can also enclose strings between ' ' (single quotes), both are practically the same and you can use either of them.

There are many methods to manipulate strings, but let's study a few of them:

1.1 indexOf

The indexOf() method returns the position of the first occurrence of a value in a string. It will return -1 if the character is not found.

Syntax:

string.indexOf(searchvalue, startfromindex)

Example:

var a= awesome;
a.indexOf("w");  //1
a.indexOf("e");  //2 , it'll return the first occurrence only
a.indexOf("e",4);//6, here start point is from 4th character

1.2 replace()

replace() is another widely used method in JavaScript. This method returns a new string with replaced values in it.

Syntax:

string.replace(current character, new character)

Example:

let quote = "Coding Minutes is great";
let newQuote = quote.replace("great", "awesome");// Coding Minutes is awesome

JavaScript var let const


1.3 concat()

The concat() method joins two or more strings and returns a new string.

Syntax:

string.concat(string1, string2, ..., stringn)

Example:

let quote1= "I have not failed.";
let quote2= "I’ve just found 100";
let quote3= "ways that won’t work.";
let outcome= text1.concat(quote1," ", quote2, " ", quote3);// I have not failed. I've just found 100 ways that won't work.

1.4 toUpperCase() and toLowerCase()

toLowerCase() method converts upper case characters to lower case letters. toUpperCase() method converts lower case characters to upper case letters.

Syntax:

string.toLowerCase() // lower case
string.toUpperCase() // upper case

Example:

let name = "Coding Minutes";
let output= name.toLowerCase(); // coding minutes

let name = "Coding Minutes";
let output= name.toUpperCase(); // CODING MINUTES

These are a few methods of strings. For all the methods, visit this link.

#2. Number

With the help of number datatype, we can store numeric values. They can be integer values or fractional decimal values. JavaScript numbers are formatted in the "IEEE 754" standard, and in common terms, it is also known as "Floating point" number representation.

It's very interesting to understand how Decimal and Binary numbers are encoded by the machine. For more information about IEEE 754 refer here.

Syntax:

let container = value;

Example:

let a = 100;
let b = 100.11;

We can represent larger numbers with the help of 'e'. For example:

let x = 312e5;    // 31200000
let y = 312e-5;   // 0.00312

JavaScript Number too has properties and methods to manipulate numbers:

2.1 MAX_VALUE

Number.MAX_VALUE returns the largest number attainable in JavaScript.

let x = Number.MAX_VALUE;
console.log(x); //1.7976931348623157e+308

It is a fixed value, which is also termed a "Static Value".

Number = 1;
console.log(Number.MAX_VALUE); //undefined

It'll return a special keyword called "undefined", this undefined is a very pivotal role to play in JavaScript, which we'll discuss in the later part of the series. This Number.MAX_VALUE does the job of providing the maximum possible extent to which JavaScript can represent numbers.

2.2 MIN_VALUE

Number.MIN_VALUE returns the smallest number attainable in JavaScript.

Example:

let y = Number.MIN_VALUE;
console.log(y); //5e-324

The same is the case with MIN_VALUE. It's a static value, it does the job of announcing the minimum possible value in JavaScript.

2.3 POSITIVE_INFINITY

This property returns 'Infinity" at the time of positive overflow.

Example:

let a = -1 / 0;
console.log(a); //Infinity

2.4 NEGATIVE_INFINITY

This property returns '-Infinity" at the time of negative overflow.

Example:

let a = -1 / 0;
console.log(a); //-Infinity

2.5 NaN

NaN will amaze you. Its abbreviation states 'Not a Number'. It conveys that the syntax that we are trying to use does not make any sense. Here are some cases where we might end up getting NaN:

Case #1: When JavaScript is unable to convert the result into a number

let myName = 'Lily';
let divideMyName= myName/100;
 console.log(divideMyName); //NaN

Case #2: We are trying to figure out the result where the operation does not return a real number.

Example:

Math.sqrt(-1); // NaN

Case #3: Indeterminate forms in mathematics result in NaN.

Example:

let a = 0 * Infinity;
let b = 1 ** Infinity;
let c =  Infinity / Infinity;
let d =  Infinity - Infinity;

console.log(a);
console.log(b);
console.log(c);
console.log(d);

Here is the way to check if your operation is NaN, by using the isNaN property:

let num= Infinity/Infinity;
Number.isNaN(num); // true

Here are a few methods to manipulate the number data type in JavaScript:

2.6 toString()

The toString() method returns a number as a string.

Example:

let x = 123;
x.toString();// 123

2.7 toFixed()

toFixed() returns a string, with a number with a specified number of decimals.

Example:

let pi = 3.141592653589793238462643;
pi.toFixed(0);// 3
pi.toFixed(2);// 3.14
pi.toFixed(4);// 3.1416

2.8 toPrecision()

toPrecision() returns a string, with a number with a specified length.

Example:

let sigma = 6.6524587321;
sigma.toPrecision(2);//6.7
sigma.toPrecision(6);//6.65246

JavaScript var let const


#3. Boolean

We use boolean values to find whether the value returns true or false. It is also used in the conversion of very specific values to true or false values.

Here is the list of values which upon conversion will result in true or false values.

Boolean True vs False in JavaScript

Example:

let a = 0;
Boolean(a); //false

let b= 45;
Boolean(b); //true

let c;
Boolean(c); // false as it is undefined value

let d= 'lily'/100;
Boolean(d); // false as it returns NaN

20 > 30// false

30 > 20 //true

30 = 30 // Uncaught SyntaxError: Invalid left-hand side in assignment. '=' is used only to assign a value not to check the boolean value.

30 == 30 // true
30 === 30 //true

Here comes one of the specialities of JavaScript

7==='7' //false

7=='7' //true

How is it possible? Let's understand this in detail in the next article 'operators', but for now just understand that == is 'loose equals', and === is 'strict equals'.

#4. Null

One of the most interesting data types in JavaScipt, it represents the "absence" of a certain value. Null is one of the false values in JavaScript. This is interesting because JavaScript implementors made a slight mistake while defining typeof null. Null is not an object. However, this bug cannot be fixed and we will have to live with it.

Let us see some examples to understand null:

typeof null // object

let a = null     
console.log(a) // null

let a = null
console.log(a  === null) // true

let a = null
console.log(a == null) //true

Remember, null is a special keyword, not an identifier. It cannot be assigned to a variable.

#5. Undefined

Undefined is an identifier. A variable that has not been assigned any values of type undefined.

Example:

let a
console.log(a); //undefined

if (a === undefined){
    console.log(" a is undefined")
}
else{
    console.log(" a is not undefined ")
} 
// a is undefined

Let's study more about undefined and its use cases when we discuss execution context. It's weird why we just declare a variable but did not initialise, it has a jaw-dropping use case in JavaScript execution Context.

Undefined vs Null

It's very important to observe and understand the differences between undefined and null.

Let's write direct code to observe their use cases which will give a good amount of idea about their difference.

let a
console.log(a); // undefined

let b = null
console.log(b); //null

typeof null // object
typeof undefined // undefined

console.log( undefined == null); // true
console.log( undefined === null); // false

console.log(1 + null); // 1 . In math, null is treated as zero
console.log(1 + undefined); // NaN

Null is an empty value, null must be assigned. Undefined means a variable has been declared but it yet to be initialised by any value.

#6. Symbol

This is a new data type, added in ES6. Symbols are unique values which are used as properties. The symbol data type is used to define your own symbol.

Example:

let symb= symbol()
typeof symb // symbol

Every symbol call returns a unique symbol, observe below...

let symb1 = symbol(" Coding Minutes is the best ")
let symb2 = symbol(" Coding Minutes is the best ")
console.log(symb1 == symb2); // false

JavaScript considers each symbol as a unique value. It always returns false upon equality operation. The motivation behind adding symbol in ES6 is to support unique object keys, it was difficult to create unique object keys before the symbol.

So, that was about primitive data types. Let us now try to understand non-primitive data types i.e object.

Object

The object is the most important data type in JavaScript, Modern JavaScript deals a lot with objects. It's important to understand that functions and arrays are subtypes of object.

We have different ways of creating and representing an object

#1. Object literal

Syntax:

object={property1:value1, property2:value2 .....propertyN:valueN}

Example:

phone = {color: "blue" ,internal_storage :"16GB",display: "5.5inch"}  
console.log(phone.color+" "+phone.internal_storage+" "+phone.display); // blue 16GB 5.5inch

#2. Instance of an object

Syntax:

let objectname=new Object();

Example:

var phone = new Object();  
phone.color = "blue";  
internal_storage = "16GB" 
display = "5.5inch"
console.log(phone.color+" "+phone.internal_storage+" "+phone.display); // blue 16GB 5.5inch

#3. Object Constructor

Here this acts as an object constructor of an object. This keyword has a lot to talk about, one needs to understand execution context, window object etc. Let's deal with this, in basic terms in this article.

Example:

function phone(color,internal_storage,display){  
this.color=color;  
this.internal_storage=internal_storage;  
this.display=display;  
}  
phn=new phone("blue","16GB", "5.5inch");  
console.log(phn.color+" "+phn.internal_storage+" "+phn.display);  // blue 16GB 5.5inch

Here are a few object methods to discuss:

#1. object.values()

This method returns an array of values in the object.

Example:

const lily = {  
  name: 'lily',  
  class: 10,  
  height: "5.3feet"  
};  
console.log(Object.values(lily));  // ["lily", 10, "5.3feet"]

#2. Object.entries()

This method returns key-value pairs in terms of an array.

Example:

const fruit = { 1: 'apple', 2: 'cherry', 3: 'berry' };  
console.log(Object.entries(fruit)[2]);  // ["3", "berry"]

#3. Object.keys()

This method returns an array of values in the object.

Example:

let veggies = {a: 'brinjal',b: 'Cabbage',c: 'beetroot'};

console.log(Object.keys(veggies)); //["a", "b", "c"]

Conclusion

In this article, we discussed data types in and required methods and properties. It's very important to understand data types in any language as they will form the building block to learning the language. Unlike any other programming language, JavaScript has slightly different data types which require a good amount of attention to understand. It is advisable to understand each data type thoroughly and practice each one of them to gain confidence as a programmer. In the next article, we will learn about operators in JavaScript in-depth.


JavaScript var let const