JavaScript Cheat Sheet
Introduction
JavaScript is a versatile, high-level programming language primarily used for web
development. It enables interactive web pages and is an essential part of web
applications.
Basics
Variables & Constants
// Declaring variables
var x = 10; // Function-scoped (not recommended)
let y = 20; // Block-scoped
const z = 30; // Immutable (cannot be reassigned)
Data Types
let name = "John"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let hobbies = ["Reading", "Sports"]; // Array
let person = { name: "Alice", age: 30 }; // Object
let value = null; // Null
let something; // Undefined
Operators
let sum = 10 + 5; // Addition
let diff = 10 - 5; // Subtraction
let mult = 10 * 5; // Multiplication
let div = 10 / 5; // Division
let mod = 10 % 3; // Modulus (remainder)
let exp = 2 ** 3; // Exponentiation
Comparison Operators
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(10 > 5); // true
console.log(10 < 5); // false
Control Flow
Conditional Statements
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Loops
// For Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}
// While Loop
let count = 0;
while (count < 5) {
console.log("Count:", count);
count++;
}
// Do-While Loop
let num = 0;
do {
console.log("Number:", num);
num++;
} while (num < 5);
Functions
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("John"));
Arrow Function
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
Anonymous Function
const square = function (num) {
return num * num;
};
console.log(square(4)); // 16
Objects
Object Declaration
let person = {
name: "Alice",
age: 30,
greet: function () {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet());
Object Destructuring
const { name, age } = person;
console.log(name, age);
Arrays
Array Declaration
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Apple
Array Methods
fruits.push("Mango"); // Add element to end
fruits.pop(); // Remove last element
fruits.unshift("Grape"); // Add to beginning
fruits.shift(); // Remove first element
console.log(fruits.join(" - ")); // Apple - Banana
Array Destructuring
let [first, second] = fruits;
console.log(first, second);
ES6+ Features
Template Literals
let name = "John";
let message = `Hello, ${name}!`;
console.log(message);
Spread Operator
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
Rest Parameters
function sum(...args) {
return args.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Promises & Async/Await
Promises
let fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched!");
}, 2000);
});
fetchData.then((data) => console.log(data));
Async/Await
async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data Loaded!");
}, 2000);
});
}
async function displayData() {
let data = await fetchData();
console.log(data);
}
displayData();
DOM Manipulation
Selecting Elements
let element = document.getElementById("myId");
let elements = document.getElementsByClassName("myClass");
let queryElement = document.querySelector(".myClass");
Modifying Elements
let heading = document.querySelector("h1");
heading.textContent = "New Heading!";
heading.style.color = "blue";
Event Listeners
document.getElementById("btn").addEventListener("click", () => {
alert("Button Clicked!");
});
Local Storage
localStorage.setItem("name", "John");
console.log(localStorage.getItem("name"));
localStorage.removeItem("name");
Error Handling
try {
let result = 10 / 0;
throw new Error("Something went wrong!");
} catch (error) {
console.error(error.message);
} finally {
console.log("Execution completed.");
}
Conclusion
JavaScript is a powerful language that enables dynamic web applications. Mastering the
basics and advanced concepts will help in building modern web applications
efficiently.