JavaScript cheatsheet Quick Reference

A complete JavaScript cheat sheet with all the essential concepts, functions, methods, and more. Perfect as a quick reference for beginners to start coding right away!

Getting Started

// Logs a message
console.log("Message");        

// Logs an error message
console.error("Error");        

// Logs a warning message
console.warn("Warning");       

// Logs an informational message
console.info("Info");          

// Logs a debug message
console.debug("Debug");        

// Displays tabular data as a table
console.table(data);           

// Logs if assertion is false
console.assert(condition, "Message"); 

// Starts a timer
console.time("Label");         

// Stops the timer and logs elapsed time
console.timeEnd("Label");      

// Starts a new group for logging
console.group("Label");        

// Ends the current group
console.groupEnd();            

// Clears the console
console.clear();  
// Basic Number

// Integer
let num1 = 10;                 

// Float
let num2 = 3.14;               

// Special Number Values

// Represents positive infinity
let infinity = Infinity;       

// Represents negative infinity
let negativeInfinity = -Infinity; 

// Represents a non-numeric value
let notANumber = NaN;          

// Number Methods

// Rounds to nearest integer
let rounded = Math.round(num2); 

// Rounds down
let floored = Math.floor(num2); 

// Rounds up
let ceiled = Math.ceil(num2);   

// Absolute value
let absolute = Math.abs(-num1); 

// Random Number

// Generates a random number between 0 and 1
let randomNum = Math.random();  

// Random integer between 0 and 99
let randomInRange = Math.floor(Math.random() * 100); 

// Number Conversion

let stringNum = "42";
// Converts string to number
let convertedNum = Number(stringNum); 

// Parses string to integer
let parsedNum = parseInt(stringNum);   

// Parses string to float
let parsedFloat = parseFloat("3.14");
// Variable Declarations

// Using var (function-scoped or globally-scoped)
var name = "Rapidcheat.Com";
console.log(name);
// Output: Rapidcheat.Com

// Using let (block-scoped)
let age = 25;
console.log(age);
// Output: 25

// Using const (block-scoped, cannot be reassigned)
const pi = 3.14;
console.log(pi);
// Output: 3.14

// Reassigning Variables

// Reassignment is allowed with let
age = 26;
console.log(age);
// Output: 26

// pi = 3.14159; // Error: Assignment to constant variable

// Variable Types

// Boolean
let isActive = true; 

// Null
let score = null;    

// Undefined
let user;            

// Dynamic Typing

// Initially a number
let dynamicVar = 10;  

// Now a string
dynamicVar = "Hello"; 
    
// Now an array
dynamicVar = [1, 2, 3];   

// Template Literals with Variables

let greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);
// Output: Hello, Rapidcheat.Com! You are 26 years old.
// String Declarations

let singleQuoteString = 'Hello, World!';
let doubleQuoteString = "Hello, World!";
let templateLiteralString = `Hello, World!`;

// String Concatenation

let firstName = "John";
let lastName = "Doe";
// Using + operator
let fullName = firstName + " " + lastName;
console.log(fullName);
// Output: John Doe

// String Length

let message = "Hello!";
console.log(message.length);
// Output: 6

// Accessing Characters

console.log(message[0]);
// Output: H
console.log(message.charAt(1));
// Output: e

// String Methods

// Converts to uppercase
let upperCase = message.toUpperCase(); 

// Converts to lowercase
let lowerCase = message.toLowerCase(); 

// Removes whitespace
let trimmed = "   Hello!   ".trim();  

// Checks if string contains "Hello"
let includesHello = message.includes("Hello"); 

// String Substring

// Extracts substring
let substring = message.substring(1, 4);
console.log(substring);
// Output: ell

// Template Literals for Multi-line Strings

let multiLineString = `This is a string
that spans multiple
lines.`;
console.log(multiLineString);

// String Replacement

// Replaces "Hello" with "Hi"
let replacedString = message.replace("Hello", "Hi");
console.log(replacedString);
// Output: Hi!

Arithmetic Operators

Click here to read more
// Addition
let sum = num1 + num2;        

// Subtraction
let difference = num1 - num2;  

// Multiplication
let product = num1 * num2;    

// Division
let quotient = num1 / num2;   

// Modulus
let remainder = num1 % 3;

Comments

// Single-line Comment

// This is a comment that explains the code below
// Assigning 10 to variable x
let x = 10;

/*
Multi-line Comment
This is a comment that can span multiple lines.
It is often used to provide detailed explanations.
*/

/* This assigns 20 to variable y */
let y = 20;

// Commenting out code

// This line is commented out and won't execute
// let z = x + y;

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

console.log(y); 
// Output: 20

Assignment Operators

// Simple assignment
let number = 20;

// Add and assign
// Both statements will add 10
number = number + 10;
number += 10;
console.log(number);
// Output => 30

// Subtract and assign
// Both statements will sub 10
number = number - 10;
number -= 10;
console.log(number);
// Output => 10

// Multiply and assign
// Both statements will divsion 10
number = number * 10;
number *= 10;
console.log(number);
// Output => 200

// Divide and assign
// Both statements will divsion 10
number = number / 10;
number /= 10;
console.log(number);
// Output => 2

String Interpolation

const name = "Rapidcheat.Com";
const age = 30;

// Using template literals for interpolation
const message = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(message);
// Output: Hello, my name is Rapidcheat.Com and I am 30 years old.

let Keyword

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

//Re-declaration Example

let y = 5;
// let y = 10; 
// SyntaxError: Identifier 'y' has already been declared

y = 10; 
// This is valid
console.log(y); 
// Output: 10

const Keyword

// Syntax
if (condition) {
    // code to be executed if condition is true
}

const PI = 3.14;
console.log(PI);
// Output: 3.14

// Reassignment example
const x = 10;
// x = 20;
// TypeError: Assignment to constant variable.

JavaScript Conditionals

if Statement

let isLogin = true;

if (isLogin) {
    console.log("You are Login.");
    // Output: You are Login.
}

Ternary Operator

// Syntax
condition ? expressionIfTrue : expressionIfFalse;

let isLoggedIn = false;

// Ternary operator for login status
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(message);
// Output: Please log in.

else if

let temperature = 25;

if (temperature > 30) {
    console.log("It's hot outside.");
} else if (temperature >= 20 && temperature <= 30) {
    console.log("The weather is pleasant."); 
    // Output: The weather is pleasant.
} else {
    console.log("It's cold outside.");
}

switch Statement

let num = 10;

switch (true) {
    case (num < 5):
        console.log("Number is less than 5.");
        break;
    case (num >= 5 && num <= 10):
        console.log("Number is between 5 and 10."); 
        // Output: Number is between 5 and 10.
        break;
    default:
        console.log("Number is greater than 10.");
}

Operators

// Logical Operators

let a = true;
let b = false;

console.log(a && b);
// Output: false

console.log(a || b);
// Output: true

console.log(!a);
// Output: false

//Comparison Operators

let x = 10;
let y = 20;

console.log(x < y);
// Output: true

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

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

== vs ===

console.log(5 == '5');
// Output: true (string '5' is coerced to number 5)
console.log(null == undefined);
// Output: true (both are considered "falsy" and equal)
console.log(0 == false);
// Output: true (0 is coerced to false)

//== converts values to the same type before comparing.

console.log(5 === '5');
// Output: false (different types: number vs string)
console.log(null === undefined);
// Output: false (different types)
console.log(0 === false);
// Output: false (different types: number vs boolean)

//=== does not convert types; it checks both value and type.

JavaScript Functions

Functions

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Rapidcheat.Com"));
// Output: Hello, Rapidcheat.Com!

Anonymous Functions

// Named function
function namedFunc() {
    return "Hello from the named function!";
  }
  console.log(namedFunc()); 
  // Output: Hello from the named function!
  
  // Anonymous function 
  const sayGoodbye = function() {
    return "Goodbye from the anonymous function!";
  };
 console.log(sayGoodbye()); 
  // Output: Goodbye from the anonymous function!

return Keyword

// Function that returns a greeting

function returnFunc(name) {
    return `Hello, ${name}!`;
  }
  console.log(returnFunc("Rapidcheat.Com"));
  // Output: Hello, Rapidcheat.Com!
  
  // Function without a return statement
  
  function noReturnFunc(name) {
    // No return statement here
    `Hello, ${name}!`;
  }
  console.log(noReturnFunc("Rapidcheat.Com"));
  // Output: undefined

Calling Functions

// Defining the function
function add(a, b) {
  return a * b;
}

// Calling the function
console.log(add(5, 3));
// Output: 15

Function Expressions

// Named function expression

const square = function squareNumber(num) {
    return num * num;
  };

// Anonymous function expression

const greet = function(name) {
    return `Hello, ${name}!`;
  };

Function Parameters

// Function with a and b parameters
function add(a, b) {
    return a + b;
  }
  
  // Calling the function with two arguments
  console.log(add(5, 3)); 
  // Output: 8

Function Declaration

// Function declaration
function functionName(name) {
    return `Hello, ${name}!`;
  }
  

Arrow Functions (ES6)

// Arrow functions

const sum = (a, b) => a + b;
console.log(sum(3, 7));
// Output: 10
// Single-argument arrow function to double a number

const double = number => number * 2;
// Calling the function
console.log(double(4)); 
// Output: 8

// Arrow functions With two arguments

// Arrow function to concatenate two strings
const concatenate = (firstName, lastName) => `${firstName} ${lastName}`;
// Calling the function
console.log(concatenate("Welcome", "Rapidcheat.Com")); 
// Output: Welcome Rapidcheat.Com

// Arrow functions With no arguments

const user = () => "Hello, welcome to Rapidcheat.Com!";
// Calling the function
console.log(ureet()); 
// Output: Hello, welcome to Rapidcheat.Com!

JavaScript Scope

Scope

function myFunction() {
    let localVar = "I am local!";
    console.log(localVar); // Accessible here
  }
  
  myFunction(); // Output: I am local!
  // console.log(localVar); // Error: localVar is not defined

Block Scoped Variables

if (true) {
    let blockScopedVar = "I am block scoped!";
    console.log(blockScopedVar); // Accessible here
  }
  
  // console.log(blockScopedVar); // Error: blockScopedVar is not defined

Global Variables

let globalVar = "I am a global variable!";

function showGlobal() {
  console.log(globalVar); 
  // Accessible here
}

showGlobal(); 
// Output: I am a global variable!

let vs var

function testVar() {
    var x = 10;
    if (true) {
      var x = 20;
      // Same variable
      //  accessible 
      console.log(x);
      // Output: 20
    }
    console.log(x);
    //accessible 
    // Output: 20
  }  
  testVar();


  
  function testLet() {
    let y = 10;
    if (true) {
      let y = 20;
      // Different variable
      console.log(y);
      // accessible
      // Output: 20
    }
    console.log(y);
    //not accessible
    // Output: 10
  }
  testLet();
  
//  var are function-scoped or globally scoped
// let are block-scoped

Loops with closures

const createVar = () => {
  const functions = [];
  for (var i = 0; i < 3; i++) {
    // Each function captures the same variable 'i'
    functions[i] = function () {
      console.log(i);
    };
  }
  return functions;
};

const funcsVar = createVar();
funcsVar[0](); // Output: 3
funcsVar[1](); // Output: 3
funcsVar[2](); // Output: 3

const createLet = () => {
  const functions = [];

  for (let i = 0; i < 3; i++) {
    // Each iteration creates a new block scope
    functions[i] = function () {
      console.log(i);
    };
  }
  return functions;
};

const funcsLet = createLet();
funcsLet[0](); // Output: 0
funcsLet[1](); // Output: 1
funcsLet[2](); // Output: 2

JavaScript Arrays

Arrays

const colors = ["Red", "Green", "Blue"];
console.log(colors);
// Output => ['Red', 'Green', 'Blue']

Property .length

const arr = [1, 'hello', true, null];
console.log(arr.length);
// Output: 4
//The .length property is a quick way to find out how many items are in an array.

index

const fruits = ['apple', 'orange', 'banana', 'grape'];

// Accessing elements
console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: orange
console.log(fruits[2]); // Output: banana
console.log(fruits[3]); // Output: grape

Mutable chart

addremovestartend
push✔✔
pop✔✔
unshift✔✔
shift✔✔

Method .push()

const fruits = ['apple', 'orange'];

// Adding a single element
fruits.push('banana');
console.log(fruits);
// Output: ['apple', 'orange', 'banana']

// Adding multiple elements
fruits.push('grape', 'mango');
console.log(fruits);
// Output: ['apple', 'orange', 'banana', 'grape', 'mango']

// add one or more elements to the end of an array

Method .pop()

const fruits = ['apple', 'orange', 'banana', 'grape'];

// Removing the last element
const removedFruit = fruits.pop();

console.log(removedFruit); // Output: grape
console.log(fruits); // Output: ['apple', 'orange', 'banana']

// remove the last element from an array

Method .shift()

const numbers = [1, 2, 3, 4, 5];

const firstNumber = numbers.shift();
console.log(firstNumber); // Output: 1
console.log(numbers); // Output: [2, 3, 4, 5]

// remove the first element from an array

Method .unshift()

// Array of cities
const cities = ['New York', 'Los Angeles', 'Chicago'];

cities.unshift('San Francisco');
console.log(cities); 
// Output: ['San Francisco', 'New York', 'Los Angeles', 'Chicago']

// add one or more elements to the beginning of an array

Method .concat()

const grains = ['rice', 'wheat'];
const dairy = ['milk', 'cheese'];

// Merging multiple arrays
const allFood = fruits.concat(grains, dairy);

console.log(allFood); 
// Output: ['rice', 'wheat', 'milk', 'cheese']

// merge two or more arrays

JavaScript Loops

While Loop

while (condition) {
  // Code to be executed
}

let count = 1;

while (count <= 5) {
    console.log(count);
    count++;
}

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

//repeatedly executes a block of code as long as a specified condition is true

Reverse Loop

const cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Miami'];

// Looping in reverse
for (let i = cities.length - 1; i >= 0; i--) {
    console.log(cities[i]);
}

// Output:
// Miami
// Houston
// Chicago
// Los Angeles
// New York

Do…While Statement

do {
  // Code to be executed
} while (condition);

let count = 1;

do {
    console.log(count);
    count++;
} while (count <= 5);

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

// executes a block of code at least once before checking a specified condition

For Loop

for (initialization; condition; increment) {
  // Code to be executed
}

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

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

Looping Through Arrays

const fruits = ['apple', 'orange', 'banana'];

// Looping through the array
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// Output:
// apple
// orange
// banana

Break

let count = 1;

while (count <= 5) {
    if (count === 4) {
        break; // Exit the loop when count is 4
    }
    console.log(count);
    count++;
}

// Output:
// 1
// 2
// 3

//terminate a loop or switch statement prematurely

Continue

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
      continue; // Skip the rest of the loop when i is 3
  }
  console.log(i);
}

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

Nested

for (let i = 1; i <= 5; i++) {
  for (let j = 1; j <= 5; j++) {
      console.log(`${i} * ${j} = ${i * j}`);
  }
}

// Output:
// 1 * 1 = 1
// 1 * 2 = 2
// ...
// 5 * 5 = 25

for...in loop

for (const key in object) {
  // Code to be executed for each key
}

const mountains = ['Everest', 'K2', 'Kangchenjunga', 'Lhotse', 'Denali'];

for (const index in mountains) {
    console.log(`${index}: ${mountains[index]}`);
}

// Output:
// 0: Everest
// 1: K2
// 2: Kangchenjunga
// 3: Lhotse
// 4: Denali

for...of loop

for (const element of iterable) {
  // Code to be executed for each element
}

const word = 'Mountain';

for (const char of word) {
    console.log(char);
}

// Output:
// M
// o
// u
// n
// t
// a
// i
// n

//iterate over iterable objects such as arrays, strings, and other collection types

JavaScript Iterators

Functions Assigned to Variables

let subtractFromTen = (number) => {
  return 10 - number;  
};

// g is assigned the value of subtractFromTen
let g = subtractFromTen;

subtractFromTen(4); // 6
// Since g has a function value, it can be invoked. 
g(7); // 3

Callback Functions

function greet(name) {
  console.log(`Hello, ${name}!`);
}

function processUserInput(callback) {
  // Simulate getting user input
  const name = "Rapidcheat.Com";
  // Invoke the callback with the name
  callback(name);
}

// Pass the greet function as a callback
processUserInput(greet);

// Output: Hello, Rapidcheat.Com!

//passed as arguments to other functions and are executed at a later time

Array Method .reduce()

// Syntax
array.reduce((accumulator, currentValue, index, array) => {
  // Logic to update the accumulator
}, initialValue);

const numbers = [1, 2, 3, 4, 5];

// Using reduce to sum the numbers
const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0); // Initial value is 0

console.log(sum); // Output: 15

Array Method .map()

// Syntax
const newArray = array.map((currentValue, index, array) => {
  // Return the new value for the new array
});
const fruits = ['apple', 'banana', 'cherry'];

// Using map to convert fruits to uppercase
const uppercaseFruits = fruits.map((fruit) => fruit.toUpperCase());

console.log(uppercaseFruits);
// Output: ['APPLE', 'BANANA', 'CHERRY']

// applying a provided function to each element of an existing array

Array Method .forEach()

// Syntax
array.forEach((currentValue, index, array) => {
  // Logic to execute for each element
});

const animals = ['cat', 'dog', 'rabbit'];

// Using forEach to log the animal and its index
animals.forEach((animal, index) => {
    console.log(`${index}: ${animal}`);
});

// Output:
// 0: cat
// 1: dog
// 2: rabbit

//executes a provided function once for each array element.

Array Method .filter()

//Syntax
const newArray = array.filter((currentValue, index, array) => {
  // Return true to keep the element, false to discard it
});

const numbers = [1, 2, 3, 4, 5, 6];

// Using filter to get even numbers
const evenNumbers = numbers.filter((number) => {
    return number % 2 === 0;
});

console.log(evenNumbers); 
// Output: [2, 4, 6]

// creates a new array containing all elements that pass a test defined by a provided function

JavaScript Objects

Accessing Properties

const person = {
  name: 'Rapidcheat',
  age: 30,
  occupation: 'Engineer'
};

console.log(person);
// Output: { name: 'Rapidcheat', age: 30, occupation: 'Engineer' }

// Dot Notation
console.log(person.name); // Output: Rapidcheat
console.log(person.age);  // Output: 30

// Bracket Notation
console.log(person['occupation']); // Output: Engineer

Naming Properties

const carSpecifications = {
  // Invalid due to the space in the key
  model name: 'Toyota Camry',
  
  // Invalid because keys can't start with a number
  2022Model: 'Model S',
  
  // Invalid character (exclamation mark) in key
  price!: 30000,
  
  // Invalid because keys can't have hyphens without quotes
  max-speed: '200 km/h',
  
  // Valid: key is in quotes so it can include spaces and special characters
  'engine type': 'V6'
};

console.log(carSpecifications);

// Rules for Naming Properties
// Valid Characters
// Case Sensitivity
// No Reserved Words

Non-existent properties

const person = {
  name: 'Rapidcheat',
  age: 30
};

console.log(person.job); // Output: undefined

Mutable

const car = {
  make: "Toyota",
  model: "Camry",
  year: 2020,
};

console.log(car);
// Modifying an existing property
car.year = 2021;

// Adding a new property
car.color = "blue";
console.log(car);
// Output: { make: 'Toyota', model: 'Camry', year: 2021, color: 'blue' }

car = {};
// Uncaught TypeError: Assignment to constant variable.

Assignment shorthand syntax

const student = {
  name: "Rapidcheat",
  subjects: {
    math: "A",
    science: "B",
  },
};

// destructuring
const {
  name,
  subjects: { math },
} = student;

console.log(name); // Output: Rapidcheat
console.log(math); // Output: A

Delete operator

const cities = {
  newYork: "NYC",
  losAngeles: "LA",
  chicago: "CHI",
};

// Deleting the 'losAngeles' property
delete cities.losAngeles; //delete cities["losAngeles"];

console.log(cities);
// Output: { newYork: 'NYC', chicago: 'CHI' }

// Accessing the deleted property
console.log(cities.losAngeles); // Output: undefined

Objects as arguments

const product = {
  id: 1,
  name: 'Laptop',
  price: 999
};

// Function with destructuring
function displayProduct({ id, name, price }) {
  console.log(`Product ID: ${id}`);
  console.log(`Product Name: ${name}`);
  console.log(`Product Price: $${price}`);
}

// Calling the function with the product object
displayProduct(product);

Shorthand object creation

const name = "Rapidcheat";
const age = 25;
const city = "New York";

// Shorthand object creation
const user = { name, age, city };

console.log(user);
// Output: { name: 'Alice', age: 25, city: 'New York' }

this Keyword

const person = {
  name: 'Rapidcheat',
  greet: function() {
      console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // Output: Hello, my name is Rapidcheat

// this keyword refers to the context in which a function is executed.

Factory functions

function createCar(make, model, year) {
  return {
      make,
      model,
      year,
      drive() {
          console.log(`Driving a ${this.make} ${this.model}`);
      }
  };
}

// Creating instances of cars
const car1 = createCar('Toyota', 'Camry', 2020);
const car2 = createCar('Honda', 'Civic', 2021);

car1.drive(); // Output: Driving a Toyota Camry
car2.drive(); // Output: Driving a Honda Civic

//Factory functions are useful for creating multiple objects with similar properties

Methods

const bicycle = {
  // Method shorthand, with one argument
  ride(adverb) {
    console.log(`The bicycle rides ${adverb} down the street...`);
  },
  // Anonymous arrow function expression with no arguments
  ringBell: () => {
    console.log('The bicycle bell rings ding ding...');
  },
};

// Calling the methods
bicycle.ride('smoothly');
//The bicycle rides smoothly down the street...
bicycle.ringBell();
//The bicycle bell rings ding ding...

Getters and setters

const person = {
  _name: "",

  // Getter for fullName
  get name() {
    return this._name;
  },

  // Setter for fullName
  set name(newName) {
    this._name = newName; // Corrected to assign to _name
  },
};

// Setting the fullName using the setter
person.name = "Rapidcheat.Com"; // Using the setter
console.log(person.name); // Output: Rapidcheat.Com

JavaScript Classes

Static Methods

class Person {
  constructor(name) {
      this.name = name;
  }

  // Static method to create a Person instance with a default name
  static createDefault() {
      return new Person('Default Name');
  }
}

// Creating an instance using the static factory method
const defaultPerson = Person.createDefault();
console.log(defaultPerson.name); // Output: Default Name

Class

class Animal {
  constructor(name, type) {
      this.name = name; // Instance property
      this.type = type; // Instance property
  }

  // Method to describe the animal
  describe() {
      return `${this.name} is a ${this.type}.`;
  }
}

// Creating an instance of the class
const lion = new Animal('Leo', 'lion');
console.log(lion.describe()); // Output: Leo is a lion.

Class Constructor

class Car {
  // Constructor method
  constructor(make, model, year) {
      this.make = make; 
      this.model = model; 
      this.year = year;
  }

  // Method to display car details
  getDetails() {
      return `${this.year} ${this.make} ${this.model}`;
  }
}

// Creating an instance of the Car class
const myCar = new Car('Toyota', 'Corolla', 2020);
console.log(myCar.getDetails()); 
// Output: 2020 Toyota Corolla

Class Methods

class Dog {
  constructor(name, breed) {
      this.name = name; // Instance property
      this.breed = breed; // Instance property
  }

  // Instance method to describe the dog
  describe() {
      return `${this.name} is a ${this.breed}.`;
  }

  // Instance method to make the dog bark
  bark() {
      return `${this.name} barks!`;
  }
}

// Creating an instance of the Dog class
const myDog = new Dog('Buddy', 'Golden Retriever');

console.log(myDog.describe());
// Output: Buddy is a Golden Retriever.
console.log(myDog.bark());
// Output: Buddy barks!

extends

// Parent class
class Vehicle {
  constructor(make, model) {
      this.make = make;  // Brand of the vehicle
      this.model = model; // Model of the vehicle
  }

  // Method to display vehicle information
  getInfo() {
      return `${this.make} ${this.model}`;
  }
}

// Child class that extends Vehicle
class Car extends Vehicle {
  constructor(make, model, doors) {
      super(make, model); // Call the parent class constructor
      this.doors = doors; // Additional property specific to Car
  }

  // Method specific to Car
  getCarDetails() {
      return `${this.getInfo()} with ${this.doors} doors.`;
  }
}

// Creating an instance of the Car class
const myCar = new Car('Toyota', 'Camry', 4);

console.log(myCar.getInfo());        // Output: Toyota Camry
console.log(myCar.getCarDetails());  // Output: Toyota Camry with 4 doors.

JavaScript Modules

Export

// calculator.js

// Function to multiply two numbers
const multiply = (a, b) => a * b;

// Default export
export default multiply;

// Named exports
export const PI = 3.14;

export function area(radius) {
  return PI * radius * radius;
}

// Multiple exports
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}
export { add, subtract };

Import

// app.js

import multiply, { add, area, PI, subtract } from "./calculator";

console.log(`PI: ${PI}`); // Output: PI: 3.14
console.log(add(5, 3)); // Output: 8
console.log(subtract(9, 4)); // Output: 5
console.log(`Area: ${area(5)}`); // Output: Area: 78.5
console.log(`Multiply: ${multiply(4, 5)}`); // Output: Multiply: 20

Export Module

// calculator.js

function divide(x, y) {
  if (y === 0) {
      throw new Error("Cannot divide by zero");
  }
  return x / y;
}

function square(x) {
  return x * x;
}

function remainder(x, y) {
  return x % y;
}

function triple(x) {
  return x * 3;
}

// Multiple exports in Node.js
module.exports = {
  divide,
  square,
  remainder,
  triple
};

Require Module

// app.js

const calculator = require("./calculator.js");

console.log(`Divide: ${calculator.divide(10, 2)}`);
// Output: Divide: 5
console.log(`Square: ${calculator.square(4)}`);
// Output: Square: 16
console.log(`Remainder: ${calculator.remainder(10, 3)}`);
// Output: Remainder: 1
console.log(`Triple: ${calculator.triple(5)}`);
// Output: Triple: 15

try {
  console.log(calculator.divide(10, 0));
  // Throws an error
} catch (error) {
  console.error(error.message);
  // Output: Cannot divide by zero
}

JavaScript Promises

Promise states

const myPromise = new Promise((resolve, reject) => {
  const success = true;

  if (success) {
    resolve("Operation succeeded!");
  } else {
    reject("Operation failed!");
  }
});
myPromise
  .then((result) => {
    console.log(result); 
    // Output: Operation succeeded!
  })
  .catch((error) => {
    console.error(error); 
    // Output: Operation failed!
  });

Executor function

// Executor function
const fetchData = (resolve, reject) => {
  // Simulating an asynchronous operation with setTimeout
  setTimeout(() => {
    const success = true; // Change this to false to simulate an error
    if (success) {
      resolve("Data fetched successfully!"); // Operation succeeded
    } else {
      reject("Error fetching data!"); // Operation failed
    }
  }, 2000); // Delay of 2 seconds
};

// Creating the Promise
const promise = new Promise(fetchData);

// Handling the Promise
promise
  .then((result) => {
    console.log(result);
    // Output: Data fetched successfully!
  })
  .catch((error) => {
    console.error(error);
    // Output: Error fetching data!
  });

setTimeout()

const popup = () => {
  console.log("Hello Sir! Welcome");
};

setTimeout(() => {
  popup();
}, 2000);

.then() method

const calculationPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true; 
    // Change to false to simulate an error
    if (success) {
      const result = 5 + 3; 
      // Example calculation
      resolve(result); 
      // Resolve with the result
    } else {
      reject("Calculation failed!"); 
      // Reject with an error message
    }
  }, 300); // Simulate a delay of 300 milliseconds
});

// Using the Promise
calculationPromise.then(
  (res) => {
    console.log(`Calculation Result: ${res}`); 
    // Output: Calculation Result: 8
  },
  (err) => {
    console.error(err); 
    // Handle the error if it occurs
  }
);

.catch() method

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject(Error("Promise Rejected."));
  }, 1000);
});

// Using .then() to handle the resolved value (not applicable here since it's rejected)
promise.then((res) => {
  console.log(res);
  // This won't run because the promise is rejected
});

// Using .catch() to handle the error
promise.catch((err) => {
  console.error(err);
  // Output: Error: Promise Rejected.
});

Promise.all()

const fetchUserData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("User Data");
    }, 1000); // Simulate a 1 second delay
  });
};

const fetchPostData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("Post Data");
    }, 1500); // Simulate a 1.5 second delay
  });
};

// Using Promise.all to fetch both user and post data
Promise.all([fetchUserData(), fetchPostData()])
  .then((results) => {
    const [userData, postData] = results; // Destructuring the results
    console.log(userData); // Output: User Data
    console.log(postData); // Output: Post Data
  })
  .catch((error) => {
    console.error("An error occurred:", error);
  });

Avoiding nested Promise and .then()

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello");
  }, 1000); // 1 second delay
});

// Function to repeat the string
const repeatString = (str) => {
  return str + str; 
  // Repeat the string
};

// Function to add an exclamation mark
const addExclamation = (str) => {
  return str + "!"; 
  // Add an exclamation mark
};

// Function to print the final result
const displayResult = (val) => {
  console.log(val); 
  // Print the final result
};

// Chaining them all together
promise
  .then(repeatString) // HelloHello
  .then(addExclamation) // HelloHello!
  .then(displayResult); // Output: HelloHello!

Creating

const immediatePromise = (res, rej) => {
  console.log("Operation completed successfully!");
};

const promise = new Promise(immediatePromise);

Chaining multiple .then()

const userPromise = new Promise(resolve => setTimeout(() => resolve('admin'), 100));
userPromise
  .then(role => {
    return role === 'admin' 
      ? Promise.resolve('Welcome, Admin!') 
      : Promise.reject('Access denied!');
  })
  .then(greeting => {
    console.log(greeting); 
    // Output if role is 'admin'
  }, error => {
    console.error(error); 
    // Output if role is not 'admin'
  });

Fake http Request with Promise

const mockRequest = (shouldSucceed) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldSucceed) {
        resolve({
          status: 200,
          data: { message: "Data retrieved successfully!" },
        });
      } else {
        reject({ status: 404, message: "Failed to retrieve data." });
      }
    }, 2000);
  });
};

const fetchData = async () => {
  try {
    const response = await mockRequest(true, 1000); // Change to false to test failure
    console.log(response.data.message);
    // Output on success
  } catch (error) {
    console.error(error.message);
    // Output on failure
  }
};

// Calling the fetchData function
fetchData();

JavaScript Async-Await

Asynchronous

function helloWorld() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello World!');
    }, 2000);
  });
}

// Async Function Expression
const displayMessage = async function() {
  const message = await helloWorld();
  console.log('Message:', message);
}

// Async Arrow Function
const displayMessageArrow = async () => {
  const message = await helloWorld();
  console.log('Message:', message);
}

// Calling the functions
displayMessage();     // Message: Hello World! <-- after 2 seconds
displayMessageArrow(); // Message: Hello World! <-- after 2 seconds

Resolving Promises

const promise1 = Promise.resolve(10); // Changed resolved value from 5 to 10
const promise2 = 100; // Changed value from 44 to 100
const promise3 = new Promise((resolve) => {
  setTimeout(resolve, 200, 'bar'); // Changed the resolved value from 'foo' to 'bar' and delay from 100ms to 200ms
});

Promise.all([promise1, promise2, promise3]).then((results) => {
  console.log(results);
});
// expected => Array [10, 100, "bar"]

Async Await Promises

function helloWorld() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello, World!'); // Added a comma for stylistic change
    }, 2000);
  });
}

const displayMessage = async () => {
  const message = await helloWorld();
  console.log('Message:', message);
};

displayMessage(); // Message: Hello, World! <-- after 2 seconds

Error Handling

let jsonData = '{ "age": 20 }'; // missing name property

try {
  let userInfo = JSON.parse(jsonData); // <-- parsing successful
  console.log(userInfo.name); // name property is undefined
} catch (error) {
  console.error("Failed to parse JSON data!");
}

Aysnc await operator

function greet() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Greetings, Universe!'); // Changed the message
    }, 2000);
  });
}

async function displayMessage() {
  const message = await greet();
  console.log('Output:', message); // Changed the output label
}

displayMessage(); // Output: Greetings, Universe! <-- after 2 seconds

#JavaScript Requests

JSON

const userObject = {
  "fullName": "Rick Sanchez", // Changed the name and added last name
  "userId": "11A",            // Changed the key name
  "accessLevel": 4            // Changed the key name
};

XMLHttpRequest

// Create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();

// Open a new request
xhr.open('GET', 'https://api.example.com/data', true); // Method: GET, URL: your API endpoint

GET

const request = new XMLHttpRequest(); // Create a new XMLHttpRequest object
request.responseType = 'json'; // Set the expected response type to JSON
request.open('GET', '/getdata?id=65'); // Initialize a GET request with the specified URL

request.onload = () => {
  // Check if the request was successful
  if (request.status >= 200 && request.status < 300) {
    console.log(request.response); // Log the JSON response
  } else {
    console.error('Request failed with status:', request.status); // Log error if request failed
  }
};

request.onerror = () => {
  console.error('Network error'); // Handle network errors
};

request.send(); // Send the request

POST

const productDetails = { // Changed variable name for clarity
  type: 'Tuna',          // Updated fish type
  weight: '2.0 KG',      // Changed weight
  quantity: 10           // Updated quantity in inventory
};

const request = new XMLHttpRequest(); // Create a new XMLHttpRequest object
request.open('POST', '/inventory/add'); // Set up a POST request to the specified endpoint
request.responseType = 'json'; // Specify that we expect a JSON response

request.onload = () => {
  // Check if the request was successful
  if (request.status >= 200 && request.status < 300) {
    console.log('Response received:', request.response); // Log the response if successful
  } else {
    console.error('Failed to add item:', request.statusText); // Log an error message if failed
  }
};

request.onerror = () => {
  console.error('Error occurred during the network request'); // Handle network errors
};

request.send(JSON.stringify(productDetails)); // Send the request with the product details as JSON

Fetch API

fetch(endpointUrl, { // Changed variable name for clarity
    method: 'POST', // Specify the request method as POST
    headers: {
      'Content-Type': 'application/json', // Set content type to JSON
      'Authorization': `Bearer ${apiKey}` // Updated header to use Authorization with Bearer token
    },
    body: JSON.stringify(payloadData) // Ensure the body is a JSON string
  })
  .then(response => {
    if (response.ok) {
      return response.json(); // Parse the JSON response if the request was successful
    }
    throw new Error('Request was unsuccessful!'); // Throw an error for failed requests
  })
  .catch(error => {
    console.error('Network error:', error.message); // Log network errors
  });

JSON Formatted

fetch('https://api.example.com/data') // Updated URL for clarity
  .then(res => { // Renamed variable for brevity
    if (!res.ok) { // Check if the response status is not OK
      throw new Error('Failed to fetch data!'); // Throw an error for bad responses
    }
    return res.json(); // Parse the response as JSON
  })
  .then(data => { // Renamed variable for clarity
    console.log('Received data:', data); // Log the JSON response
  })
  .catch(error => {
    console.error('Error:', error.message); // Log any errors that occur
  });

promise url parameter fetch api

fetch('https://api.example.com/resource') // Updated URL for clarity
  .then(
    response => {
      console.log('Response received:', response); // Log the response
    },
    error => {
      console.error('Fetch error:', error.message); // Log the error message
    }
  )
  .catch(err => {
    console.error('An unexpected error occurred:', err.message); // Handle any unexpected errors
  });

Fetch API Function

fetch('https://api.example.com/submit', { // Updated URL for clarity
  method: 'POST', // Set the request method to POST
  headers: { // Added headers for content type
    'Content-Type': 'application/json' // Specify content type as JSON
  },
  body: JSON.stringify({ id: "200" }) // Send data as a JSON string
})
.then(response => {
  if (response.ok) { // Check if the response status is OK
    return response.json(); // Parse the response as JSON
  }
  throw new Error('Failed to process the request!'); // Throw an error for bad responses
})
.catch(error => {
  console.error('Network error:', error.message); // Handle network errors
})
.then(jsonData => {
  console.log('Response data:', jsonData); // Log the parsed JSON response
});

async await syntax

const fetchSuggestions = async () => {
  const searchTerm = inputField.value; // Get the value from the input field
  const apiUrl = `${url}${queryParams}${searchTerm}`; // Construct the endpoint URL

  try {
    const response = await fetch(apiUrl, { cache: 'no-store' }); // Fetch data with no caching
    if (response.ok) { // Check if the response status is OK
      const data = await response.json(); // Parse the response as JSON
      console.log('Suggestions received:', data); // Log the parsed suggestions
    } else {
      console.error('Error fetching suggestions:', response.statusText); // Log error status if response is not OK
    }
  } catch (error) {
    console.error('Fetch error:', error); // Handle any errors that occur during the fetch
  }
};