In this post, we will learn about most important data types in JavaScript and their characteristics. Data types describe the different types or kinds of data. These data types are similar in almost all programming languages. Data types have their own importance in any programming language. These data are stored in variables.


Most Important Data Types in JavaScript


There are 8 types of data in JavaScript:

  1. Number: integer or floating-point
  2. String: represent textual data
  3. BigInt: large integers
  4. Boolean: true or false
  5. Undefined: not initialized value
  6. Null: denotes an empty value
  7. Object: key-value pairs of collection of data
  8. Symbol: represents data whose instances are unique and immutable (can't be changed)


All data types except Object are primitive data types, whereas Object is non-primitive because it can store collections of data. Primitive data types can only store a single data.


Now we are going to describe each data type by its syntax, operations or methods and how to use each data types.


Number

The number data type is used for integer and floating points numbers. JavaScript numbers are always 64-bit floating-point, where the number is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign-in bit 63.


Syntax

const num1 = 123; // Literal declaration

const num2 = Number(123); // Using the Number constructor

const num3 = Number.parseInt("123.45"); // Conversion to integer

const num4 = Number.parseFloat("1.23e2"); // Conversion to float

const num5 = +"123"; // unary conversion to number code-box


Operations

We can also perform some built-in operations on number:


const a = 12;

const b = 34;

// addition

a + b; // 46

// subtraction

a - b; // -22

// multiplication

a * b; // 408

// division

a / b; // 0.35294117647058826

// exponentiation

b ** a; // 2386420683693101000

// increment

a++; // 13

// decrement

b--; // 33

// modulus (remainder of the division)

b % a; // 10 code-box


Specific numeric values

These specific numeric values are just "Infinity", "-Infinity" and "NaN".

  • Infinity represents the mathematic Infinity.
  • NaN (Not a Number) is the result of incorrect or undefined mathematical operations.


console.log(8 / 0); // Result: Infinity

console.log("Hello", / 5); //Result: NaN code-box


How to check for number type

To check for number type, we use "typeof" operator. If the variable is a number, it'll return "number".


const n = 314;

const d = 3.14;

typeof n; //Result: "number"

typeof d; //Result: "number" code-box


Silly mistakes

We often make mistakes when working with numbers and strings. We should know these rules so that we do not make these mistakes again and again.

  • JavaScript uses the + operator for both addition and concatenation.
  • Numbers are added and strings are concatenated.
  • Adding a number and a string will result in a string concatenation.



BigInt Data Type

BigInt is a recent data type (introduce in ES2020). The "number" data type cannot represent integer values respectively larger or less than 2*53 - 1 or - (2*53 - 1). A BigInt value is created by appending "n" to the end of the integer.


Syntax

const a = 2n;

const n = 1234567890n; code-box


Operations

We can also perform operations like a number on BigInt.

const a = 12n;

const b = 34n;

// addition

a + b; // 46n

// subtraction

a - b; // -22n

// multiplication

a * b; // 408n

// division

a / b; // 0.35294117647058826n

// exponentiation

b ** a; // 2386420683693101000n

// increment

a++; // 13n

// decrement

b--; // 33n

// modulus (remainder of the division)

b % a; // 10n code-box


Comparisons and Boolean operations

  • Comparisons such as < and >, work with BigInts and numbers just well.
  • But note that numbers and bigints can be equalt "==",but not strictly equal "===".
  • Operators such as "||" or "&&" works on bigints similar to numbers


console.log(2n > 1n); // => true

console.log(2n > 1); // => true

console.log(2n == 2); // => true

console.log(4 === 4n); // => false code-box


How to check for bigint type

To check for bigint type, we use "typeof" operator. If the variable is a bigint, it'll return "bigint".


const a = 2n;

typeof a; // Result: "bigint" code-box


Things to keep in mind

We should keep in mind these things, when we working with bigint:

  • Only use bigint when values are greater than 2**53.
  • The operations supported on BigInts are not constant time. BigInt is therefore unsuitable for use in cryptography.
  • Use TypeScript with bigint to reduce the production of TypeErrors.



String

A string in JavaScript represents textual data. A string in JavaScript is always surrounded by quotes (single quotes or double quotes) and backticks(``).


Syntax

let singleQuotes = 'Single Quotes';
let doubleQuotes = "Double Quotes";

let str = "Using backticks with string";
let backticks = `Here, ${str}`;

console.log(backticks); // Result: "Here, Using backticks with string." code-box


String properties and methods

There are many properties and methods, which are used on strings. Some are as follows:

str.length = returns string length.

str.indexOf(subStr, pos) = looks for a substring within a string.

str.includes(subStr, pos) = true/false if the string contains subStr within.

str.startsWith and str.endswith = do exactly what they say.

str.substring(start, end) = returns the part of str between start and end

str.substr(start, end) = returns the part of str from start, with the given length

str.slice(start, end) = returns the part of str from start to end (not included).


let str = "CodexRadar";

str.length; // Result: 5

str.indexOf("C"); //Result: 0

str.includes("Codex"); //Result: true

str.includes("b"); //Result: false

str.startsWith("Code"); //Result: true

str.endsWith("r"); //Result: true

str.substring(0, 2); //Result: "Co"

str.substr(0, 2); //Result: "Co"

str.slice(2,4); //Result: "de" code-box


Accessing characters

Keep in mind that the first character starts form the zero position. There are two methods for accessing characters:

  1. To get a character at position 'index', use square brackets [].
  2. We can also use the method str.charAt(index).


let str = "CodexRadar";

str[0]; //Result: "C"

str.charAt(0); //Result: "C" code-box


Things to keep in mind

Strings are immutable (can't be changed) in JavaScript. It's impossible to change a character. We can use str.replace(oldChar, newChar) to return a new string with the oldChar replaced by newChar.


let str = "Hello World!";

str = str.replace("ll", "bb");

console.log(str); //Result: "Hebbo World!" code-box



Boolean

The boolean is mainly used for comparisons. The boolean type in JavaScript has only two values: true or false.


Syntax

let a = 2;

let b = 4;

a > b; //Result: false code-box


Comparisons

Boolean values comes as a result of comparisons in JavaScipt.

 ===   strictly equal to

 !==   strictly not equal to

 >    greater than

 <   lighter than

 >=  greater than or equal to

 <=   lighter than or equal to


console.log(1 === 1); //Result: true

console.log(1 > 2); //Result: false

console.log(1 < 2); //Result: true code-box


Logical Operators

OR =  ||  (Returns true if one operand is true and false if none are true.)

AND =  &&  ( Returns true if both operands are truthy and false.)

NOT =  (converts the operand to boolean type and return the inverse value) operand.


let a = true;

let b = true;

let c = false;

a || b; //Result: true

a || c; //Result: true

a && b; //Result: true

a && c); //Result: false code-box


Things to keep in mind

We can also use  ==  (equal to) and  !=  (not equal too) to make comparisons. But strict operators ( ===  and  !== ) compare value and types.

let a = 1; //type number

let b = "1"; //type string

a == b; //Result: true

a === b; //Result: false code-box



Null

Null means nothing. Null is just a value in JavaScript. We can assign  null  to a variable and when we check for that variable value then we get null.


Syntax

let var = null;

console.log(var); //Result: null code-box


How to check for null?

If we want to check whether the value of a variable is  null  or not, we use the strict operator  ===  for this. The boolean value of  null  is false. If the value of the variable is  null  then we get false in the result.


let var = null;

console.log(var === null ); //Result: true


if (var) {

console.log("var is true.");

} else {

console.log("var is false.");

}
//Result: var is false. code-box



Undefined

 undefined  is returned for the following reasons:

  • When a variable hasn't been initialized.
  • When accessing a non-existing object property.
  • When accessing a non-existing index value in array.
  • When a function returns nothing.


Syntax

//When a variable hasn't been initialized.

var a;
console.log(a); //Result: undefined

//When accessing a non-existing object property.

var fruit = { name: 'Mango' };
console.log(fruit.color); //Result: undefined

//When accessing a non-existing index value in array.

var fruits = ["Orange", "Banana", "Mango"];
console.log(fruits[3]); // => undefined

//When a function returns nothing.

function sum(a, b) {
var sumNumbers = a + b;
};
sum(4 + 8); // => undefined code-box


How to check for undefined?

If we want to check whether the variable is  undefined  or not, we use the strict operator  ===  for this. The boolean value for  undefined  is false. If the variable is  undefined  then we get false in the result.


let var;

console.log(var === undefined ); //Result: true


if (var) {

console.log("var has value.");

} else {

console.log("var is undefined.");

}

//Result: var is undefined. code-box



Object

An object is a non-primitive, structured data type in JavaScript. Objects are same as variables in JavaScript, the only difference is that an object holds multiple values in terms of properties and methods. 


We use  const  keyword to declare objects. In JavaScript, array is also object.


Syntax

We create object in JavaScript in two ways:

  1. Using object literal  { }  
  2. Using the object constructor function with the  new  keyword


// Using Object literal

const city = {

name: "Paris",

population: 1000,

getCityInfo: function() {

return this.name + ', ' + this.population;

}

};


// Using Object constructor

let city = new Object();

city.name = "Paris";

city.population = 1000;

city.getCityInfo = function() {

return this.name + ', ' + this.population;

}; code-box


Accessing properties

We can access the object properties in the following ways:

  • via the dot notation
  • via the bracket [ ]  notation


city.name; //Result: "Paris"

city["name"]; //Result: "Paris"

city.getCityInfo(); //Result: "Paris, 1000" code-box



Symbol

The JavaScript ES6 introduced a new primitive data type called  Symbol  . Symbols are immutable (can't be changed) and are unique. We can pass an optional string as its description


Syntax

We use the  Symbol()  function to create a symbol.

// two symbols with the same description

const value1 = Symbol('hello');

const value2 = Symbol('hello');

console.log(value1 === value2); //Result: false code-box


value1 and value2 both contain the same description but they are different.


Access symbol description

To access the description of a symbol, we use the dot operator.


const x = Symbol('hey');

console.log(x.description); //Result: hey code-box


Add Symbol as an Object Key

We can add symbol as a key in an object using square brackets.


let id = Symbol("id");

let person = {

name: "Jack",

// adding symbol as a key

[id]: 123 // not "id": 123

};

console.log(person); //Result: {name: "Jack", Symbol(id): 123} code-box


Benefit of Using Symbols in Object

If the same code snippet is used in various programs, then it is better to use  Symbol  in the object key. It's because you can use the same key name in different codes and avoid duplication issues.



Summary

In this post, we learned most important data types in JavaScript. Hope you have understood it better. Keep visiting for more such great posts. If you have any suggestion or question then tell us in comment section.

Post a Comment

Previous Post Next Post