JavaScript Cheat Sheet
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
Operators
Comparison Operators
Control Flow
Conditional Statements
let age = 18;
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
Anonymous Function
Object Declaration
let person = {
name: "Alice",
age: 30,
greet: function () {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet());
Object Destructuring
Arrays
Array Declaration
Array Methods
Array Destructuring
ES6+ Features
Template Literals
Rest Parameters
function sum(...args) {
return args.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
Async/Await
displayData();
DOM Manipulation
Selecting Elements
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.