50%

Javascript Cheat Sheet

A Javascript Cheat Sheet is a reference tool that provides quick and easy access to standard coding syntax and language functions. It can be used by beginning coders and experienced developers to quickly review the basics, find solutions for common problems, or look up unfamiliar language features.

# Introduction :

Comments
// This line will denote
   a Single line comment

/* This line will denote 
   a Multi line comment */      

Comments can also be used to temporarily disable part of a program so it can be tested and document the code.

Var Keyword
var b;
console.log(b); // => undifined

b = 9;
console.log(b); // => 9         

var is a keyword in JavaScript that is used to declare variables. Variables declared using var are globally scoped or function-scoped. They can be reassigned and re-declared within their scope.

Const Keyword
const pieValue = 3.14;
console.log(pieValue); // => 3.14

pieValue = 3.24;
// TypeError: Assignment to constant...

The const keyword is used to create a constant. It is similar to a variable except that the value of a constant cannot be changed once it has been defined.

Console
// => Good Morning!
console.log('Good Morning!');

// => Good Morning!
console.warn('Good %s', 'Morning!');

// Prints error message to stderr
console.error(new Error('OH No!'));

The console in JavaScript is used for logging information as part of the debugging process.

Let Keyword
let a;
console.log(a); // => undefined

a = 6;
console.log(a); // => 6

The let is a keyword in Javascript that declares a variable. It permits the variable to only be available within the current block (or scope) of code.

Variables
let a = 6;
let name  = "Rahul";
const pieValue = 3.14;

// => 6, Rahul, 3.14
console.log(a, name, pieValue);

var b;
console.log(b); // => undefined

Variables are names assigned to parts of a computer program that store values that can be changed during the execution of the program.

Numbers
let productAmount = 50;
let productTotal = 70.00        

A number is a primitive data type that represents numerical values. It can be an integer (whole number) or a floating point number (decimal).

Strings
let homeAddress = "Gandy Street,Saint Louis,Missouri,United States-63141";
console.log(homeAddress); // => 53

let officeAddress = "Trinity Crescent,Whichford,United Kingdom-CV36 5SR
"
console.log(officeAddress); // => 50 

A string in Javascript is a series of characters surrounded by single or double quotes. Strings are used to store and manipulate text.

# Scopes :

Block Scope
let bulb = true;
if (bulb == true) {
  const bulbOn = 'Light On';
}
// Uncaught ReferenceError...
console.log(bulbOn);            

Block Scope means that the variable can only be accessed from inside the block it was declared in, not outside.

Global Scope
// Variable declared globally
const city = 'california';
function myCity() {
  console.log(city);
}
myCity(); // California         

The global scope is available throughout the entire program and can be accessed by any code within the program.

Function Scope
function myFunction() 
{
  var country = "Usa";
  // Code here can use country  
}
// Code here can't use country  

Function scope in JavaScript refers to the environment in which a function is declared and executed.

# Operators :

Arithmetic Operators
3 + 3 = 6     // Addition
6 - 3 = 3     // Subtraction
6 * 10 = 60    // Multiplication
6 / 3 = 2     // Division
10 % 6 = 0     // Modulus 

let x = 5;      // Increment 
x++; 
console.log(x); // 6

let x = 5;      // Decrement 
x--; 
console.log(x); // 4            

Arithmetic operators in JavaScript are symbols that allow you to perform mathematical operations on one or more operands.

Assignment Operators
let num = 100; // Simple operator

// Both statements will add 10
num = num + 10; //Addition Assignment   
num += 10; // 110  += Operator

num -= 10; // 100  Subtraction Assignment

num *= 10; // 1000 Multiplication Assignment

num /= 10; // 10 Division Assignment

Assignment operators in Javascript are used to assign values to variables. They are a type of operator that assigns a value and returns it.

Comparison Operators
//equal to
a == 8  // false  

//equal value and equal type
a === 5 //true

//not equal	
a != 8	//true

//not equal value or not equal type	
x !== 5	//false

//greater than	
x > 8	//false

//less than	
x < 8	//true

//greater than or equal to	
x >= 5	//true

//less than or equal to	
x <= 8	//true                  

Comparison operators in JavaScript are used to compare two values and determine whether the condition is true or false.

Ternary Operators
// ternary operator for check the eligibility for vote
let age = 15;
let result =
    (age >= 18) ? "You are eligible for vote." : "You are not eligible for vote yet";
console.log(result);            

A ternary operator in JavaScript is an alternative to writing an if/else statement. It takes the form of a question followed by a colon and two possible answers, separated by a comma.

Logical Operators
// Logical Operator ||                
10 > 3 || 9 > 20;   // true
6 > 60 || 5 > 30; // false
true || false;       // true
false || false;      // false

// Logical Operator &&
1 > 6 && 6 > 1;      // false
6 === 6 && 9 > 1;    // true   
true && true;        // true
true && false;       // false 

// Logical Operator !
let officeWork = true;
let work = !officeWork;

// => false
console.log(work);              

Logical operators are used in JavaScript to perform logical operations on values. Logical operators are commonly used with conditional statements to determine whether a specific condition is true or false.

Bitwise Operators
5 & 1	//1	 AND
5 | 1	//5	OR
~ 5	//10 NOT
5 << 1	//10  Zero fill left shift	
5 ^ 1	//4	XOR
5 >> 1	//2 Signed right shift	
5 >>> 1	//2	 Zero fill right shift

Bitwise operators perform operations on the binary representations of two given numbers. Bitwise operators are commonly used to create masks and flags or for bit-shifting and bit-counting operations.

# Conditionals :

If-Else Statement
let number = 10;

// check if number is modulo by 2 than Even Number

if (number % 2 == 0) {
  console.log('Number is Even'+number);
}

// check if number is not modulo by 2 than Odd Number

else{
    console.log('Number is Odd'+number);
}                               

An if-else statement in JavaScript is a control flow code that lets you execute a code block depending on whether a specified condition evaluates to true or false.

Else-If Statement
let number = prompt("Enter a number: ");
// check if number is greater than 0
if (number > 0) {
    console.log("The number is positive");
}
// check if number is 0
else if (number == 0) {
  console.log("The number is 0");
}
// if number is neither greater than 0, nor zero
else {
    console.log("The number is negative");
}
console.log("The if...else if...else statement is easy");

An else-if statement in JavaScript is a conditional statement that helps with controlling the flow of execution based on multiple given conditions. It is used when you want to check various conditions.

Switch Statement
var grade = 'A';

console.log("Entering Switch Block:-");
switch (grade) {
    case 'A': console.log("Good job");
    break;

    case 'B': console.log("Pretty good");
    break;

    case 'C': console.log("Passed");
    break;

    case 'D': console.log("Failed");
    break;

    default:  console.log("Better Luck Next Time For Grade");
}
console.log("Exiting switch block;-");

A switch statement is a control flow structure in JavaScript that allows a program to evaluate an expression, match the expression's value to a case clause, and execute the associated statement.

# Loops :

For Loop
for (initialExpression; condition; updateExpression) 
{
   // for loop body
}

// looping from i = 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log(i); //1 2 3 4 5
}                               

A for loop in JavaScript allows the programmer to execute a code block several times or until a specific condition is met.

Continue
for (let i = 1; i <= 6; i++) 
{
    // condition to continue    
    if (i == 2) {
        continue;
    }
    console.log(i);// 1 3 4 5 6
}                               

The continue is a control flow statement in Javascript that allows the program to skip over part of a loop. It can be used in a while, do-while, and for loops.

Break
for (let i = 1; i <= 10; i++) 
{
    // condition to break    
    if (i == 4) {
        break;
    }
    console.log(i);// 1 2 3
}                               

The break in JavaScript is a keyword used to stop the execution of a loop or an entire program.

While Loop
while (condition) 
{
  // while loop body 
}

let i = 1;
while (i < 5) {        
  console.log(i); // 1 2 3 4 5
  i++;
}                               

A while loop in JavaScript is a type of loop used to repeat a block of code until a certain condition is met. The while loop will continue to run when the expression evaluates to false, and the loop will stop.

For...In Loop
for (key in object) 
{
   // for...in loop body
}

const language = 'javascript';

// using for...in loop
for (let i in language) {
    console.log(language[i]);
}                               

A for...in a loop is used to loop through the properties of an object in JavaScript. It iterates through the object's enumerable properties and executes a code block for each one.

Do...While Loop
do 
{
  // do....while loop body
} while(condition)

let i = 1;
// do...while loop from 1 to 5
do {
    console.log(i); //1 2 3 4 5
    i++;
} while(i <= 5);                

A do-while loop in JavaScript is a type of loop that evaluates its condition at the base of the loop instead of at the top. It will consistently execute the code inside its block once, even if the state is false, and then will continue to repeat the loop as long as the condition remains true.

For...Of Loop
for (element of iterable) 
{
   // for...of loop body
}

// array
const fruits = ['Banana', 'Apple', 'Mango'];

// using for...of
for ( let element of fruits ) {

    // display the values
    console.log(element);
}                               

The for...of the loop is a new type introduced in ES6 that allows you to iterate over any iterable object, such as an array, a Map, a Set, and even a string. It runs until it has iterated through all the elements of the given object.

# Arrays :

Arrays and Index
// Array
let language = ["Javascript", "Java", "Python"];
// Different data types
let newDataArray = ['Rajesh','Javascript',9];

// Index
console.log(language[0]); // Javascript
console.log(newDataArray[2]); // 9

An Array in Javascript is an object used to store multiple data in a single variable. Each value in the array can be accessed and manipulated using an indexed number known as the index.

.Concat() Method
// Array pop() Method
let language = ["Javascript", "Java"];
let designLanguage = ["Html","Css"]

let joinedArray = language.concat(designLanguage);
console.log(joinedArray); //["Javascript", "Java","Html","Css"];

The Array.concat() function merges two or more arrays into one array. It creates a new Array that includes the elements of the given arrays and returns the new Array.

.Push() Method
// Array push() Method
let language = ["Javascript", "Java", "Python"];

// add "Php" to the array
language.push("Php");
console.log(language);          

The Array.push() method in JavaScript adds one or many elements to the bottom of an array and returns the new length of the Array.

.Fill() Method
//defining an array 
var fruits = ['Apple', 'Banana', 'Mango'];

// filling every element of the array with 'Orange'
fruits.fill("Orange");
console.log(fruits); // ['Orange', 'Orange', 'Orange']

The Array.fill() method in JavaScript fills all the elements of an array from a start index to an end index with a static value.

.Pop() Method
// Array pop() Method
let language = ["Javascript", "Java", "Python","Php"];

// remove the last element
let removedlanguage = language.pop();

console.log(language) // ["Javascript", "Java", "Python","Php"]
console.log(removedlanguage); // Php

The Array.pop() method is a JavaScript function that removes the final element from an array and returns that element. This function changes the length of the Array.

.Reverse() Method
let primeNumber = [1, 3, 5, 7, 11];

// reversing the primeNumber array
let reversedArray = primeNumber.reverse();

console.log(reversedArray);
// Output: [ 11, 7, 5, 3, 1]    

The Array.reverse() method in JavaScript is used to flip the order of the elements in the array. The last array element becomes the first, and the first becomes the last.

# Functions :

Declaring And CallingFunction
// declaring a function named demo()
function demo() {
    console.log("Hello Javascript...!!");
}
//calling Function
demo();                         

In JavaScript, a function is a set of statements that performs a specific task. The Function can be called and executed when needed and can also be declared or defined to be called later.

Function With Parameter
// declaring a function
function addition(a, b) {
    console.log(a + b);
}
// calling functions
addition(3,6);                  

In JavaScript, a function with a parameter is a function that can accept input values, known as parameters or arguments, when it is called. These parameters are used as variables within the function body and can be used to perform calculations or operations within the function.

Return Keyword
let x = myMulFunction(3, 9);   // Function is called, return value will end up in x

function myMulFunction(a, b) {
  return a * b;  // Function returns the product of a and b
  // 27
}                               

The return keyword in JavaScript is used to stop the execution of a function and return a value from that function. It can be used to return a specified or no value.

# Objects :

Object
//Object Declaration
let object_name = {
   key1: value1,
   key2: value2,
   key3: value3
}

// object person
let person = {
  name: "Marek Lux",
  age: 36,
  city: "New York"
};

console.log(typeof person); // object

In JavaScript, an object is a complex data type allowing you to store related data and functionalities. It is a container for named values, which are called properties, and functions, called methods.

Dot Notation
//Accessing Object With Dot Notation
objectName.key

// object person
let person = {
  name: "Marek Lux",
  age: 36,
  city: "New York"
};

console.log(person.name); // Marek Lux

In JavaScript, object accessing with dot notation refers to a way of accessing the properties and methods of an object using a dot (.) followed by the name of the property or method.

Bracket Notation
//Accessing Object With Bracket Notation
objectName["propertyName"]

// object person
let person = {
  name: "Marek Lux",
  age: 36,
  city: "New York"
};

// accessing property
console.log(person["city"]); // New York

In JavaScript, object accessing with bracket notation is a way to retrieve or set the value of a property in an object using square brackets and a string that represents the property name.

# Classes :

Class
//Class Declaration
class ClassName {
  constructor() 
  {     
    ... 
  }
}

// creating a class car
class car {
  constructor(modelName, year) {
    this.modelName = modelName;
    this.year = year;
  }
}

// creating an object
const myCar1 = new Car("MG Hector", 2023);
const myCar2 = new Car("Scorpio", 2019);

console.log(myCar1.modelName); // MG Hector
console.log(myCar1.year); // 2023

Classes in JavaScript are a type of method or function, and they are used as a blueprint for creating objects. They allow you to create a template to create multiple objects with the same properties and methods.

Class Methods
//Class Method Declaration
class ClassName {
  constructor() 
  { 
    ... 
  }
  method_1() 
  { 
    ... 
  }
}

// creating a class car
class car {
  constructor(modelName, year) {
    this.modelName = modelName;
    this.year = year;
  }
  age() {
    const date = new Date();
    return date.getFullYear() - this.year;
  }
}

// creating an object
const myCar1 = new Car("MG Hector", 2018);
const myCar2 = new Car("Scorpio", 2019);

console.log(myCar1.modelName); // MG Hector
console.log(myCar1.year); // 2018
console.log(myCar1.age()); // 5 Year

Class methods in JavaScript are the functions defined inside the class constructor. They provide functionality and behavior for objects created from that class. Class methods can be called from both within the Class, as well as from outside of it.

# Iterators :

Iterator
//String Iterator
const str = 'Hello Javascript!!';

// calling the Symbol.iterator() method
const strIterator = str[Symbol.iterator]();

// gives String Iterator
console.log(strIterator); //StringIterator {}

//Array Iterator
const arr = [3, 6 ,9];

// calling the Symbol.iterator() method
const arrIterator = arr[Symbol.iterator]();

// Gives Array Iterator
console.log(arrIterator); //Array Iterator {}

An iterator in Javascript is an object which represents a series and potentially a return value upon its termination. Iterators can be used to loop through data structures such as Arrays, Maps, and Sets, or even custom objects.

next() Method
// Create an array 
const arr = ['J', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't'];

//Get an iterator for the array
let arrIterator = arr[Symbol.iterator]();

console.log(arrIterator.next()); // {value: "J", done: false}
console.log(arrIterator.next()); // {value: "a", done: false}
console.log(arrIterator.next()); // {value: "v", done: false}
console.log(arrIterator.next()); // {value: "a", done: false}
console.log(arrIterator.next()); // {value: "s", done: false}
console.log(arrIterator.next()); // {value: "c", done: false}
console.log(arrIterator.next()); // {value: "r", done: false}
console.log(arrIterator.next()); // {value: "i", done: false}
console.log(arrIterator.next()); // {value: "p", done: false}
console.log(arrIterator.next()); // {value: "t", done: false}
console.log(arrIterator.next()); // {value: undefined, done: true}

In JavaScript, an iterator is an complex object that provides a sequence of values to be iterated (looped) over. The next() method is a built-in method in the iterator object that is used to retrieve the next value in the sequence.

# Modules :

Modules
//exporting a function
export function person(name) {
    return `Hello ${name}`;
}

// importing person from person.js file
import { person } from './person.js';

// using person() defined in greet.js
let displayName = person('JavaScript!!!');

console.log(displayName); // Hello JavaScript!!!

Modules are reusable pieces of code that can be exported from one program and imported for use in another. Modules are beneficial for several reasons. Finally, modules make it easier to reuse code across multiple applications.

Export Multiple Objects
//exporting the variable
export const name = 'JavaScript Program';

// exporting the function
export function sum(x, y) {
    return x + y;
}
In main file,

import { name, sum } from './demoModfule.js';

console.log(name);
let add = sum(3, 9);
console.log(add); // 12

Export multiple objects in JavaScript allows you to export multiple variables, functions, or classes from a single module. You can use the keyword 'export' to export any number of objects from the same module.

# Promises :

Promises
//Create a Promise
let promise = new Promise(function(resolve, reject)
{
    //do something
});

const counter = true;

let counterValue = new Promise(function (resolve, reject) {
    if (counter) {
        resolve("There is a counter value.");
    } else {
        reject("There is not a counter value");
    }
});

console.log(counterValue); 
//Promise {<resolved>: "There is a counter value."}

In JavaScript, a promise is a complex object representing an asynchronous operation's eventual completion or failure and its resulting value. A promise is handling asynchronous operations, such as fetching data from an API, without blocking the main thread or waiting for the process to complete before proceeding to the next task.

Catch() Method
// returns a promise
let counterValue = new Promise(function (resolve, reject) 
{
   reject('Promise rejected'); 
});

// executes when promise is resolved successfully
counterValue.then(
    function successValue(result) {
        console.log(result);
    },
 )

// executes if there is an error
.catch(
    function errorValue(result) {
        console.log(result); 
        //Promise rejected
    }
);

In JavaScript Promises, the catch() method handles errors in a Promise chain. When a Promise is rejected or encounters an error, the catch() method is called with the error message.

Finally() Method
// returns a promise

let counterValue = new Promise(function (resolve, reject) 
{
    // could be resolved or rejected   
    resolve('Promise resolved'); 
});

// add other blocks of code

counterValue.finally(
    function demo() 
    {
        console.log('This code is executed.');
    }
);

The finally() method is a method that can be called on a Promise object in JavaScript. It allows you to register a callback function that will be called when the Promise is either resolved or rejected. The finally() method will be executed regardless of whether the Promise was resolved or rejected.

# Async - Await :

Async Function
//Create a Async Function
async function name(parameter1, parameter2, ...paramaterN) {
    // statements
}

// async function example

async function demo() {
    console.log('Hello Async function.'); //Hello Async function.
    return Promise.resolve(1);
}

demo(); 

We use the keyword async with a function to represent the function asynchronously. The async function returns a promise. An async function in JavaScript is a type of function that is used to write asynchronous code more cleanly and concisely.

Await Keyword
//Create a Await Keyword
let result = await promise;
// a promise
let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
    resolve('Promise resolved')}, 4000); 
});

// async function
async function asyncFuncDemo() {
    // wait until the promise resolves 
    let result = await promise; 
    console.log(result); // Promise resolved
    console.log('Hello Javascript'); // Hello Javascript
}
// calling the async function
asyncFuncDemo();

The await keyword is used in an asynchronous function to pause the execution of the function until a Promise is resolved.

JS CheatSheet Online


A JavaScript cheat sheet is a quick reference guide summarizing the JavaScript programming language's essential concepts, syntax, and features. It typically includes snippets of code, explanations of standard functions and methods, and examples of how to use them.

JavaScript cheat sheets are helpful for both beginners and experienced developers who need to look up syntax or recall certain concepts quickly. They can be printed out and kept on a desk for easy access or bookmarked for quick reference online.

Know more about JavaScript on MDN Web Docs

  • The online JavaScript Cheat Sheet works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.