Home Cheatsheets JavaScript Language Cheat Sheet

JavaScript Language Cheat Sheet

1. Basic Syntax

Structure of a JavaScript Program:

// Inline comment

/*
Multi-line comment
*/

console.log("Hello, World!"); // Output to console

2. Variables

Declaration:

var name = "John"; // Global or function scope
let age = 25;      // Block scope
const PI = 3.14;   // Constant value, block scope

Types of Variables:

Type Description Example
string Text let name = "John";
number Numeric values let age = 30;
boolean True or False let isTrue = true;
array Collection of elements let fruits = ["Apple", "Banana"];
object Key-value pairs let person = {name: "John", age: 25};
undefined Variable without value let x;
null No value let y = null;

3. Operators

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b
++ Increment a++
-- Decrement a--
== Equal to a == b
=== Strict equal a === b
!= Not equal a != b
!== Strict not equal a !== b
&& Logical AND a && b
` `
! Logical NOT !a
+= Addition assignment a += b

Conditional Statements

if-else Statement:

if (condition) {
    // code block if condition is true
} else {
    // code block if condition is false
}

switch Statement:

switch (expression) {
    case 'value1':
        // code block
        break;
    case 'value2':
        // code block
        break;
    default:
        // code block
}

Loops

for Loop:

for (let i = 0; i < 5; i++) {
    // code block
}

while Loop:

let i = 0;
while (i < 5) {
    // code block
    i++;
}

do-while Loop:

let i = 0;
do {
    // code block
    i++;
} while (i < 5);

5. Functions

Function Declaration:

function sum(a, b) {
    return a + b;
}

Function Expression:

const multiply = function(a, b) {
    return a * b;
};

Arrow Function:

const subtract = (a, b) => a - b;

Default Parameters:

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

6. Arrays

Array Declaration:

let fruits = ["Apple", "Banana", "Orange"];

Accessing Elements:

let firstFruit = fruits[0]; // "Apple"

Array Methods:

push(): Add to the end
pop(): Remove from the end
shift(): Remove from the beginning
unshift(): Add to the beginning
length: Get the number of elements

fruits.push("Mango");
let fruitCount = fruits.length;

7. Objects

Object Declaration:

let person = {
    name: "John",
    age: 30,
    greet: function() {
        return `Hello, my name is ${this.name}`;
    }
};

Accessing Object Properties:

console.log(person.name);    // "John"
console.log(person['age']);  // 30

Object Methods:

console.log(person.greet()); // "Hello, my name is John"

8. String Methods

Method Description Example
length Returns the length of a string "hello".length
toUpperCase() Converts a string to uppercase "hello".toUpperCase()
toLowerCase() Converts a string to lowercase "HELLO".toLowerCase()
indexOf() Finds the index of a substring "hello".indexOf("e")
slice() Extracts a substring "hello".slice(1, 3)
replace() Replaces a substring "hello".replace("l", "p")
split() Splits a string into an array "a,b,c".split(",")

 

9. JSON (JavaScript Object Notation)

JSON Object:

let jsonObject = {
    "name": "John",
    "age": 30
};

Convert Object to JSON:

let jsonString = JSON.stringify(jsonObject);

Parse JSON to Object:

let parsedObject = JSON.parse(jsonString);

10. Event Handling (in DOM)

Add an Event Listener:

document.getElementById("myButton").addEventListener("click", function() {
    alert("Button clicked!");
});

Mouse Events:

click, dblclick, mouseenter, mouseleave

Keyboard Events:

keydown, keyup

11. DOM Manipulation

Accessing Elements:

document.getElementById("myId");
document.querySelector(".myClass");

Changing Content:

document.getElementById("myId").textContent = "New content";
document.getElementById("myId").innerHTML = "<strong>Bold text</strong>";

Changing Styles:

document.getElementById("myId").style.color = "red";

12. Error Handling

try-catch Block:

try {
    // Code that may throw an error
} catch (error) {
    console.error(error);
} finally {
    // Code that always runs
}

13. Promises and Asynchronous JavaScript

Creating a Promise:

let promise = new Promise(function(resolve, reject) {
    let success = true;
    if (success) {
        resolve("Success!");
    } else {
        reject("Failure!");
    }
});

Handling a Promise:

promise.then(function(value) {
    console.log(value); // Success!
}).catch(function(error) {
    console.log(error); // Failure!
});

Async-Await Syntax:

async function fetchData() {
    try {
        let response = await fetch("https://api.example.com/data");
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

14. Classes

Class Declaration:

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

    greet() {
        return `Hello, my name is ${this.name}`;
    }
}

Creating an Object from a Class:

let person1 = new Person("Alice", 25);
console.log(person1.greet()); // "Hello, my name is Alice"

15. Modules (ES6)

Export a Module:

// file: myModule.js
export const PI = 3.14;

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

Import a Module:

// file: main.js
import { PI, square } from './myModule.js';
console.log(PI);              // 3.14
console.log(square(5));        // 25

16. Common Built-in Functions

Function Description
alert() Shows an alert dialog box
prompt() Takes input from the user
console.log() Logs output to the browser console
setTimeout() Executes code after a delay
setInterval() Repeats code at specified intervals
Math.random() Returns a random number between 0 and 1
Math.floor() Rounds down a number
parseInt() Converts a string to an integer

17. Common Escape Sequences

Escape Sequence Description
\n Newline
\t Tab
\\ Backslash
\' Single quote
\" Double quote

18. Example Program

A simple program to add two numbers and display the result:

function addNumbers(a, b) {
    return a + b;
}

let num1 = parseInt(prompt("Enter first number:"));
let num2 = parseInt(prompt("Enter second number:"));
let sum = addNumbers(num1, num2);

alert("The sum is: " + sum);

This cheat sheet provides a quick reference for fundamental concepts and syntax in JavaScript.

You may also like