JavaScript is a versatile and powerful programming language essential for web development. This cheat sheet covers the fundamental concepts and syntax, providing a reference for both beginners and experienced developers.
Basics
Hello, World!
console.log("Hello, World!");
Comments
// Single line comment
/*
Multi-line comment
*/
Variables
Declaration
let x = 10; // Block-scoped variable
const y = 20; // Block-scoped, read-only variable
var z = 30; // Function-scoped variable (avoid using var)
Data Types
Primitive Types
- Number
- String
- Boolean
- Undefined
- Null
- Symbol (ES6+)
- BigInt (ES2020)
let num = 42; // Number
let str = "Hello"; // String
let bool = true; // Boolean
let undef; // Undefined
let nil = null; // Null
let sym = Symbol(); // Symbol
let bigInt = 9007199254740991n; // BigInt
Type Checking
console.log(typeof num); // "number"
Operators
Arithmetic Operators
let a = 5 + 2; // Addition
let b = 5 - 2; // Subtraction
let c = 5 * 2; // Multiplication
let d = 5 / 2; // Division
let e = 5 % 2; // Modulus
let f = 5 ** 2; // Exponentiation (ES6+)
Assignment Operators
let x = 10;
x += 5; // x = x + 5
Comparison Operators
let equal = (x == y); // Loose equality
let strictEqual = (x === y); // Strict equality
let notEqual = (x != y); // Loose inequality
let strictNotEqual = (x !== y); // Strict inequality
let greater = (x > y); // Greater than
let less = (x < y); // Less than
Logical Operators
let and = (x && y); // Logical AND
let or = (x || y); // Logical OR
let not = !x; // Logical NOT
Control Flow
Conditional Statements
if (condition) {
// code block
} else if (anotherCondition) {
// another code block
} else {
// default code block
}
Switch Statement
switch (expression) {
case value1:
// code block
break;
case value2:
// another code block
break;
default:
// default code block
}
Loops
For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
While Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Do-While Loop
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Functions
Function Declaration
function add(a, b) {
return a + b;
}
Function Expression
const subtract = function (a, b) {
return a - b;
};
Arrow Function (ES6+)
const multiply = (a, b) => a * b;
Arrays
Array Declaration
let arr = [1, 2, 3, 4, 5];
Array Methods
arr.push(6); // Add to end
arr.pop(); // Remove from end
arr.shift(); // Remove from beginning
arr.unshift(0); // Add to beginning
arr.slice(1, 3); // Extract sub-array
arr.splice(2, 1); // Remove elements
Objects
Object Declaration
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function () {
console.log("Hello, " + this.firstName);
},
};
Accessing Object Properties
console.log(person.firstName); // Dot notation
console.log(person["lastName"]); // Bracket notation
Object Methods
person.greet();
DOM Manipulation
Selecting Elements
let element = document.getElementById("myId");
let elements = document.getElementsByClassName("myClass");
let queryElement = document.querySelector(".myClass");
let queryElements = document.querySelectorAll(".myClass");
Modifying Elements
element.innerHTML = "New Content";
element.style.color = "blue";
element.setAttribute("class", "newClass");
Events
Adding Event Listeners
element.addEventListener("click", function () {
alert("Element clicked!");
});
ES6+ Features
Template Literals
let name = "John";
let greeting = `Hello, ${name}!`;
Destructuring
let [a, b] = [1, 2];
let { firstName, lastName } = person;
Spread Operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5, 6];
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 };
Asynchronous JavaScript
Promises
let promise = new Promise((resolve, reject) => {
// asynchronous operation
if (success) {
resolve("Success!");
} else {
reject("Failure!");
}
});
promise.then((message) => {
console.log(message);
}).catch((error) => {
console.error(error);
});
Async/Await (ES8)
async function fetchData() {
try {
let response = await fetch("url");
let data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
Error Handling
Try-Catch
try {
// code that may throw an error
} catch (error) {
console.error(error);
} finally {
// code that will always run
}
Throwing Errors
function checkPositive(number) {
if (number < 0) {
throw new Error("Negative number not allowed");
}
return number;
}
try {
checkPositive(-1);
} catch (error) {
console.error(error.message);
}