1.18.1 • Published 5 months ago

learn-javascript v1.18.1

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

Learn JavaScript

This repository contains a list of JavaScript concepts, functions, methods, and other important topics that are essential for every JavaScript developer to learn. It is a comprehensive guide that covers all the basic and advanced concepts of JavaScript.

npm npm npm npm GitHub repo size

GitHub

Table of Contents

Introduction

JavaScript is a scripting language. It is object-based, lightweight, cross-platform translated language. It is widely used for client-side validation.

Add JavaScript

There are three ways to add JavaScript to a web page:

  1. Inline JavaScript - It is used to add JavaScript directly to the HTML document. It is added inside the <script> tag in the HTML document.

  2. Internal JavaScript - It is used to add JavaScript to the HTML document. It is added inside the <script> tag in the <head> or <body> section of the HTML document.

  3. External JavaScript - It is used to add JavaScript to the HTML document. It is added in a separate file with a .js extension and linked to the HTML document using the <script> tag.

JavaScript in <head> -

<!DOCTYPE html>
<html>
<head>
<script>
    //code
</script>
</head>
<body>
<h2>Heading</h2>
</body>
</html>

JavaScript in <body>

<!DOCTYPE html>
<html>
<body>

<h2>Heading</h2>

<script>
    //code
</script>

</body>
</html>

External JavaScript -

<!DOCTYPE html>
<html>
<body>

<h2>Heading</h2>

<script src="myScript.js"></script>
</body>
</html>

Back to Top⤴️

Outputing JavaScript

JavaScript can "display" data in different ways

1. Writing into an HTML element, using innerHTML

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>

2. Writing into an HTML element, using document.write()

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

3. Writing into an alert box, using window.alert()

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>

4. Writing into the browser console, using console.log()

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

Back to Top⤴️

Single Line Comments

Single line comments start with //

// comments

Multi-line Comments

Multi-line comments start with /* and end with */.

/* Hey!
Hello, How are you?
*/ 

Back to Top⤴️

Variables

Variables are containers for storing data values. In JavaScript, variables are declared using the var, let, or const keyword.

Declare Variables

There are three ways to declare variables in JavaScript:

1. var - It is used to declare a variable. It is function-scoped.

var a = 1; // Declare a variable x with the value 1 (function-level scope).

2. let - It is used to declare a variable. It is block-scoped.

let b = 1; // Declare a variable y with the value 10 (block-level scope).

3. const - It is used to declare a read-only variable. It is block-scoped.

const c = 1; // Declare a read-only variable z with the value 15 (block-level scope).

Back to Top⤴️

Data Types

Data types are used to define the type of data that a variable can store. JavaScript is a loosely typed language, which means that you do not have to declare the data type of a variable when you declare it.

There are two types of data types in JavaScript:

  • Primitive Data Types
  • Non-Primitive Data Types

1. Primitive Data Types

Primitive data types are the most basic data types in JavaScript. They are immutable (cannot be changed) and are copied by value.

Primitive data types include:

  • numbers
  • strings
  • booleans
  • null
  • undefined
  • symbol

numbers - numbers can be written with or without decimals.

let number = 10;

strings - strings are text. They are written inside double or single quotes.

let name = "Manthan";

booleans - booleans can only have two values: true or false.

let value1 = true;
let value2 = false;

null - null is an empty value.

let value = null;

undefined - undefined means a variable has been declared but has not yet been assigned a value.

let name;

symbol - symbols are unique and immutable values.

let a = Symbol();

Back to Top⤴️

2. Non Primitive Data Types

Non-primitive data types are complex data types that are mutable (can be changed) and are copied by reference.

Non-primitive data types include:

  • objects
  • arrays
  • functions
  • regexp

functions - functions are objects that can be invoked.

function greet() {
  return "Hello!";
}

object - objects are used to store collections of data and more complex entities.

let name = {firstName:"Manthan", lastName:"Ank"};

arrays - arrays are used to store multiple values in a single variable.

let array = ["value1", "value2"];

regexp - regular expressions are used to perform pattern-matching in strings.

let pattern = /w3schools/i;

Back to Top⤴️

Operators

Operators are used to perform operations on variables and values.

There are different types of operators in JavaScript:

  • Arithmetic Operators
  • Logical Operators
  • Comparison Operators
  • Bitwise Operators
  • Type Operators
  • Assignment Operators
  • Conditional (Ternary) Operator
  • Nullish Coalescing Operator(??)
  • Optional Chaining Operator(?.)
  • delete Operator
  • Spread (...) Operator

Arithmetic Operators

OperatorDescription
+Addition
-Subtraction
*Multiplication
**Exponentiation (ES2016)
/Division
%Modulus (Division Remainder)
++Increment
--Decrement

Examples

let x = 5;
let y = 2;

console.log(x + y); // Output: 7
console.log(x - y); // Output: 3
console.log(x * y); // Output: 10
console.log(x / y); // Output: 2.5
console.log(x % y); // Output: 1

x++;
console.log(x); // Output: 6

y--;
console.log(y); // Output: 1

Back to Top⤴️

Logical Operators

OperatorDescription
&&logical and
lllogical or
!logical not

Examples

let x = true;
let y = false;

console.log(x && y); // Output: false
console.log(x || y); // Output: true
console.log(!x); // Output: false
console.log(!y); // Output: true

Comparison Operators

OperatorDescription
==equal to
===equal value and equal type
!=not equal
!==not equal value or not equal type
>greater than
<less than
>=greater than or equal to
<=less than or equal to
?ternary operator

Examples

let x = 5;
let y = 10;

console.log(x == y); // Output: false
console.log(x === y); // Output: false
console.log(x != y); // Output: true
console.log(x !== y); // Output: true
console.log(x > y); // Output: false
console.log(x < y); // Output: true
console.log(x >= y); // Output: false
console.log(x <= y); // Output: true
console.log(x ? y : x); // Output: 10
console.log(x ? x : y); // Output: 5

Back to Top⤴️

Bitwise Operators

OperatorDescription
&AND
lOR
~NOT
^XOR
<<Left shift
>>Right shift
>>>Unsigned right

Examples

let x = 5; // Binary representation: 101
let y = 3; // Binary representation: 011

console.log(x & y); // Output: 1 (binary: 001)
console.log(x | y); // Output: 7 (binary: 111)
console.log(x ^ y); // Output: 6 (binary: 110)
console.log(~x); // Output: -6 (binary: 11111111111111111111111111111010)
console.log(x << 1); // Output: 10 (binary: 1010)
console.log(x >> 1); // Output: 2 (binary: 10)
console.log(x >>> 1); // Output: 2 (binary: 10)

Type Operators

OperatorDescription
typeofReturns the type of a variable
instanceofReturns true if an object is an instance of an object type

Examples

console.log(typeof 5); // Output: "number"
console.log(typeof 'hello'); // Output: "string"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof null); // Output: "object" (this is a bug in JavaScript)
console.log(typeof {}); // Output: "object"
console.log(typeof []); // Output: "object"
console.log(typeof function() {}); // Output: "function"

let cars = ['BMW', 'Volvo', 'Mini'];

console.log(cars instanceof Array); // Output: true
console.log(cars instanceof Object); // Output: true
console.log(cars instanceof String); // Output: false
console.log(cars instanceof Number); // Output: false
console.log(cars instanceof Function); // Output: false
console.log(cars instanceof RegExp); // Output: false
console.log(cars instanceof Date); // Output: false
console.log(cars instanceof Symbol); // Output: false
console.log(cars instanceof Boolean); // Output: false

Back to Top⤴️

Assignment Operators

OperatorDescription
=x = y
+=x += y
-=x -= y
*=x *= y
/=x /= y
%=x %= y
**=x **= y
:x : 45
let x = 5;
let y = 10;

x += y; // x = x + y
console.log(x); // Output: 15

x -= y; // x = x - y
console.log(x); // Output: 5

x *= y; // x = x * y
console.log(x); // Output: 50

x /= y; // x = x / y
console.log(x); // Output: 5

x %= y; // x = x % y
console.log(x); // Output: 5

x **= y; // x = x ** y
console.log(x); // Output: 9765625

x = y; // x = y
console.log(x); // Output: 10

Back to Top⤴️

Conditional (Ternary) Operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

Syntax

(condition) ? x : y
let x = 10;
let y = 5;

let result = (x > y) ? "x is greater than y" : "x is less than y";

console.log(result); // Output: "x is greater than y"

Nullish Coalescing Operator(??)

The nullish coalescing operator (??) is a new operator in JavaScript that returns the right-hand operand when the left-hand operand is null or undefined.

Example

let x = null;
let y = undefined;
let z = 'Hello';

console.log(x ?? 'Default Value'); // Output: "Default Value"
console.log(y ?? 'Default Value'); // Output: "Default Value"
console.log(z ?? 'Default Value'); // Output: "Hello"

Back to Top⤴️

Optional Chaining Operator(?.)

The optional chaining operator (?.) is a new operator in JavaScript that allows you to access properties of an object without having to check if the object or its properties are null or undefined.

Example

let person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  }
};

console.log(person.address?.city); // Output: "New York"
console.log(person.address?.zipCode); // Output: undefined

delete Operator

The delete operator is used to delete a property from an object.

Example

const person = {
  firstName:"Manthan",
  lastName:"Ank",
  age:25,
  eyeColor:"black"
};

delete person.age;

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank", eyeColor: "black"}

Back to Top⤴️

Spread (...) Operator

The spread operator is a new addition to the JavaScript language in ES6. It is denoted by three dots (...). It is used to expand an array or object into individual elements.

Example

// Array literal
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5, 6];
console.log(newNumbers); // Output: [1, 2, 3, 4, 5, 6]

// Object literal
let person = {name: 'John', age: 30};
let newPerson = {...person, city: 'New York', country: 'USA'};
console.log(newPerson); // Output: {name: "John", age: 30, city: "New York", country: "USA"}

// Function call
function sum(a, b, c) {
  return a + b + c;
}
let numbers = [1, 2, 3];
console.log(sum(...numbers)); // Output: 6

// Copy an array
let numbers = [1, 2, 3];
let newNumbers = [...numbers];
console.log(newNumbers); // Output: [1, 2, 3]

Back to Top⤴️

Boolean

JavaScript booleans can have one of two values: true or false.

let value = true;

Boolean Methods and Properties

The following are some of the most commonly used boolean methods and properties in JavaScript:

constructor - Returns the function that created JavaScript's Boolean prototype

let value = true;

console.log(value.constructor); // Output: ƒ Boolean() { [native code] }

prototype - Allows you to add properties and methods to the Boolean prototype

Boolean.prototype.age = 25;

let value = true;

console.log(value.age); // Output: 25

toString() - Converts a boolean value to a string, and returns the result

let value = true;

console.log(value.toString()); // Output: "true"

valueOf() - Returns the primitive value of a boolean

let value = true;

console.log(value.valueOf()); // Output: true

Back to Top⤴️

Object

Objects are used to store key/value (name/value) collections.

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object Methods & Properties

The following are some of the most commonly used object methods and properties in JavaScript:

constructor - Returns the function that created an object's prototype

let person = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(person.constructor); // Output: ƒ Object() { [native code] }

keys() - Returns an Array Iterator object with the keys of an object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

let keys = Object.keys(person);
console.log(keys); // Output: ["firstName", "lastName"]

prototype - Let you to add properties and methods to JavaScript objects

let person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.prototype.age = 25;

console.log(person.age); // Output: 25

toString() - Converts an object to a string and returns the result

let person = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(person.toString()); // Output: "[object Object]"

valueOf() - Returns the primitive value of an object

let person = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(person.valueOf()); // Output: {firstName: "Manthan", lastName: "Ank"}

Back to Top⤴️

Arrays

Arrays are used to store multiple values in a single variable.

const letters = ['a', 'b', 'c'];

Array Methods

The following are some of the most commonly used array methods in JavaScript:

  • at()
  • concat()
  • constructor
  • copyWithin()
  • entries()
  • every()
  • fill()
  • filter()
  • find()
  • findIndex()
  • findLast()
  • findLastIndex()
  • flat()
  • flatMap()
  • forEach()
  • from()
  • includes()
  • indexOf()
  • isArray()
  • join()
  • keys()
  • lastIndexOf()
  • length
  • map()
  • pop()
  • prototype
  • push()
  • reduce()
  • reduceRight()
  • reverse()
  • shift()
  • slice()
  • some()
  • sort()
  • splice()
  • toLocaleString()
  • toReversed()
  • toSorted()
  • toSpliced()
  • toString()
  • unshift()
  • valueOf()
  • values()
  • with()

Back to Top⤴️

at() - Returns the element at a specified index in an array

let array = ['a', 'b', 'c'];

console.log(array.at(1)); // Output: "b"

concat() - Joins arrays and returns an array with the joined arrays.

let array1 = ['a', 'b', 'c'];
let array2 = ['d', 'e', 'f'];

let mergedArray = array1.concat(array2);
console.log(mergedArray); // mergedArray is ['a', 'b', 'c', 'd', 'e', 'f']

constructor - Returns the function that created the Array object's prototype

let array = ['a', 'b', 'c'];

console.log(array.constructor); // Output: ƒ Array() { [native code] }

copyWithin() - Copies array elements within the array, to and from specified positions

let array = ['a', 'b', 'c', 'd', 'e', 'f'];

array.copyWithin(2, 0);
console.log(array); // Output: ["a", "b", "a", "b", "c", "d"]

array.copyWithin(4, 0, 2);
console.log(array); // Output: ["a", "b", "a", "b", "a", "b"]

Back to Top⤴️

entries() - Returns a key/value pair Array Iteration Object

let array = ['a', 'b', 'c'];

let iterator = array.entries();

console.log(iterator.next().value); // Output: [0, "a"]
console.log(iterator.next().value); // Output: [1, "b"]
console.log(iterator.next().value); // Output: [2, "c"]

every() - Checks if every element in an array pass a test

let array = [1, 2, 3, 4, 5];

let result = array.every(value => value > 0);

console.log(result); // Output: true

fill() - Fill the elements in an array with a static value

let array = ['a', 'b', 'c', 'd', 'e', 'f'];

array.fill('x', 2, 4);

console.log(array); // Output: ["a", "b", "x", "x", "e", "f"]

Back to Top⤴️

filter() - Creates a new array with every element in an array that pass a test

let array = [1, 2, 3, 4, 5];

let newArray = array.filter(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(newArray); // Output: [4, 5]

find() - Returns the value of the first element in an array that pass a test

let array = [1, 2, 3, 4, 5];

let value = array.find(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(value); // Output: 4

findIndex() - Returns the index of the first element in an array that pass a test

let array = [1, 2, 3, 4, 5];

let index = array.findIndex(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(index); // Output: 3

findLast() - Returns the value of the last element in an array that pass a test

let array = [1, 2, 3, 4, 5];

let value = array.findLast(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(value); // Output: 5

findLastIndex() - Returns the index of the last element in an array that pass a test

let array = [1, 2, 3, 4, 5];

let index = array.findLastIndex(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(index); // Output: 4

Back to Top⤴️

flat() - Flattens an array up to a specified depth

let array = [1, 2, [3, 4, [5, 6]]];

let newArray = array.flat(2);

console.log(array); // Output: [1, 2, [3, 4, [5, 6]]]
console.log(newArray); // Output: [1, 2, 3, 4, 5, 6]

flatMap() - Maps each element using a mapping function, then flattens the result into a new array

let array = [1, 2, 3, 4, 5];

let newArray = array.flatMap(value => [value * 2]);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(newArray); // Output: [2, 4, 6, 8, 10]

forEach() - Calls a function for each array element

let array = [1, 2, 3, 4, 5];

array.forEach(value => {
  console.log(value);
});

// Output: 1
// Output: 2
// Output: 3
// Output: 4
// Output: 5

from() - Creates an array from an object

let array = 'hello';

let newArray = Array.from(array);

console.log(array); // Output: "hello"
console.log(newArray); // Output: ["h", "e", "l", "l", "o"]

includes() - Check if an array contains the specified element

let array = [1, 2, 3, 4, 5];

let result = array.includes(3);

console.log(array); // Output: [1, 2, 3, 4, 5]

console.log(result); // Output: true
console.log(array.includes(6)); // Output: false

indexOf() - Search the array for an element and returns its position

let array = [1, 2, 3, 4, 5];

let index = array.indexOf(3);

console.log(array); // Output: [1, 2, 3, 4, 5]

console.log(index); // Output: 2
console.log(array.indexOf(6)); // Output: -1

Back to Top⤴️

isArray() - Checks whether an object is an array

let array = [1, 2, 3, 4, 5];

let result = Array.isArray(array);

console.log(array); // Output: [1, 2, 3, 4, 5]

console.log(result); // Output: true
console.log(Array.isArray('hello')); // Output: false

join() - Joins all elements of an array into a string

let array = ['a', 'b', 'c'];

let result = array.join();

console.log(array); // Output: ["a", "b", "c"]
console.log(result); // Output: "a,b,c"

keys() - Returns a Array Iteration Object, containing the keys of the original array

let array = ['a', 'b', 'c'];

let iterator = array.keys();

console.log(array); // Output: ["a", "b", "c"]
console.log(iterator.next().value); // Output: 0

Back to Top⤴️

lastIndexOf() - Search the array for an element, starting at the end, and returns its position

let array = [1, 2, 3, 4, 5, 3];

let index = array.lastIndexOf(3);

console.log(array); // Output: [1, 2, 3, 4, 5, 3]
console.log(index); // Output: 5

length - Sets or returns the number of elements in an array

let array = ['a', 'b', 'c'];

console.log(array); // Output: ["a", "b", "c"]
console.log(array.length); // Output: 3

map() - Creates a new array with the result of calling a function for each array element

let array = [1, 2, 3, 4, 5];

let newArray = array.map(value => value * 2);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(newArray); // Output: [2, 4, 6, 8, 10]

pop() - Removes the last element of an array, and returns that element

let array = ['a', 'b', 'c'];

let element = array.pop();

console.log(array); // Output: ["a", "b"]
console.log(element); // Output: "c"

Back to Top⤴️

prototype - Allows you to add properties and methods to an Array object

let array = ['a', 'b', 'c'];

Array.prototype.age = 25;

console.log(array); // Output: ["a", "b", "c"]
console.log(array.age); // Output: 25

push() - Adds new elements to the end of an array, and returns the new length

let array = ['a', 'b', 'c'];

let length = array.push('d', 'e');

console.log(array); // Output: ["a", "b", "c", "d", "e"]
console.log(length); // Output: 4

reduce() - Reduce the values of an array to a single value (going left-to-right)

let array = [1, 2, 3, 4, 5];

let total = array.reduce((accumulator, value) => accumulator + value, 0);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(total); // Output: 15

Back to Top⤴️

reduceRight() - Reduce the values of an array to a single value (going right-to-left)

let array = [1, 2, 3, 4, 5];

let total = array.reduceRight((accumulator, value) => accumulator + value, 0);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(total); // Output: 15

reverse() - Reverses the order of the elements in an array

let array = ['a', 'b', 'c'];

array.reverse();

console.log(array); // Output: ["c", "b", "a"]

shift() - Removes the first element of an array, and returns that element

let array = ['a', 'b', 'c'];

let element = array.shift();

console.log(array); // Output: ["b", "c"]
console.log(element); // Output: "a"

Back to Top⤴️

slice() - Selects a part of an array, and returns the new array

let array = ['a', 'b', 'c', 'd', 'e', 'f'];

let newArray = array.slice(2, 4);

console.log(array); // Output: ["a", "b", "c", "d", "e", "f"]
console.log(newArray); // Output: ["c", "d"]

some() - Checks if any of the elements in an array pass a test

let array = [1, 2, 3, 4, 5];

let result = array.some(value => value > 3);

console.log(array); // Output: [1, 2, 3, 4, 5]
console.log(result); // Output: true

sort() - Sorts the elements of an array

let array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

array.sort();

console.log(array); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

Back to Top⤴️

splice() - Adds/Removes elements from an array

let array = ['a', 'b', 'c', 'd', 'e', 'f'];

array.splice(2, 0, 'x', 'y');

console.log(array); // Output: ["a", "b", "x", "y", "c", "d", "e", "f"]

toLocaleString() - Converts an array to a string, using locale-specific settings

let array = ['a', 'b', 'c'];

console.log(array.toLocaleString()); // Output: "a,b,c"

toReversed() - Reverses the elements of an array

let array = ['a', 'b', 'c'];

let reversedArray = array.toReversed();

console.log(array); // Output: ["a", "b", "c"]
console.log(reversedArray); // Output: ["c", "b", "a"]

Back to Top⤴️

toSorted() - Sorts the elements of an array

let array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];

let sortedArray = array.toSorted();

console.log(array); // Output: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
console.log(sortedArray); // Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

toSpliced() - Adds/Removes elements from an array

let array = ['a', 'b', 'c', 'd', 'e', 'f'];

let splicedArray = array.toSpliced(2, 0, 'x', 'y');

console.log(array); // Output: ["a", "b", "c", "d", "e", "f"]
console.log(splicedArray); // Output: ["a", "b", "x", "y", "c", "d", "e", "f"]

toString() - Converts an array to a string, and returns the result

let array = ['a', 'b', 'c'];

console.log(array.toString()); // Output: "a,b,c"

Back to Top⤴️

unshift() - Adds new elements to the beginning of an array, and returns the new length

let array = ['a', 'b', 'c'];

let length = array.unshift('x', 'y');

console.log(array); // Output: ["x", "y", "a", "b", "c"]

valueOf() - Returns the primitive value of an array

let array = ['a', 'b', 'c'];

console.log(array.valueOf()); // Output: ["a", "b", "c"]

values() - Returns an Array Iteration Object, containing the values of the original array

let array = ['a', 'b', 'c'];

let iterator = array.values();

console.log(array); // Output: ["a", "b", "c"]
console.log(iterator.next().value); // Output: "a"

with() - Allows you to add properties and methods to an Array object

let array = ['a', 'b', 'c'];

Array.with = 25;

console.log(array); // Output: ["a", "b", "c"]
console.log(Array.with); // Output: 25

Back to Top⤴️

Strings

Strings are used to store text. Strings must be enclosed in single or double quotes.

const name = 'Manthan';

Strings methods

The following are some of the most commonly used string methods in JavaScript:

  • at()
  • charAt()
  • charCodeAt()
  • concat()
  • constructor
  • endsWith()
  • fromCharCode()
  • includes()
  • indexOf()
  • lastIndexOf()
  • length
  • localeCompare()
  • match()
  • matchAll()
  • padEnd()
  • padStart()
  • prototype
  • repeat()
  • replace()
  • replaceAll()
  • search()
  • slice()
  • split()
  • startsWith()
  • substr()
  • substring()
  • toLocaleLowerCase()
  • toLocaleUpperCase()
  • toLowerCase()
  • toString()
  • toUpperCase()
  • trim()
  • trimEnd()
  • trimStart()
  • valueOf()

Back to Top⤴️

at() - Returns the character at a specified index (position)

let myString = "Hello World!";

console.log(myString.at(0)); // Output: "H"

charAt() - Returns the character at a specified index (position)

let myString = "Hello World!";

console.log(myString.charAt(0)); // Output: "H"

charCodeAt() - Returns the Unicode of the character at a specified index

let myString = "Hello World!";

console.log(myString.charCodeAt(0)); // Output: 72

Back to Top⤴️

concat() - Returns two or more joined strings

let myString1 = "Hello";
let myString2 = "World!";

let newString = myString1.concat(" ", myString2);

console.log(newString); // Output: "Hello World!"

constructor - Returns the string's constructor function

let myString = "Hello World!";

console.log(myString.constructor); // Output: ƒ String() { [native code] }

Back to Top⤴️

endsWith() - Returns if a string ends with a specified value

let myString = "Hello World!";

console.log(myString.endsWith("!")); // Output: true

fromCharCode() - Returns Unicode values as characters

let myString = String.fromCharCode(72, 101, 108, 108, 111);

console.log(myString); // Output: "Hello"

Back to Top⤴️

includes() - Returns if a string contains a specified value

let myString = "Hello World!";

console.log(myString.includes("World")); // Output: true

indexOf() - Returns the index (position) of the first occurrence of a value in a string

let myString = "Hello World!";

console.log(myString.indexOf("World")); // Output: 6

Back to Top⤴️

lastIndexOf() - Returns the index (position) of the last occurrence of a value in a string

let myString = "Hello World! World!";

console.log(myString.lastIndexOf("World")); // Output: 13

length - Returns the length of a string

let myString = "Hello World!";

console.log(myString.length); // Output: 12

Back to Top⤴️

localeCompare() - Compares two strings in the current locale

let myString = "Hello World!";

console.log(myString.localeCompare("Hello World!")); // Output: 0

match() - Searches a string for a value, or a regular expression, and returns the matches

let myString = "The quick brown fox jumps over the lazy dog.";

let result = myString.match(/the/i);

console.log(myString); // Output: "The quick brown fox jumps over the lazy dog."
console.log(result); // Output: ["the", index: 30, input: "The quick brown fox jumps over the lazy dog.", groups: undefined]

matchAll() - Returns an iterator of all results matching a string against a regular expression

let myString = "The quick brown fox jumps over the lazy dog.";

let result = myString.matchAll(/the/gi);

console.log(myString); // Output: "The quick brown fox jumps over the lazy dog."
console.log(result); // Output: [RegExpStringIterator]

padEnd() - Pads a string with a specified value at the end

let myString = "Hello";

let newString = myString.padEnd(10, " World!");

console.log(myString); // Output: "Hello"
console.log(newString); // Output: "Hello World!"

padStart() - Pads a string with a specified value at the start

let myString = "Hello";

let newString = myString.padStart(10, " World!");

console.log(myString); // Output: "Hello"
console.log(newString); // Output: " World!Hello"

Back to Top⤴️

prototype - Allows you to add properties and methods to an object

let myString = "Hello World!";
String.prototype.age = 25;

console.log(myString.age); // Output: 25

repeat() - Returns a new string with a number of copies of a string

let myString = "Hello World!";

console.log(myString.repeat(2)); // Output: "Hello World!Hello World!"

Back to Top⤴️

replace() - Searches a string for a value, or a regular expression, and returns a string where the values are replaced

let myString = "Hello World!";

let newString = myString.replace("World", "Universe");

console.log(myString); // Output: "Hello World!"
console.log(newString); // Output: "Hello Universe!"

search() - Searches a string for a value, or regular expression, and returns the index (position) of the match

let myString = "The quick brown fox jumps over the lazy dog.";

let result = myString.search(/fox/);

console.log(myString); // Output: "The quick brown fox jumps over the lazy dog."
console.log(result); // Output: 16

Back to Top⤴️

slice() - Extracts a part of a string and returns a new string

let myString = "Hello World!";

let newString = myString.slice(6, 11);

console.log(myString); // Output: "Hello World!"
console.log(newString); // Output: "World"

split() - Splits a string into an array of substrings

let myString = "Hello World!";

let array = myString.split(" ");

console.log(myString); // Output: "Hello World!"
console.log(array); // Output: ["Hello", "World!"]

Back to Top⤴️

startsWith() - Checks whether a string begins with specified characters

let myString = "Hello World!";

console.log(myString.startsWith("Hello")); // Output: true

substr() - Extracts a number of characters from a string, from a start index (position)

let myString = "Hello World!";

let newString = myString.substr(6, 5);

console.log(myString); // Output: "Hello World!"
console.log(newString); // Output: "World"

Back to Top⤴️

substring() - Extracts characters from a string, between two specified indices (positions)

let myString = "Hello World!";

let newString = myString.substring(6, 11);

console.log(myString); // Output: "Hello World!"
console.log(newString); // Output: "World"

toLocaleLowerCase() - Returns a string converted to lowercase letters, using the host's locale

let myString = "Hello World!";

console.log(myString.toLocaleLowerCase()); // Output: "hello world!"

Back to Top⤴️

toLocaleUpperCase() - Returns a string converted to uppercase letters, using the host's locale

let myString = "Hello World!";

console.log(myString.toLocaleUpperCase()); // Output: "HELLO WORLD!"

toLowerCase() - Returns a string converted to lowercase letters

let myString = "Hello World!";

console.log(myString); // Output: "Hello World!"
console.log(myString.toLowerCase()); // Output: "hello world!"

Back to Top⤴️

toString() - Returns a string or a string object as a string

let myString = "Hello World!";
let number = 25; 

console.log(myString.toString()); // Output: "Hello World!"
console.log(number.toString()); // Output: "25"

toUpperCase() - Returns a string converted to uppercase letters

let myString = "Hello World!";

console.log(myString); // Output: "Hello World!"
console.log(myString.toUpperCase()); // Output: "HELLO WORLD

Back to Top⤴️

trim() - Returns a string with removed whitespaces

let myString = " Hello World! ";

console.log(myString); // Output: " Hello World! "
console.log(myString.trim()); // Output: "Hello World!"

trimEnd() - Returns a string with removed whitespaces from the end

let myString = " Hello World! ";

console.log(myString); // Output: " Hello World! "
console.log(myString.trimEnd()); // Output: " Hello World!"

Back to Top⤴️

trimStart() - Returns a string with removed whitespaces from the start

let myString = " Hello World! ";

console.log(myString); // Output: " Hello World! "
console.log(myString.trimStart()); // Output: "Hello World! "

valueOf() - Returns the primitive value of a string or a string object.

let myString = "Hello World!";

console.log(myString.valueOf()); // Output: "Hello World!"

Back to Top⤴️

Objects

Objects are used to store collections of data and more complex entities.

const person = {
  firstName: "Manthan",
  lastName: "Ank",
  age: 25,
  hobbies: ["reading", "coding", "traveling"],
  address: {
    street: "123 Main St",
    city: "Mumbai",
    state: "MH",
  },
};

Object Methods

The following are some of the most commonly used object methods in JavaScript:

  • assign()
  • create()
  • defineProperties()
  • defineProperty()
  • entries()
  • freeze()
  • fromEntries()
  • getOwnPropertyDescriptor()
  • getOwnPropertyDescriptors()
  • getOwnPropertyNames()
  • getOwnPropertySymbols()
  • getPrototypeOf()
  • groupBy()
  • hasOwn()
  • is()
  • isExtensible()
  • isFrozen()
  • isSealed()
  • keys()
  • preventExtensions()
  • prototype
  • seal()
  • setPrototypeOf()
  • values()

Back to Top⤴️

assign() - Copies the values of all enumerable own properties from one or more source objects to a target object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const details = {
  age: 25,
  hobbies: ["reading", "coding", "traveling"],
};

const newPerson = Object.assign(person, details);

console.log(newPerson); // Output: {firstName: "Manthan", lastName: "Ank", age: 25, hobbies: Array(3)}

create() - Creates a new object with the specified prototype object and properties

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const newPerson = Object.create(person);

console.log(newPerson); // Output: {}

Back to Top⤴️

defineProperties() - Defines new or modifies existing properties directly on an object, returning the object

const person = {};

Object.defineProperties(person, {
  firstName: {
    value: "Manthan",
    writable: true,
  },
  lastName: {
    value: "Ank",
    writable: true,
  },
});

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}

defineProperty() - Defines a new property directly on an object, or modifies an existing property on an object, and returns the object

const person = {};

Object.defineProperty(person, "firstName", {
  value: "Manthan",
  writable: true,
});

console.log(person); // Output: {firstName: "Manthan"}

Back to Top⤴️

entries() - Returns an array of a given object's own enumerable string-keyed property key, value pairs

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const entries = Object.entries(person);

console.log(entries); // Output: [["firstName", "Manthan"], ["lastName", "Ank"]]

freeze() - Freezes an object: other code can't delete or change any properties

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.freeze(person);

person.age = 25;

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}

Back to Top⤴️

fromEntries() - Returns a new object from an iterable of key, value pairs

const entries = [
  ["firstName", "Manthan"],
  ["lastName", "Ank"],
];

const person = Object.fromEntries(entries);

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}

getOwnPropertyDescriptor() - Returns a property descriptor for a named property on an object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const descriptor = Object.getOwnPropertyDescriptor(person, "firstName");

console.log(descriptor); // Output: {value: "Manthan", writable: true, enumerable: true, configurable: true}

Back to Top⤴️

getOwnPropertyDescriptors() - Returns all own property descriptors of a given object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const descriptors = Object.getOwnPropertyDescriptors(person);

console.log(descriptors); // Output: {firstName: {…}, lastName: {…}}

getOwnPropertyNames() - Returns an array of all properties (enumerable or not) found directly upon a given object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const properties = Object.getOwnPropertyNames(person);

console.log(properties); // Output: ["firstName", "lastName"]

Back to Top⤴️

getOwnPropertySymbols() - Returns an array of all symbol properties found directly upon a given object

const person = {
  [Symbol("firstName")]: "Manthan",
  [Symbol("lastName")]: "Ank",
};

const symbols = Object.getOwnPropertySymbols(person);

console.log(symbols); // Output: [Symbol(firstName), Symbol(lastName)]

getPrototypeOf() - Returns the prototype of the specified object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const prototype = Object.getPrototypeOf(person);

console.log(prototype); // Output: {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}

Back to Top⤴️

groupBy() - Groups the elements of an array based on the given function

const people = [
  { name: "Manthan", age: 25 },
  { name: "Ank", age: 30 },
  { name: "John", age: 25 },
];

const groupedPeople = people.groupBy(person => person.age);

console.log(groupedPeople); // Output: {25: Array(2), 30: Array(1)}

hasOwn() - Returns a boolean indicating whether the object has the specified property as its own property

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(person.hasOwn("firstName")); // Output: true

Back to Top⤴️

is() - Compares if two values are the same value

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const newPerson = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(Object.is(person, newPerson)); // Output: false

isExtensible() - Returns a boolean indicating if the object is extensible

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

console.log(Object.isExtensible(person)); // Output: true

Back to Top⤴️

isFrozen() - Returns a boolean indicating if the object is frozen

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.freeze(person);

console.log(Object.isFrozen(person)); // Output: true

isSealed() - Returns a boolean indicating if the object is sealed

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.seal(person);

console.log(Object.isSealed(person)); // Output: true

Back to Top⤴️

keys() - Returns an array of a given object's own enumerable property names

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const keys = Object.keys(person);

console.log(keys); // Output: ["firstName", "lastName"]

preventExtensions() - Prevents any extensions of an object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.preventExtensions(person);

person.age = 25;

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}

Back to Top⤴️

prototype - Allows you to add properties and methods to an object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.prototype.age = 25;

console.log(person.age); // Output: 25

seal() - Prevents other code from deleting properties of an object

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

Object.seal(person);

delete person.firstName;

console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}

Back to Top⤴️

setPrototypeOf() - Sets the prototype (i.e., the internal [Prototype] property) of a specified object to another object or null

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const newPerson = {
  age: 25,
};

Object.setPrototypeOf(newPerson, person);

console.log(newPerson); // Output: {age: 25}

values() - Returns an array of a given object's own enumerable property values

const person = {
  firstName: "Manthan",
  lastName: "Ank",
};

const values = Object.values(person);

console.log(values); // Output: ["Manthan", "Ank"]

Loops

Loops are used to execute a block of code multiple times.

There are several types of loops in JavaScript:

  • for loop
  • while loop
  • do while loop
  • for in loop
  • for of loop

Back to Top⤴️

for loop

This type of loop is used to execute a block of code a specified number of times.

for (let i = 0; i < 5; i++) {
  console.log(i);
}

while loop

This type of loop is used to execute a block of code as long as a specified condition is true.

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

Back to Top⤴️

do while loop

This type of loop is similar to the while loop, but it guarantees that the code block will be executed at least once.

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

for in loop

This type of loop is used to iterate over the enumerable properties of an object.

let obj = {a: 1, b: 2, c: 3};
for (let prop in obj) {
  console.log(prop + ": " + obj[prop]);
}

Back to Top⤴️

for of loop

This type of loop is used to iterate over the iterable objects such as arrays, strings, and maps.

let arr = [1, 2, 3];
for (let value of arr) {
  console.log(value);
}

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

There are several types of conditional statements in JavaScript:

  • if statement
  • if else statement
  • if else else if statement
  • switch statement

Back to Top⤴️

if statement

The if statement is used to execute a block of code if a specified condition is true.

if (x > 0) {
  console.log("x is greater than 0");
}

if else statement

The if...else statement is used to execute a block of code if a specified condition is true and another block of code if the condition is false.

if (x > 0) {
  console.log("x is greater than 0");
} else {
  console.log("x is not greater than 0");
}

Back to Top⤴️

if else else if statement

The if...else if...else statement is used to specify multiple conditions and execute a different block of code for each one.

if (x > 0) {
  console.log("x is positive");
} else if (x < 0) {
  console.log("x is negative");
} else {
  console.log("x is zero");
}

switch statement

The switch statement is used to select one of many blocks of code to be executed.

let day = new Date().getDay();
switch (day) {
  case 0:
    console.log("Sunday");
    break;
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  // and so on
  default:
    console.log("Invalid day");
}

Back to Top⤴️

Functions

Functions are blocks of code that can be reused to perform a specific task. Defined with the function keyword, followed by a name, followed by parentheses ().

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Types of Functions

  • Named Function
  • Anonymous Function
  • Arrow Function
  • IIFE
  • Higher-Order Function
  • Function Expression
  • Function Declaration
  • Function Constructor

Back to Top⤴️

Named Function

A named function is a function that has a name. It can be defined using the function keyword followed by the function name.

function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Anonymous Function

An anonymous function is a function that does not have a name. It can be defined using the function keyword followed by parentheses ().

const name = function(parameter1, parameter2, parameter3) {
  // code to be executed
}

Arrow Function

Arrow functions are a more concise way to write functions in JavaScript. They are defined using the => syntax.

const name = (parameter1, parameter2, parameter3) => {
  // code to be executed
}

const name = (parameter1, parameter2, parameter3) => expression

const name = parameter => expression

const name = () => expression

const name = (parameter1, parameter2, parameter3) => {
  return expression
}

const name = parameter => {
  return expression
}

const name = () => {
  return expression
}

Back to Top⤴️

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

(function() {
  console.log("Hello World!");
})();

Back to Top⤴️

Higher-Order Functions

A higher-order function is a function that takes another function as an argument or returns a function as a result.

function greet() {
  return "Hello World!";
}

function greetUser(greet) {
  return greet();
}

console.log(greetUser(greet)); // Output: "Hello World!"

Back to Top⤴️

Function Expression

A function expression is a function that is assigned to a variable.

const greet = function() {
  return "Hello World!";
}

console.log(greet()); // Output: "Hello World!"

Function Declaration

A function declaration is a function that is defined using the function keyword followed by the function name.

function greet() {
  return "Hello World!";
}

console.log(greet()); // Output: "Hello World!"

Function Constructor

A function constructor is a function that is used to create new objects.

const greet = new Function("return 'Hello World!'");
console.log(greet()); // Output: "Hello World!"

Back to Top⤴️

Scope

Scope refers to the visibility of variables in JavaScript. There are three types of scope in JavaScript:

  • Global Scope
  • Function Scope
  • Block Scope

Global Scope

let a = 10;
function myFunction() {
    console.log(a);
}
myFunction();

Block Scope

//var
function myFunction () {
    if(true) {
        var a = 10; // it exists in function scope
    }
    console.log(a);
}
myFunction();

//let
function myFunction () {
    if(true) {
        let a = 10; // it exists in block scope
    }
    console.log(a);
}
myFunction();

//const
function myFunction () {
    if(true) {
        const a = 10; // it exists in block scope
    }
    console.log(a);
}
myFunction();

Back to Top⤴️

Function Scope

//var
function myFunction() {
    var a = 10;
}
myFunction()
console.log(a);

//let
function myFunction() {
    let a = 10;
}
myFunction()
console.log(a);

//const
function myFunction() {
    const a = 10;
}
myFunction()
console.log(a);

Back to Top⤴️

Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase.

console.log(x); // Output: undefined

var x = 5;

Back to Top⤴️

Currying

Currying is a technique in which a function with multiple arguments is converted into a sequence of nested functions, each taking a single argument.

function multiply(a) {
  return function(b) {
    return function(c) {
      return a * b * c;
    };
  };
}

console.log(multiply(2)(3)(4)); // Output: 24

Dates

JavaScript provides a built-in Date object that can be used to work with dates and times.

Date Object

The Date object is used to work with dates and times in JavaScript. It can be created using the new keyword followed by the Date() constructor.

new Date()

Back to Top⤴️

Date Formats

There are several ways to create a new Date object in JavaScript:

new Date() // current date and time
new Date(milliseconds) // milliseconds since January 1, 1970, 00:00:00 UTC
new Date(dateString) // date string (e.g. "October 13, 2014 11:13:00")
new Date(year, month, day, hours, minutes, seconds, milliseconds) // year, month, day, hours, minutes, seconds, milliseconds

Back to Top⤴️

Date Properties

constructor - Returns the function that created the Date object's prototype

const d = new Date();
d.constructor; // ƒ Date() { [native code] }

prototype - Allows you to add properties and methods to the Date object

Date.prototype.age = 25;

const d = new Date();
d.age; // 25

UTC - Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

const d = new Date();
d.UTC(); // 1642149980524

Back to Top⤴️

parse - Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

Date.parse("Jan 1, 2023"); // 1672531200000

now - Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC

Date.now(); // 1642149980524

Back to Top⤴️

Date Methods

toString - It is a built-in function that can be used to convert a date object to a string.

const d = new Date();
d.toString(); // 'Sat Jan 14 2023 10:36:20 GMT+0530 (India Standard Time)'

toDateString - It is a built-in function that can be used to convert a date object to a string in the format of "Weekday Month Date Year".

const d = new Date();
d.toDateString(); // 'Sat Jan 14 2023'

Back to Top⤴️

toUTCString - It is a built-in function that can be used to convert a date object to a string in the format of "Weekday, DD Mon YYYY HH:MM:SS GMT".

const d = new Date();
d.toUTCString(); // 'Sat, 14 Jan 2023 05:06:20 GMT'

toISOString - It is a built-in function that can be used to convert a date object to a string in the format of "YYYY-MM-DDTHH:mm:ss.sssZ".

const d = new Date();
d.toISOString(); // '2023-01-14T05:06:20.524Z'

Back to Top⤴️

Date Get Methods

The Date object has several built-in methods that can be used to get the date and time components of a date object. Some of the most commonly used get methods are:

getFullYear - returns the four-digit year of the date.

const d = new Date();
d.getFullYear();

getMonth - returns the month of the date (0-11, where 0 represents January and 11 represents December).

const d = new Date();
d.getMonth();

Back to Top⤴️

getDate - returns the day of the month of the date (1-31).

const d = new Date();
d.getDate();

getDay - returns the day of the week of the date (0-6, where 0 represents Sunday and 6 represents Saturday).

const d = new Date();
d.getDay();

getHours - returns the hour of the date (0-23).

const d = new Date();
d.getHours();

Back to Top⤴️

getMinutes - returns the minutes of the date (0-59).

const d = new Date();
d.getMinutes();

getSeconds - returns the seconds of the date (0-59).

const d = new Date();
d.getSeconds();

Back to Top⤴️

getMilliseconds - returns the milliseconds of the date (0-999).

const d = new Date();
d.getMilliseconds();

getTime - returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

const d = new Date();
d.getTime();

Back to Top⤴️

Date Set Methods

setDate - sets the day of the month of the date object.

const d = new Date();
d.setDate(15);

setFullYear - sets the year, and optionally the month and date, of the date object.

const d = new Date();
d.setFullYear(2020);

Back to Top⤴️

setHours - sets the hours, minutes, seconds and milliseconds of the date object.

const d = new Date();
d.setHours(22);

setMilliseconds - sets the milliseconds of the date object.

const d = new Date();
d.setMilliSeconds(3000);

setMinutes - sets the minutes, seconds and milliseconds of the date object.

const d = new Date();
d.setMinutes(30);

Back to Top⤴️

setSeconds - sets the seconds and milliseconds of the date object.

const d = new Date();
d.setSeconds(30);

setMonth - sets the month, and optionally the date, of the date object.

const d = new Date();
d.setMonth(11);

setTime - sets the date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.

const d = new Date();
d.setTime(30);

Back to Top⤴️

Type Conversion

JavaScript is a loosely typed language, which means that variables can hold values of any data type. JavaScript automatically converts the data type of a variable to the appropriate type when needed.

Convert string to numbers

Number - Converts a string to a number using the Number() function.

Number("3.14") // 3.14
Number(Math.PI) // 3.141592653589793
Number(" ") // 0
Number("") // 0
Number("99 88") // NaN
Number("John") // NaN

Back to Top⤴️

parseFloat - Converts a string to a floating-point number using the parseFloat() method.

let num = parseFloat("123.456");
console.log(num); // Output: 123.456

Back to Top⤴️

parseInt - Converts a string to an integer using the parseInt() method.

let num = parseInt("123");
console.log(num); // Output: 123

Convert number to a string

String - Converts a number to a string using the String() method.

let str = String(123);
console.log(str); // Output: "123"

Back to Top⤴️

toString - Converts a number to a string using the toString() method.

let str = (123).toString();
console.log(str); // Output: "123"

toExponential - Converts a number to a string, using toExponential() method.

let str = (123).toExponential();
console.log(str); // Output: 1.23e+2

toFixed - Converts a number to a string, using toFixed() method.

let str = (123).toFixed();
console.log(str); // Output: 123

Back to Top⤴️

toPrecision - Converts a number to a string, using toPrecision() method.

let str = (123).toPrecision();
console.log(str); // Output: 123

Convert dates to numbers

Number - Converts a date to a number using the Number() function.

d = new Date();
Number(d) // 1673677425068

Back to Top⤴️

getTime Converts a date to a number using the getTime() method.

d = new Date();
d.getTime() // 1673677461233

string - Converts a date to a string using the String() function.

String(Date()) // 'Sat Jan 14 2023 11:54:38 GMT+0530 (India Standard Time)'

Back to Top⤴️

toString - Converts a date to a string using the toString() method.

Date().toString() //'Sat Jan 14 2023 11:54:57 GMT+0530 (India Standard Time)'

Convert boolean to number

Number - Converts a boolean to a number using the Number() function.

Number(false)     // returns 0
Number(true)      // returns 1

Back to Top⤴️

Convert boolean to string

string - Converts a boolean to a string using the String() function.

1.18.1

5 months ago

1.18.0

9 months ago

1.17.0

9 months ago

1.16.0

9 months ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago