https://github.com/manthanank/learn-javascript
Complete Guide to Learn JavaScript.
https://github.com/manthanank/learn-javascript
advanced beginner es6 intermediate interview interview-questions javascript learn learn-javascript learning-javascript nodejs package snippets
Last synced: 9 months ago
JSON representation
Complete Guide to Learn JavaScript.
- Host: GitHub
- URL: https://github.com/manthanank/learn-javascript
- Owner: manthanank
- License: mit
- Created: 2023-01-11T14:49:17.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-10-15T15:20:26.000Z (over 1 year ago)
- Last Synced: 2024-12-25T19:44:12.628Z (over 1 year ago)
- Topics: advanced, beginner, es6, intermediate, interview, interview-questions, javascript, learn, learn-javascript, learning-javascript, nodejs, package, snippets
- Language: Dockerfile
- Homepage: https://manthanank.github.io/learn-javascript/
- Size: 171 KB
- Stars: 15
- Watchers: 1
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
README
# 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.






## Table of Contents
- [Introduction](#introduction)
- [Add JavaScript](#add-javascript)
- [Output JavaScript](#outputing-javascript)
- [Single Line Comments](#single-line-comments)
- [Multi Line Comments](#multi-line-comments)
- [Variables](#variables)
- [Declare Variables](#declare-variables)
- [Data Types](#data-types)
- [Primitive Data Types](#1-primitive-data-types)
- [Non Primitive Data Types](#2-non-primitive-data-types)
- [Operators](#operators)
- [Arithmetic Operators](#arithmetic-operators)
- [Logical Operators](#logical-operators)
- [Comparison Operators](#comparison-operators)
- [Bitwise Operators](#bitwise-operators)
- [Type operators](#type-operators)
- [Assignment Operators](#assignment-operators)
- [Conditional (Ternary) Operators](#conditional-ternary-operator)
- [Nullish Coalescing Operator(??)](#nullish-coalescing-operator)
- [Optional Chaining Operator(?.)](#optional-chaining-operator)
- [delete Operator](#delete-operator)
- [Spread (...) Operator](#spread--operator)
- [Arrays](#arrays)
- [Array Methods](#array-methods)
- [Strings](#strings)
- [String Methods](#strings-methods)
- [Loops](#loops)
- [for Loop](#for-loop)
- [while Loop](#while-loop)
- [do while Loop](#do-while-loop)
- [for in Loop](#for-in-loop)
- [for of Loop](#for-of-loop)
- [Conditional Statements](#conditional-statements)
- [if statement](#if-statement)
- [if else statement](#if-else-statement)
- [if else else if statement](#if-else-else-if-statement)
- [switch statement](#switch-statement)
- [Functions](#functions)
- [Named Function](#named-function)
- [Anonymous Function](#anonymous-function)
- [Arrow Functions](#arrow-function)
- [Immediately Invoked Function Expression (IIFE)](#iife)
- [Higher Order Function](#higher-order-functions)
- [Function Declaration](#function-declaration)
- [Function Expression](#function-expression)
- [Function Constructor](#function-constructor)
- [Scope](#scope)
- [Block Scope](#block-scope)
- [Function Scope](#function-scope)
- [Global Scope](#global-scope)
- [Hoisting](#hoisting)
- [Currying](#currying)
- [Dates](#dates)
- [Date Methods](#date-methods)
- [Date Get Methods](#date-get-methods)
- [Date Set Methods](#date-set-methods)
- [Type Conversion](#type-conversion)
- [Convert string to numbers](#convert-string-to-numbers)
- [Convert number to a string](#convert-number-to-a-string)
- [Convert dates to numbers](#convert-dates-to-numbers)
- [Convert boolean to number](#convert-boolean-to-number)
- [Convert boolean to string](#convert-boolean-to-string)
- [Typeof](#typeof)
- [Math](#math)
- [Math Property](#math-property)
- [Math Methods](#math-methods)
- [Sets](#sets)
- [Set Methods](#set-methods)
- [Map](#map)
- [Map Methods](#map-methods)
- [Recursion](#recursion)
- [Async](#async)
- [DOM](#dom)
- [Browser BOM](#browser-bom)
- [JSON](#json)
- [Web API](#web-api)
- [Ajax](#ajax)
- [jQuery](#jquery)
- [Graphics](#graphics)
- [Best Practices](#best-practices)
- [Common Mistakes](#common-mistakes)
- [Performace](#performance)
- [ES6 Featues](#es6-features)
- [ES5 Features](#es5-features)
- [Snippets](#snippets)
- [Short Hands](#short-hands)
- [Interview Questions](#interview-questions)
- [List of GitHub Repositories to learn JavaScript](#list-of-github-repositories-to-learn-javascript)
- [List of Websites to learn JavaScript](#list-of-websites-to-learn-javascript)
- [List of Books to learn JavaScript](#list-of-books-to-learn-javascript)
- [List of YouTube Channels to learn JavaScript](#list-of-youtube-channels-to-learn-javascript)
- [List of Udemy Courses to learn JavaScript](#list-of-udemy-courses-to-learn-javascript)
- [List of Games to learn JavaScript by playing](#list-of-games-to-learn-javascript-by-playing)
- [List of Blogs Sites to learn JavaScript](#list-of-blogs-sites-to-learn-javascript)
- [List of JavaScript Online Editors/Compilers](#list-of-javascript-online-editorscompilers)
- [List of Twitter Users](#list-of-twitter-users)
- [List of LinkedIn Users](#list-of-linkedin-users)
## 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 `` 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>`** -
```html
<!DOCTYPE html>
<html>
<head>
<script>
//code
Heading
`**
```html
Heading
//code
```
**External JavaScript** -
```html
Heading
```
[Back to Top⤴️](#table-of-contents)
## Outputing JavaScript
### JavaScript can "display" data in different ways
**1. Writing into an HTML element, using `innerHTML`**
```html
My First Web Page
My First Paragraph
document.getElementById("demo").innerHTML = 5 + 6;
```
**2. Writing into an HTML element, using `document.write()`**
```html
My First Web Page
My first paragraph.
document.write(5 + 6);
```
**3. Writing into an alert box, using `window.alert()`**
```html
My First Web Page
My first paragraph.
window.alert(5 + 6);
```
**4. Writing into the browser console, using `console.log()`**
```html
console.log(5 + 6);
```
[Back to Top⤴️](#table-of-contents)
## Single Line Comments
Single line comments start with `//`
```jsx
// comments
```
## Multi-line Comments
Multi-line comments start with `/*` and end with `*/`.
```jsx
/* Hey!
Hello, How are you?
*/
```
[Back to Top⤴️](#table-of-contents)
## 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.
```jsx
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.
```jsx
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.
```jsx
const c = 1; // Declare a read-only variable z with the value 15 (block-level scope).
```
[Back to Top⤴️](#table-of-contents)
## 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.
```javascript
let number = 10;
```
**strings** - strings are text. They are written inside double or single quotes.
```javascript
let name = "Manthan";
```
**booleans** - booleans can only have two values: true or false.
```javascript
let value1 = true;
let value2 = false;
```
**null** - null is an empty value.
```javascript
let value = null;
```
**undefined** - undefined means a variable has been declared but has not yet been assigned a value.
```javascript
let name;
```
**symbol** - symbols are unique and immutable values.
```javascript
let a = Symbol();
```
[Back to Top⤴️](#table-of-contents)
### 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.
```javascript
function greet() {
return "Hello!";
}
```
**object** - objects are used to store collections of data and more complex entities.
```javascript
let name = {firstName:"Manthan", lastName:"Ank"};
```
**arrays** - arrays are used to store multiple values in a single variable.
```javascript
let array = ["value1", "value2"];
```
**regexp** - regular expressions are used to perform pattern-matching in strings.
```javascript
let pattern = /w3schools/i;
```
[Back to Top⤴️](#table-of-contents)
## 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
| Operator | Description |
| :-----------: | :-----------: |
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| ** | Exponentiation (ES2016) |
| / | Division |
| % | Modulus (Division Remainder) |
| ++ | Increment |
| -- | Decrement |
Examples
```javascript
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⤴️](#table-of-contents)
### Logical Operators
| Operator | Description |
| :-----------: | :-----------: |
| && | logical and |
| ll | logical or |
| ! | logical not |
Examples
```javascript
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
| Operator | Description |
| :-----------: | :-----------: |
| == | 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
```javascript |
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⤴️](#table-of-contents)
### Bitwise Operators
| Operator | Description |
| :-----------: | :-----------: |
| & | AND |
| l | OR |
| ~ | NOT |
| ^| XOR |
| << | Left shift |
| >> | Right shift |
| >>> | Unsigned right |
Examples
```javascript
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
| Operator | Description |
| :-----------: | :-----------: |
| typeof | Returns the type of a variable |
| instanceof | Returns true if an object is an instance of an object type |
Examples
```javascript
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⤴️](#table-of-contents)
### Assignment Operators
| Operator | Description |
| :-----------: | :-----------: |
| = | x = y |
| += | x += y |
| -= | x -= y |
| *= | x *= y |
| /= | x /= y |
| %= | x %= y |
| **= | x **= y |
| : | x : 45 |
```javascript
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⤴️](#table-of-contents)
### 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
```javascript
(condition) ? x : y
```
```javascript
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
```javascript
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⤴️](#table-of-contents)
### 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
```javascript
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
```javascript
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⤴️](#table-of-contents)
### 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
```javascript
// 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⤴️](#table-of-contents)
## Boolean
JavaScript booleans can have one of two values: true or false.
```javascript
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
```javascript
let value = true;
console.log(value.constructor); // Output: ƒ Boolean() { [native code] }
```
**prototype** - Allows you to add properties and methods to the Boolean prototype
```javascript
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
```javascript
let value = true;
console.log(value.toString()); // Output: "true"
```
**valueOf()** - Returns the primitive value of a boolean
```javascript
let value = true;
console.log(value.valueOf()); // Output: true
```
[Back to Top⤴️](#table-of-contents)
## Object
Objects are used to store key/value (name/value) collections.
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
let person = {
firstName: "Manthan",
lastName: "Ank",
};
console.log(person.toString()); // Output: "[object Object]"
```
**valueOf()** - Returns the primitive value of an object
```javascript
let person = {
firstName: "Manthan",
lastName: "Ank",
};
console.log(person.valueOf()); // Output: {firstName: "Manthan", lastName: "Ank"}
```
[Back to Top⤴️](#table-of-contents)
## Arrays
Arrays are used to store multiple values in a single variable.
```javascript
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⤴️](#table-of-contents)
**at()** - Returns the element at a specified index in an array
```javascript
let array = ['a', 'b', 'c'];
console.log(array.at(1)); // Output: "b"
```
**concat()** - Joins arrays and returns an array with the joined arrays.
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**entries()** - Returns a key/value pair Array Iteration Object
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**filter()** - Creates a new array with every element in an array that pass a test
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**flat()** - Flattens an array up to a specified depth
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**isArray()** - Checks whether an object is an array
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**lastIndexOf()** - Search the array for an element, starting at the end, and returns its position
```javascript
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
```javascript
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
```javascript
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
```javascript
let array = ['a', 'b', 'c'];
let element = array.pop();
console.log(array); // Output: ["a", "b"]
console.log(element); // Output: "c"
```
[Back to Top⤴️](#table-of-contents)
**prototype** - Allows you to add properties and methods to an Array object
```javascript
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
```javascript
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)
```javascript
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⤴️](#table-of-contents)
**reduceRight()** - Reduce the values of an array to a single value (going right-to-left)
```javascript
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
```javascript
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
```javascript
let array = ['a', 'b', 'c'];
let element = array.shift();
console.log(array); // Output: ["b", "c"]
console.log(element); // Output: "a"
```
[Back to Top⤴️](#table-of-contents)
**slice()** - Selects a part of an array, and returns the new array
```javascript
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
```javascript
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
```javascript
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⤴️](#table-of-contents)
**splice()** - Adds/Removes elements from an array
```javascript
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
```javascript
let array = ['a', 'b', 'c'];
console.log(array.toLocaleString()); // Output: "a,b,c"
```
**toReversed()** - Reverses the elements of an array
```javascript
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⤴️](#table-of-contents)
**toSorted()** - Sorts the elements of an array
```javascript
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
```javascript
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
```javascript
let array = ['a', 'b', 'c'];
console.log(array.toString()); // Output: "a,b,c"
```
[Back to Top⤴️](#table-of-contents)
**unshift()** - Adds new elements to the beginning of an array, and returns the new length
```javascript
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
```javascript
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
```javascript
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
```javascript
let array = ['a', 'b', 'c'];
Array.with = 25;
console.log(array); // Output: ["a", "b", "c"]
console.log(Array.with); // Output: 25
```
[Back to Top⤴️](#table-of-contents)
## Strings
Strings are used to store text. Strings must be enclosed in single or double quotes.
```javascript
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⤴️](#table-of-contents)
**at()** - Returns the character at a specified index (position)
```javascript
let myString = "Hello World!";
console.log(myString.at(0)); // Output: "H"
```
**charAt()** - Returns the character at a specified index (position)
```javascript
let myString = "Hello World!";
console.log(myString.charAt(0)); // Output: "H"
```
**charCodeAt()** - Returns the Unicode of the character at a specified index
```javascript
let myString = "Hello World!";
console.log(myString.charCodeAt(0)); // Output: 72
```
[Back to Top⤴️](#table-of-contents)
**concat()** - Returns two or more joined strings
```javascript
let myString1 = "Hello";
let myString2 = "World!";
let newString = myString1.concat(" ", myString2);
console.log(newString); // Output: "Hello World!"
```
**constructor** - Returns the string's constructor function
```javascript
let myString = "Hello World!";
console.log(myString.constructor); // Output: ƒ String() { [native code] }
```
[Back to Top⤴️](#table-of-contents)
**endsWith()** - Returns if a string ends with a specified value
```javascript
let myString = "Hello World!";
console.log(myString.endsWith("!")); // Output: true
```
**fromCharCode()** - Returns Unicode values as characters
```javascript
let myString = String.fromCharCode(72, 101, 108, 108, 111);
console.log(myString); // Output: "Hello"
```
[Back to Top⤴️](#table-of-contents)
**includes()** - Returns if a string contains a specified value
```javascript
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
```javascript
let myString = "Hello World!";
console.log(myString.indexOf("World")); // Output: 6
```
[Back to Top⤴️](#table-of-contents)
**lastIndexOf()** - Returns the index (position) of the last occurrence of a value in a string
```javascript
let myString = "Hello World! World!";
console.log(myString.lastIndexOf("World")); // Output: 13
```
**length** - Returns the length of a string
```javascript
let myString = "Hello World!";
console.log(myString.length); // Output: 12
```
[Back to Top⤴️](#table-of-contents)
**localeCompare()** - Compares two strings in the current locale
```javascript
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
```javascript
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
```javascript
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
```javascript
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
```javascript
let myString = "Hello";
let newString = myString.padStart(10, " World!");
console.log(myString); // Output: "Hello"
console.log(newString); // Output: " World!Hello"
```
[Back to Top⤴️](#table-of-contents)
**prototype** - Allows you to add properties and methods to an object
```javascript
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
```javascript
let myString = "Hello World!";
console.log(myString.repeat(2)); // Output: "Hello World!Hello World!"
```
[Back to Top⤴️](#table-of-contents)
**replace()** - Searches a string for a value, or a regular expression, and returns a string where the values are replaced
```javascript
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
```javascript
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⤴️](#table-of-contents)
**slice()** - Extracts a part of a string and returns a new string
```javascript
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
```javascript
let myString = "Hello World!";
let array = myString.split(" ");
console.log(myString); // Output: "Hello World!"
console.log(array); // Output: ["Hello", "World!"]
```
[Back to Top⤴️](#table-of-contents)
**startsWith()** - Checks whether a string begins with specified characters
```javascript
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)
```javascript
let myString = "Hello World!";
let newString = myString.substr(6, 5);
console.log(myString); // Output: "Hello World!"
console.log(newString); // Output: "World"
```
[Back to Top⤴️](#table-of-contents)
**substring()** - Extracts characters from a string, between two specified indices (positions)
```javascript
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
```javascript
let myString = "Hello World!";
console.log(myString.toLocaleLowerCase()); // Output: "hello world!"
```
[Back to Top⤴️](#table-of-contents)
**toLocaleUpperCase()** - Returns a string converted to uppercase letters, using the host's locale
```javascript
let myString = "Hello World!";
console.log(myString.toLocaleUpperCase()); // Output: "HELLO WORLD!"
```
**toLowerCase()** - Returns a string converted to lowercase letters
```javascript
let myString = "Hello World!";
console.log(myString); // Output: "Hello World!"
console.log(myString.toLowerCase()); // Output: "hello world!"
```
[Back to Top⤴️](#table-of-contents)
**toString()** - Returns a string or a string object as a string
```javascript
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
```javascript
let myString = "Hello World!";
console.log(myString); // Output: "Hello World!"
console.log(myString.toUpperCase()); // Output: "HELLO WORLD
```
[Back to Top⤴️](#table-of-contents)
**trim()** - Returns a string with removed whitespaces
```javascript
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
```javascript
let myString = " Hello World! ";
console.log(myString); // Output: " Hello World! "
console.log(myString.trimEnd()); // Output: " Hello World!"
```
[Back to Top⤴️](#table-of-contents)
**trimStart()** - Returns a string with removed whitespaces from the start
```javascript
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.
```javascript
let myString = "Hello World!";
console.log(myString.valueOf()); // Output: "Hello World!"
```
[Back to Top⤴️](#table-of-contents)
## Objects
Objects are used to store collections of data and more complex entities.
```javascript
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⤴️](#table-of-contents)
**assign()** - Copies the values of all enumerable own properties from one or more source objects to a target object
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
const newPerson = Object.create(person);
console.log(newPerson); // Output: {}
```
[Back to Top⤴️](#table-of-contents)
**defineProperties()** - Defines new or modifies existing properties directly on an object, returning the object
```javascript
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
```javascript
const person = {};
Object.defineProperty(person, "firstName", {
value: "Manthan",
writable: true,
});
console.log(person); // Output: {firstName: "Manthan"}
```
[Back to Top⤴️](#table-of-contents)
**entries()** - Returns an array of a given object's own enumerable string-keyed property [key, value] pairs
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
Object.freeze(person);
person.age = 25;
console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}
```
[Back to Top⤴️](#table-of-contents)
**fromEntries()** - Returns a new object from an iterable of [key, value] pairs
```javascript
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
```javascript
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⤴️](#table-of-contents)
**getOwnPropertyDescriptors()** - Returns all own property descriptors of a given object
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
const properties = Object.getOwnPropertyNames(person);
console.log(properties); // Output: ["firstName", "lastName"]
```
[Back to Top⤴️](#table-of-contents)
**getOwnPropertySymbols()** - Returns an array of all symbol properties found directly upon a given object
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
const prototype = Object.getPrototypeOf(person);
console.log(prototype); // Output: {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
```
[Back to Top⤴️](#table-of-contents)
**groupBy()** - Groups the elements of an array based on the given function
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
console.log(person.hasOwn("firstName")); // Output: true
```
[Back to Top⤴️](#table-of-contents)
**is()** - Compares if two values are the same value
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
console.log(Object.isExtensible(person)); // Output: true
```
[Back to Top⤴️](#table-of-contents)
**isFrozen()** - Returns a boolean indicating if the object is frozen
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
Object.seal(person);
console.log(Object.isSealed(person)); // Output: true
```
[Back to Top⤴️](#table-of-contents)
**keys()** - Returns an array of a given object's own enumerable property names
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
const keys = Object.keys(person);
console.log(keys); // Output: ["firstName", "lastName"]
```
**preventExtensions()** - Prevents any extensions of an object
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
Object.preventExtensions(person);
person.age = 25;
console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}
```
[Back to Top⤴️](#table-of-contents)
**prototype** - Allows you to add properties and methods to an object
```javascript
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
```javascript
const person = {
firstName: "Manthan",
lastName: "Ank",
};
Object.seal(person);
delete person.firstName;
console.log(person); // Output: {firstName: "Manthan", lastName: "Ank"}
```
[Back to Top⤴️](#table-of-contents)
**setPrototypeOf()** - Sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null
```javascript
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
```javascript
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⤴️](#table-of-contents)
### for loop
This type of loop is used to execute a block of code a specified number of times.
```javascript
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.
```javascript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
```
[Back to Top⤴️](#table-of-contents)
### 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.
```javascript
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.
```javascript
let obj = {a: 1, b: 2, c: 3};
for (let prop in obj) {
console.log(prop + ": " + obj[prop]);
}
```
[Back to Top⤴️](#table-of-contents)
### for of loop
This type of loop is used to iterate over the iterable objects such as arrays, strings, and maps.
```javascript
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⤴️](#table-of-contents)
## if statement
The if statement is used to execute a block of code if a specified condition is true.
```javascript
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.
```javascript
if (x > 0) {
console.log("x is greater than 0");
} else {
console.log("x is not greater than 0");
}
```
[Back to Top⤴️](#table-of-contents)
### 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.
```javascript
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.
```javascript
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⤴️](#table-of-contents)
## 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 ().
```jsx
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⤴️](#table-of-contents)
### 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.
```javascript
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 ().
```javascript
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.
```javascript
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⤴️](#table-of-contents)
## IIFE
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
```javascript
(function() {
console.log("Hello World!");
})();
```
[Back to Top⤴️](#table-of-contents)
## Higher-Order Functions
A higher-order function is a function that takes another function as an argument or returns a function as a result.
```javascript
function greet() {
return "Hello World!";
}
function greetUser(greet) {
return greet();
}
console.log(greetUser(greet)); // Output: "Hello World!"
```
[Back to Top⤴️](#table-of-contents)
## Function Expression
A function expression is a function that is assigned to a variable.
```javascript
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.
```javascript
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.
```javascript
const greet = new Function("return 'Hello World!'");
console.log(greet()); // Output: "Hello World!"
```
[Back to Top⤴️](#table-of-contents)
## 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
```javascript
let a = 10;
function myFunction() {
console.log(a);
}
myFunction();
```
### Block Scope
```javascript
//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⤴️](#table-of-contents)
### Function Scope
```javascript
//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⤴️](#table-of-contents)
## Hoisting
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase.
```javascript
console.log(x); // Output: undefined
var x = 5;
```
[Back to Top⤴️](#table-of-contents)
## 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.
```javascript
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.
```javascript
new Date()
```
[Back to Top⤴️](#table-of-contents)
### Date Formats
There are several ways to create a new Date object in JavaScript:
```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⤴️](#table-of-contents)
### Date Properties
**constructor** - Returns the function that created the Date object's prototype
```javascript
const d = new Date();
d.constructor; // ƒ Date() { [native code] }
```
**prototype** - Allows you to add properties and methods to the Date object
```javascript
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
```javascript
const d = new Date();
d.UTC(); // 1642149980524
```
[Back to Top⤴️](#table-of-contents)
**parse** - Parses a date string and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
```javascript
Date.parse("Jan 1, 2023"); // 1672531200000
```
**now** - Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC
```javascript
Date.now(); // 1642149980524
```
[Back to Top⤴️](#table-of-contents)
### Date Methods
**toString** - It is a built-in function that can be used to convert a date object to a string.
```javascript
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".
```javascript
const d = new Date();
d.toDateString(); // 'Sat Jan 14 2023'
```
[Back to Top⤴️](#table-of-contents)
**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".
```javascript
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".
```javascript
const d = new Date();
d.toISOString(); // '2023-01-14T05:06:20.524Z'
```
[Back to Top⤴️](#table-of-contents)
## 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.
```javascript
const d = new Date();
d.getFullYear();
```
**getMonth** - returns the month of the date (0-11, where 0 represents January and 11 represents December).
```javascript
const d = new Date();
d.getMonth();
```
[Back to Top⤴️](#table-of-contents)
**getDate** - returns the day of the month of the date (1-31).
```javascript
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).
```javascript
const d = new Date();
d.getDay();
```
**getHours** - returns the hour of the date (0-23).
```javascript
const d = new Date();
d.getHours();
```
[Back to Top⤴️](#table-of-contents)
**getMinutes** - returns the minutes of the date (0-59).
```javascript
const d = new Date();
d.getMinutes();
```
**getSeconds** - returns the seconds of the date (0-59).
```javascript
const d = new Date();
d.getSeconds();
```
[Back to Top⤴️](#table-of-contents)
**getMilliseconds** - returns the milliseconds of the date (0-999).
```javascript
const d = new Date();
d.getMilliseconds();
```
**getTime** - returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.
```javascript
const d = new Date();
d.getTime();
```
[Back to Top⤴️](#table-of-contents)
## Date Set Methods
**setDate** - sets the day of the month of the date object.
```javascript
const d = new Date();
d.setDate(15);
```
**setFullYear** - sets the year, and optionally the month and date, of the date object.
```javascript
const d = new Date();
d.setFullYear(2020);
```
[Back to Top⤴️](#table-of-contents)
**setHours** - sets the hours, minutes, seconds and milliseconds of the date object.
```javascript
const d = new Date();
d.setHours(22);
```
**setMilliseconds** - sets the milliseconds of the date object.
```javascript
const d = new Date();
d.setMilliSeconds(3000);
```
**setMinutes** - sets the minutes, seconds and milliseconds of the date object.
```javascript
const d = new Date();
d.setMinutes(30);
```
[Back to Top⤴️](#table-of-contents)
**setSeconds** - sets the seconds and milliseconds of the date object.
```javascript
const d = new Date();
d.setSeconds(30);
```
**setMonth** - sets the month, and optionally the date, of the date object.
```javascript
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.
```javascript
const d = new Date();
d.setTime(30);
```
[Back to Top⤴️](#table-of-contents)
## 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.
```javascript
Number("3.14") // 3.14
Number(Math.PI) // 3.141592653589793
Number(" ") // 0
Number("") // 0
Number("99 88") // NaN
Number("John") // NaN
```
[Back to Top⤴️](#table-of-contents)
**parseFloat** - Converts a string to a floating-point number using the parseFloat() method.
```javascript
let num = parseFloat("123.456");
console.log(num); // Output: 123.456
```
[Back to Top⤴️](#table-of-contents)
**parseInt** - Converts a string to an integer using the parseInt() method.
```javascript
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.
```javascript
let str = String(123);
console.log(str); // Output: "123"
```
[Back to Top⤴️](#table-of-contents)
**toString** - Converts a number to a string using the toString() method.
```javascript
let str = (123).toString();
console.log(str); // Output: "123"
```
**toExponential** - Converts a number to a string, using toExponential() method.
```javascript
let str = (123).toExponential();
console.log(str); // Output: 1.23e+2
```
**toFixed** - Converts a number to a string, using toFixed() method.
```javascript
let str = (123).toFixed();
console.log(str); // Output: 123
```
[Back to Top⤴️](#table-of-contents)
**toPrecision** - Converts a number to a string, using toPrecision() method.
```javascript
let str = (123).toPrecision();
console.log(str); // Output: 123
```
### Convert dates to numbers
**Number** - Converts a date to a number using the Number() function.
```javascript
d = new Date();
Number(d) // 1673677425068
```
[Back to Top⤴️](#table-of-contents)
**getTime** Converts a date to a number using the getTime() method.
```javascript
d = new Date();
d.getTime() // 1673677461233
```
**string** - Converts a date to a string using the String() function.
```javascript
String(Date()) // 'Sat Jan 14 2023 11:54:38 GMT+0530 (India Standard Time)'
```
[Back to Top⤴️](#table-of-contents)
**toString** - Converts a date to a string using the toString() method.
```javascript
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.
```javascript
Number(false) // returns 0
Number(true) // returns 1
```
[Back to Top⤴️](#table-of-contents)
### Convert boolean to string
**string** - Converts a boolean to a string using the String() function.
```javascript
String(false) // returns "false"
String(true) // returns "true"
```
| Original Value | Converted to Number | Converted to String | Converted to Boolean |
|---|---|---|---|
| false | 0 | "false" | false |
| true | 1 | "true" | true |
| 0 | 0 | "0" | false |
| 1 | 1 | "1" | true |
| "0" | 0 | "0" | true |
| "000" | 0 | "000" | true |
| "1" | 1 | "1" | true |
| NaN | NaN | "NaN" | false |
| Infinity | Infinity | "Infinity" | true |
| -Infinity | -Infinity | "-Infinity" | true |
| "" | 0 | "" | false |
| "20" | 20 | "20" | true |
| "twenty" | NaN | "twenty" | true |
| [ ] | 0 | "" | true |
| [20] | 20 | "20" | true |
| [10,20] | NaN | "10,20" | true |
| ["twenty"] | NaN | "twenty" | true |
| ["ten","twenty"] | NaN | "ten,twenty" | true |
| function(){} | NaN | "function(){}" | true |
| { } | NaN | "[object Object]" | true |
| null | 0 | "null" | false |
| undefined | NaN | "undefined" | false |
[Back to Top⤴️](#table-of-contents)
## Typeof
The typeof operator is used to get the data type of a variable or an expression.
```javascript
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
```
[Back to Top⤴️](#table-of-contents)
Keep in mind that
- The data type of NaN is number
- The data type of an array is object
- The data type of a date is object
- The data type of null is object
- The data type of an undefined variable is undefined *
- The data type of a variable that has not been assigned a value is also undefined *
## Math
The Math object allows you to perform mathematical tasks on numbers.
```javascript
Math.PI // returns 3.141592653589793
```
[Back to Top⤴️](#table-of-contents)
### Math Property
```javascript
Math.property
```
Example
```javascript
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
```
[Back to Top⤴️](#table-of-contents)
### Math Methods
The Math object has several built-in methods that can be used to perform mathematical tasks. Some of the most commonly used methods are:
**Math.round** - Returns x rounded to its nearest integer
```javascript
Math.round(4.6); // 5
```
**Math.ceil** - Returns x rounded up to its nearest integer
```javascript
Math.ceil(4.4); // 5
```
[Back to Top⤴️](#table-of-contents)
**Math.floor** - Returns x rounded down to its nearest integer
```javascript
Math.floor(4.7); // 4
```
**Math.trunc** - Returns the integer part of x (new in ES6)
```javascript
Math.trunc(4.7); // 4
```
[Back to Top⤴️](#table-of-contents)
**Math.sign** - Returns if x is negative, null or positive.
```javascript
Math.sign(4); // 1
```
**Math.pow** - returns the value of x to the power of y.
```javascript
Math.pow(8, 2); // 64
```
**Math.sqrt** - returns the square root of x.
```javascript
Math.sqrt(64); // 8
```
[Back to Top⤴️](#table-of-contents)
**Math.abs** - returns the absolute (positive) value of x.
```javascript
Math.abs(-4.7); // 4.7
```
**Math.sin** - returns the sine (a value between -1 and 1) of the angle x (given in radians).
```javascript
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)
```
**Math.cos** - returns the cosine (a value between -1 and 1) of the angle x (given in radians).
```javascript
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
```
[Back to Top⤴️](#table-of-contents)
**Math.min** - It can be used to find the lowest value in a list of arguments.
```javascript
Math.min(0, 150, 30, 20, -8, -200); // -200
```
**Math.max** - It can be used to find the highest value in a list of arguments.
```javascript
Math.max(0, 150, 30, 20, -8, -200); // 150
```
**Math.random** - returns a random number between 0 (inclusive), and 1 (exclusive).
```javascript
Math.random(); // 0.07840484495533051
```
[Back to Top⤴️](#table-of-contents)
**Math.log** - returns the natural logarithm of x.
```javascript
Math.log(1); // 0
```
**Math.log2** - returns the base 2 logarithm of x.
```javascript
Math.log2(8); // 3
```
**Math.log10** - returns the base 10 logarithm of x.
```javascript
Math.log10(1000); // 3
```
[Back to Top⤴️](#table-of-contents)
| Method | Description |
|---|---|
| abs(x) | Returns the absolute value of x |
| acos(x) | Returns the arccosine of x, in radians |
| acosh(x) | Returns the hyperbolic arccosine of x |
| asin(x) | Returns the arcsine of x, in radians |
| asinh(x) | Returns the hyperbolic arcsine of x |
| atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
| atan2(y, x) | Returns the arctangent of the quotient of its arguments |
| atanh(x) | Returns the hyperbolic arctangent of x |
| cbrt(x) | Returns the cubic root of x |
| ceil(x) | Returns x, rounded upwards to the nearest integer |
| cos(x) | Returns the cosine of x (x is in radians) |
| cosh(x) | Returns the hyperbolic cosine of x |
| exp(x) | Returns the value of Ex |
| floor(x) | Returns x, rounded downwards to the nearest integer |
| log(x) | Returns the natural logarithm (base E) of x |
| max(x, y, z, ..., n) | Returns the number with the highest value |
| min(x, y, z, ..., n) | Returns the number with the lowest value |
| pow(x, y) | Returns the value of x to the power of y |
| random() | Returns a random number between 0 and 1 |
| round(x) | Rounds x to the nearest integer |
| sign(x) | Returns if x is negative, null or positive (-1, 0, 1) |
| sin(x) | Returns the sine of x (x is in radians) |
| sinh(x) | Returns the hyperbolic sine of x |
| sqrt(x) | Returns the square root of x |
| tan(x) | Returns the tangent of an angle |
| tanh(x) | Returns the hyperbolic tangent of a number |
| trunc(x) | Returns the integer part of a number (x) |
## Sets
A Set is a collection of unique values. A Set can hold any datatype, including primitive types and objects.
```javascript
const letters = new Set(["a","b","c"]);
```
[Back to Top⤴️](#table-of-contents)
### Set Properties
**constructor** - Returns the function that created the Set object's prototype
```javascript
letters.constructor; // ƒ Set() { [native code] }
```
**prototype** - Allows you to add properties and methods to a Set object
```javascript
Set.prototype.size = 0;
const letters = new Set(["a","b","c"]);
letters.size; // 3
```
[Back to Top⤴️](#table-of-contents)
### Set Methods
The Set object has several built-in methods that can be used to work with Sets. Some of the most commonly used methods are:
- new Set()
- add()
- delete()
- has()
- forEach()
- values()
- size
**new Set** - Creates a new Set
```javascript
const letters = new Set(["a","b","c"]);
```
[Back to Top⤴️](#table-of-contents)
**add** - Adds a new element to the Set
```javascript
letters.add("d");
```
**delete** - Removes an element from a Set
```javascript
letters.delete("d");
```
**has** - Returns true if a value exists in the Set
```javascript
letters.has("a");
```
[Back to Top⤴️](#table-of-contents)
**forEach** - Invokes a callback for each element in the Set
```javascript
// Create a Set
const letters = new Set(["a", "b", "c"]);
// List all Elements
let text = "";
letters.forEach(function(value) {
text += value + " ";
});
console.log(text.trim()); // Output: "a b c"
```
**values** - Returns an iterator with all the values in a Set
```javascript
letters.values() // Returns [object Set Iterator]
```
[Back to Top⤴️](#table-of-contents)
**size Property** - Returns the number of elements in a Set
```javascript
letters.size;
```
## Map
A Map holds key-value pairs where the keys can be any datatype. A Map remembers the original insertion order of the keys.
```javascript
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
```
[Back to Top⤴️](#table-of-contents)
### Map Properties
**constructor** - Returns the function that created the Map object's prototype
```javascript
fruits.constructor; // ƒ Map() { [native code] }
```
**prototype** - Allows you to add properties and methods to a Map object
```javascript
Map.prototype.size = 0;
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
fruits.size; // 3
```
[Back to Top⤴️](#table-of-contents)
### Map Methods
The Map object has several built-in methods that can be used to work with Maps. Some of the most commonly used methods are:
- new Map()
- set()
- get()
- delete()
- has()
- forEach()
- entries()
- size
**new Map** - Creates a new Map
```javascript
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
```
[Back to Top⤴️](#table-of-contents)
**set** - Sets the value for a key in a Map
```javascript
// Create a Map
const fruits = new Map();
// Set Map Values
fruits.set("apples", 500);
fruits.set("bananas", 300);
fruits.set("oranges", 200);
```
**get** - Gets the value for a key in a Map
```javascript
fruits.get("apples"); // Returns 500
```
**delete** - Removes a Map element specified by the key
```javascript
fruits.delete("apples");
```
[Back to Top⤴️](#table-of-contents)
**has** - Returns true if a key exists in a Map
```javascript
fruits.has("apples");
```
**forEach** - Calls a function for each key/value pair in a Map
```javascript
// List all entries
let text = "";
fruits.forEach (function(value, key) {
text += key + ' = ' + value;
})
```
**entries** - Returns an iterator with the [key, value] pairs in a Map.
```javascript
// List all entries
let text = "";
for (const x of fruits.entries()) {
text += x;
}
```
**size Property** - Returns the number of elements in a Map
```javascript
fruits.size;
```
[Back to Top⤴️](#table-of-contents)
## Recursion
Recursion is a programming technique where a function calls itself in order to solve a problem. Recursion is used to solve problems that can be broken down into smaller, more manageable subproblems.
```javascript
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
factorial(5); // 120
```
[Back to Top⤴️](#table-of-contents)
## Async
Asynchronous programming allows you to run multiple tasks concurrently without blocking the main thread. JavaScript provides several ways to work with asynchronous code, including callbacks, promises, and async/await.
### Callbacks
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
```javascript
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
// Output: 10
```
[Back to Top⤴️](#table-of-contents)
### Asynchronous JavaScript
JavaScript is a single-threaded language, which means it can only execute one task at a time. Asynchronous JavaScript allows you to run multiple tasks concurrently without blocking the main thread.
```javascript
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("The async operation was successful");
}, 1000);
});
myPromise.then((value) => {
console.log(value);
});
// Output: The async operation was successful
```
### Promise
A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Syntax -
```javascript
const myPromise = new Promise((resolve, reject) => {
// code
});
myPromise.then(
(value) => {
// success
},
(error) => {
// error
}
);
myPromise.catch(
(error) => {
// error
}
);
myPromise.finally(
() => {
// code
}
);
myPromise.all([promise1, promise2, promise3, ...])
```
Example
```javascript
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("The async operation was successful");
}, 1000);
});
myPromise.then((value) => {
console.log(value);
});
// Output: The async operation was successful
```
[Back to Top⤴️](#table-of-contents)
### async/await
The async/await syntax allows you to write asynchronous code that looks synchronous. The async keyword is used to define an asynchronous function, and the await keyword is used to wait for a promise to be resolved.
Async Syntax
```javascript
async function myFunction() {
// code
}
```
Await Syntax
```javascript
let result = await promise;
// or
await promise;
```
Example
```javascript
async function myFunction() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("The async operation was successful"), 1000);
});
let result = await promise;
console.log(result);
}
myFunction();
// Output: The async operation was successful
```
[Back to Top⤴️](#table-of-contents)
## DOM
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of nodes, where each node is an object representing a part of the document.
### DOM Properties
**document.body** - Returns the body element
```javascript
document.body;
```
**document.cookie** - Returns the document's cookie
```javascript
document.cookie;
```
**document.doctype** - Returns the document's doctype
```javascript
document.doctype;
```
[Back to Top⤴️](#table-of-contents)
**document.documentElement** - Returns the document's root element
```javascript
document.documentElement;
```
**document.documentURI** - Returns the URI of the document
```javascript
document.documentURI;
```
**document.domain** - Returns the domain name of the server that loaded the document
```javascript
document.domain;
```
[Back to Top⤴️](#table-of-contents)
**document.head** - Returns the head element
```javascript
document.head;
```
**document.images** - Returns a collection of all images in the document
```javascript
document.images;
```
**document.lastModified** - Returns the date and time the document was last modified
```javascript
document.lastModified;
```
**document.links** - Returns a collection of all links in the document
```javascript
document.links;
```
[Back to Top⤴️](#table-of-contents)
**document.readyState** - Returns the loading status of the document
```javascript
document.readyState;
```
**document.referrer** - Returns the URI of the referrer (the linking document)
```javascript
document.referrer;
```
**document.title** - Returns the title of the document
```javascript
document.title;
```
**document.URL** - Returns the complete URL of the document
```javascript
document.URL;
```
[Back to Top⤴️](#table-of-contents)
### DOM Methods
The Document object has several built-in methods that can be used to manipulate the document. Some of the most commonly used methods are:
addEventListener() - It is used to add an event listener to the document.
```javascript
document.addEventListener("click", () => {
console.log("The document was clicked");
});
```
adoptNode() - It is used to adopt the node from the other documents.
```javascript
document.adoptNode(node);
```
[Back to Top⤴️](#table-of-contents)
append() - It appends the new node or HTML after the last child node of the document.
```javascript
document.append(node);
```
caretPositionFromPoint() - It returns the caretPosition object, containing the DOM node based on the coordinates passed as an argument.
```javascript
document.caretPositionFromPoint(x, y);
```
close() - It closes the output stream opened using the document.open() method.
```javascript
document.close();
```
[Back to Top⤴️](#table-of-contents)
createAttribute() - It creates a new attribute node.
```javascript
document.createAttribute("class");
```
createAttributeNS() - It creates a new attribute node with the particular namespace URI.
```javascript
document.createAttributeNS("http://www.w3.org/2000/svg", "class");
```
createComment() - It creates a new comment node with a specific text message.
```javascript
document.createComment("This is a comment");
```
[Back to Top⤴️](#table-of-contents)
createDocumentFragment() - It creates a DocumentFragment node.
```javascript
document.createDocumentFragment();
```
createElement() - It creates a new element node to insert into the web page.
```javascript
document.createElement("div");
```
createElementNS() - It is used to create a new element node with a particular namespace URI.
```javascript
document.createElementNS("http://www.w3.org/2000/svg", "div");
```
createEvent() - It creates a new event node.
```javascript
document.createEvent("Event");
```
[Back to Top⤴️](#table-of-contents)
createTextNode() - It creates a new text node.
```javascript
document.createTextNode("This is a text node");
```
elementFromPoint() - It accesses the element from the specified coordinates.
```javascript
document.elementFromPoint(x, y);
```
elementsFromPoint() - It returns the array of elements that are at the specified coordinates.
```javascript
document.elementsFromPoint(x, y);
```
[Back to Top⤴️](#table-of-contents)
getAnimations() - It returns the array of all animations applied on the document.
```javascript
document.getAnimations();
```
getElementById() - It accesses the HTML element using the id.
```javascript
document.getElementById("id");
```
getElementsByClassName() - It accesses the HTML element using the class name.
```javascript
document.getElementsByClassName("class");
```
[Back to Top⤴️](#table-of-contents)
getElementsByName() - It accesses the HTML element using the name.
```javascript
document.getElementsByName("name");
```
getElementsByTagName() - It accesses the HTML element using the tag name.
```javascript
document.getElementsByTagName("tag");
```
hasFocus() - It returns the boolean value based on whether any element or document itself is in the focus.
```javascript
document.hasFocus();
```
[Back to Top⤴️](#table-of-contents)
importNode() - It is used to import the node from another document.
```javascript
document.importNode(node);
```
normalize() - It removes the text nodes, which are empty, and joins other nodes.
```javascript
document.normalize();
```
open() - It is used to open a new output stream.
```javascript
document.open();
```
[Back to Top⤴️](#table-of-contents)
prepand() - It is used to insert the particular node before all nodes.
```javascript
document.prepand(node);
```
querySelector() - It is used to select the first element that matches the css selector passed as an argument.
```javascript
document.querySelector("p");
```
querySelectorAll() - It returns the nodelist of the HTML elements, which matches the multiple CSS selectors.
```javascript
document.querySelectorAll("p.intro");
```
[Back to Top⤴️](#table-of-contents)
removeEventListener() - It is used to remove the event listener from the document.
```javascript
document.removeEventListener("click", () => {
console.log("The document was clicked");
});
```
replaceChildren() - It replaces the children nodes of the document.
```javascript
document.replaceChildren(node);
```
[Back to Top⤴️](#table-of-contents)
write() - It is used to write text, HTML, etc., into the document.
```javascript
document.write("Hello World!");
```
writeln() - It is similar to the write() method but writes each statement in the new line.
```javascript
document.writeln("Hello World!");
```
[Back to Top⤴️](#table-of-contents)
### Documents
The Document object represents the entire HTML document. It is the root node of the HTML document tree.
**Finding HTML Elements** -
| Method | Description |
|---|---|
| document.getElementById(id) | Find an element by element id |
| document.getElementsByTagName(name) | Find elements by tag name |
| document.getElementsByClassName(name) | Find elements by class name |
**Changing HTML Elements** -
| Property | Description |
|--|--|
| element.innerHTML = new html content | Change the inner HTML of an element |
| element.attribute = new value | Change the attribute value of an HTML element |
| element.style.property = new style | Change the style of an HTML element |
| Method | Description |
|--|--|
| element.setAttribute(attribute, value) | Change the attribute value of an HTML element |
[Back to Top⤴️](#table-of-contents)
**Adding and Deleting Elements** -
| Method | Description |
|--|--|
| document.createElement(element) | Create an HTML element |
| document.removeChild(element) | Remove an HTML element |
| document.appendChild(element) | Add an HTML element |
| document.replaceChild(new, old) | Replace an HTML element |
| document.write(text) | Write into the HTML output stream |
**Adding Events Handlers** -
| Method | Description |
|--|--|
| document.getElementById(id).onclick = function(){code} | Adding event handler code to an onclick event |
**Finding HTML Objects** -
| Property | Description | DOM |
|--|--|--|
| document.anchors | Returns all elements that have a name attribute | 1 |
| document.applets | Deprecated | 1 |
| document.baseURI | Returns the absolute base URI of the document | 3 |
| document.body | Returns the element | 1 |
| document.cookie | Returns the document's cookie | 1 |
| document.doctype | Returns the document's doctype | 3 |
| document.documentElement | Returns the element | 3 |
| document.documentMode | Returns the mode used by the browser | 3 |
| document.documentURI | Returns the URI of the document | 3 |
| document.domain | Returns the domain name of the document server | 1 |
| document.domConfig | Obsolete. | 3 |
| document.embeds | Returns all elements | 3 |
| document.forms | Returns all elements | 1 |
| document.head | Returns the element | 3 |
| document.images | Returns all elements | 1 |
| document.implementation | Returns the DOM implementation | 3 |
| document.inputEncoding | Returns the document's encoding (character set) | 3 |
| document.lastModified | Returns the date and time the document was updated | 3 |
| document.links | Returns all and elements that have a href attribute | 1 |
| document.readyState | Returns the (loading) status of the document | 3 |
| document.referrer | Returns the URI of the referrer (the linking document) | 1 |
| document.scripts | Returns all elements | 3 |
| document.strictErrorChecking | Returns if error checking is enforced | 3 |
| document.title | Returns the element | 1 |
| document.URL | Returns the complete URL of the document | 1 |
[Back to Top⤴️](#table-of-contents)
**Elements** -
Finding HTML elements by id
```javascript
const element = document.getElementById("intro");
```
Finding HTML elements by tag name
```javascript
const element = document.getElementsByTagName("p");
```
Finding HTML elements by class name
```javascript
const x = document.getElementsByClassName("intro");
```
Finding HTML elements by CSS selectors
```javascript
const x = document.querySelectorAll("p.intro");
```
[Back to Top⤴️](#table-of-contents)
Finding HTML elements by HTML object collections
```javascript
const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "
";
}
document.getElementById("demo").innerHTML = text;
```
Changing HTML
```javascript
document.getElementById("demo").innerHTML = "Hello World!";
```
Forms
```javascript
document.getElementById("myForm").submit();
```
Changing CSS
```javascript
document.getElementById("demo").style.fontSize = "35px";
```
[Back to Top⤴️](#table-of-contents)
Animations
```javascript
document.getElementById("animate").style.animation = "mymove 4s infinite";
```
Events
```javascript
document.getElementById("myBtn").addEventListener("click", displayDate);
```
Event Listener
```javascript
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
```
[Back to Top⤴️](#table-of-contents)
Navigation
```javascript
document.getElementById("myAnchor").href = "https://www.w3schools.com";
```
Nodes
```javascript
document.getElementById("demo").childNodes[0].nodeValue = "new text";
```
Collections
```javascript
document.getElementsByTagName("p");
```
Node
```javascript
document.getElementById("main").firstChild.nodeValue;
```
Lists
```javascript
document.getElementById("myList").innerHTML = "Mango";
```
[Back to Top⤴️](#table-of-contents)
## Browser BOM
Browser Object Model (BOM) is used to interact with the browser. The Browser Object Model (BOM) allows JavaScript to interact with the browser. The BOM is not standardized, and its properties and methods may differ between browsers.
**Window** -
Window Object
```javascript
window.document.getElementById("header");
//or
document.getElementById("header");
```
Window Size
window.innerHeight - the inner height of the browser window (in pixels)
window.innerWidth - the inner width of the browser window (in pixels)
window.open() - open a new window
window.close() - close the current window
window.moveTo() - move the current window
window.resizeTo() - resize the current window
```javascript
window.innerWidth;
window.innerHeight;
```
[Back to Top⤴️](#table-of-contents)
**Window Screen** -
`window.screen` - object contains information about the user's screen.
screen.width
```javascript
document.getElementById("demo").innerHTML =
"Screen Width: " + screen.width;
```
screen.height
```javascript
document.getElementById("demo").innerHTML =
"Screen Height: " + screen.height;
```
screen.availWidth
```javascript
document.getElementById("demo").innerHTML =
"Available Screen Width: " + screen.availWidth;
```
screen.availHeight
```javascript
document.getElementById("demo").innerHTML =
"Available Screen Height: " + screen.availHeight;
```
screen.colorDepth
```javascript
document.getElementById("demo").innerHTML =
"Screen Color Depth: " + screen.colorDepth;
```
screen.pixelDepth
```javascript
document.getElementById("demo").innerHTML =
"Screen Pixel Depth: " + screen.pixelDepth;
```
[Back to Top⤴️](#table-of-contents)
Example
```javascript
document.getElementById('demo1').innerHTML = 'Screen Width: ' + screen.width;
document.getElementById('demo2').innerHTML = 'Screen Height: ' + screen.height;
document.getElementById('demo3').innerHTML =
'Available Screen Width: ' + screen.availWidth;
document.getElementById('demo4').innerHTML =
'Available Screen Height: ' + screen.availHeight;
document.getElementById('demo5').innerHTML =
'Screen Color Depth: ' + screen.colorDepth;
document.getElementById('demo6').innerHTML =
'Screen Pixel Depth: ' + screen.pixelDepth;
```
```html
Window Screen
```
[Stackblitz Link](https://stackblitz.com/edit/web-platform-paqevc?file=index.html)
[Back to Top⤴️](#table-of-contents)
Window Location
`window.location` - object can be used to get the current page address (URL) and to redirect the browser to a new page.
window.location.href returns the href (URL) of the current page
```javascript
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
```
window.location.hostname returns the domain name of the web host
```javascript
document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;
```
window.location.pathname returns the path and filename of the current page
```javascript
document.getElementById("demo").innerHTML =
"Page path is " + window.location.pathname;
```
window.location.protocol returns the web protocol used (http: or https:)
```javascript
document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;
```
window.location.assign() loads a new document
```javascript
document.getElementById("demo").innerHTML =
"Port number is " + window.location.port;
```
[Back to Top⤴️](#table-of-contents)
Window Location Assign
```javascript
JavaScript
The window.location object
function newDoc() {
window.location.assign("https://www.w3schools.com")
}
```
Example
```javascript
document.getElementById('demo1').innerHTML =
'Page location is ' + window.location.href;
document.getElementById('demo2').innerHTML =
'Page hostname is ' + window.location.hostname;
document.getElementById('demo3').innerHTML =
'Page path is ' + window.location.pathname;
document.getElementById('demo4').innerHTML =
'Page protocol is ' + window.location.protocol;
document.getElementById('demo5').innerHTML =
'Port number is ' + window.location.port;
```
```html
Window Location
Window Location Example
```
[Stackblitz Link](https://stackblitz.com/edit/web-platform-sixdd6?file=script.js)
[Back to Top⤴️](#table-of-contents)
**Window History** - The window.history object contains the browser's history.
`window.history` - object can be written without the window prefix.
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser
```javascript
window.history.back()
window.history.forward()
```
```html
Window History
Window History
```
[Back to Top⤴️](#table-of-contents)
**Window Navigator** - Window Navigator object contains information about the visitor's browser.
navigator.cookieEnabled
navigator.appCodeName
navigator.platform
Browser Cookies
```javascript
document.getElementById("demo").innerHTML =
"cookiesEnabled is " + navigator.cookieEnabled;
```
Browser Application Name
```javascript
document.getElementById("demo").innerHTML =
"navigator.appName is " + navigator.appName;
```
Browser Application Code Name
```javascript
document.getElementById("demo").innerHTML =
"navigator.appCodeName is " + navigator.appCodeName;
```
[Back to Top⤴️](#table-of-contents)
Browser Engine
```javascript
document.getElementById("demo").innerHTML =
"navigator.product is " + navigator.product;
```
Browser Version
```javascript
document.getElementById("demo").innerHTML = navigator.appVersion;
```
Browser Agent
```javascript
document.getElementById("demo").innerHTML = navigator.userAgent;
```
Browser Platform
```javascript
document.getElementById("demo").innerHTML = navigator.platform;
```
Browser Language
```javascript
document.getElementById("demo").innerHTML = navigator.language;
```
Is The Browser Online?
```javascript
document.getElementById("demo").innerHTML = navigator.onLine;
```
[Back to Top⤴️](#table-of-contents)
Is Java Enabled?
```javascript
document.getElementById("demo").innerHTML = navigator.javaEnabled();
```
```javascript
document.getElementById('demo1').innerHTML =
'navigator.cookieEnabled is ' + navigator.cookieEnabled;
document.getElementById('demo2').innerHTML =
'navigator.appName is ' + navigator.appName;
document.getElementById('demo3').innerHTML =
'navigator.appCodeName is ' + navigator.appCodeName;
document.getElementById('demo4').innerHTML =
'navigator.product is ' + navigator.product;
document.getElementById('demo5').innerHTML =
'navigator.appVersion is ' + navigator.appVersion;
document.getElementById('demo6').innerHTML =
'navigator.userAgent is ' + navigator.userAgent;
document.getElementById('demo7').innerHTML =
'navigator.platform is ' + navigator.platform;
document.getElementById('demo8').innerHTML =
'navigator.language is ' + navigator.language;
document.getElementById('demo9').innerHTML =
'navigator.onLine is ' + navigator.onLine;
document.getElementById('demo10').innerHTML =
'navigator.javaEnabled is ' + navigator.javaEnabled();
```
```html
Window Navigator
Window Navigator