JavaScript Cheatsheet

A comprehensive reference guide for JavaScript syntax, methods, and concepts. Perfect for adding interactivity and dynamic behavior to your web pages.

Variables & Data Types

Variable Declarations

let name = "John";
const age = 25;
var city = "New York";

Data Types

// Primitive
let str = "Hello";
let num = 42;
let bool = true;
let nothing = null;
let notDefined;
let sym = Symbol();

// Reference
let obj = {};
let arr = [];

Type Checking

typeof variable;
Array.isArray(arr);
instanceof constructor;
Operators

Arithmetic

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)
** (exponentiation)
++ (increment)
-- (decrement)

Comparison

== (equal)
=== (strict equal)
!= (not equal)
!== (strict not equal)
> (greater than)
< (less than)
>= (greater or equal)
<= (less or equal)

Logical

&& (AND)
|| (OR)
! (NOT)
?? (nullish coalescing)
Functions

Function Declaration

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

Arrow Function

const add = (a, b) => a + b;

// With block
const multiply = (a, b) => {
return a * b;
};

Function Expression

const sayHi = function() {
console.log("Hi!");
};

Higher Order Functions

arr.map(item => item * 2);
arr.filter(item => item > 5);
arr.reduce((acc, item) => acc + item, 0);
Arrays

Creating Arrays

let arr = [1, 2, 3];
let arr2 = new Array(1, 2, 3);
let arr3 = Array.of(1, 2, 3);

Array Methods

arr.push(item);
arr.pop();
arr.shift();
arr.unshift(item);
arr.slice(start, end);
arr.splice(start, deleteCount, items);

Iteration

arr.forEach(item => console.log(item));
arr.map(item => item * 2);
arr.filter(item => item > 5);
arr.find(item => item === 5);
arr.reduce((acc, item) => acc + item, 0);
Objects

Creating Objects

let obj = {
name: "John",
age: 25
};

const obj2 = new Object();
obj2.name = "Jane";

Object Methods

Object.keys(obj);
Object.values(obj);
Object.entries(obj);
Object.assign(target, source);
Object.freeze(obj);

Destructuring

const {name, age} = obj;

// With default
const {name = "Unknown"} = obj;
Control Flow

If Statement

if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
}

Switch

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

Ternary Operator

condition ? valueIfTrue : valueIfFalse;
Loops

For Loop

for (let i = 0; i < 10; i++) {
console.log(i);
}

While Loop

while (condition) {
// code
}

Do-While

do {
// code
} while (condition);

For...In & For...Of

for (let key in obj) {
console.log(key);
}

for (let item of arr) {
console.log(item);
}
DOM Manipulation

Selecting Elements

document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('div');

Modifying Elements

element.textContent = 'New text';
element.innerHTML = 'Bold';
element.style.color = 'red';
element.classList.add('active');

Creating Elements

const div = document.createElement('div');
div.textContent = 'Hello';
document.body.appendChild(div);
Events

Event Listeners

element.addEventListener('click', function() {
// handle click
});

// Arrow function
element.addEventListener('click', () => {
// handle click
});

Common Events

click
dblclick
mousedown
mouseup
mouseover
mouseout
keydown
keyup
submit
load
resize

Event Object

element.addEventListener('click', (e) => {
console.log(e.target);
console.log(e.type);
e.preventDefault();
e.stopPropagation();
});
ES6+ Features

Template Literals

const name = "John";
const greeting = `Hello, ${name}!`;

Destructuring

// Array
const [a, b] = [1, 2];

// Object
const {name, age} = person;

Spread Operator

const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];

const obj = {...obj1, newProp: 'value'};

Modules

// Export
export const PI = 3.14;
export default function() {}

// Import
import { PI } from './math';
import myFunc from './myFunc';
Async JavaScript

Callbacks

function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}

Promises

const promise = new Promise((resolve, reject) => {
if (success) {
resolve('Success!');
} else {
reject('Error!');
}
});

promise.then(data => console.log(data))
.catch(error => console.log(error));

Async/Await

async function fetchData() {
try {
const response = await fetch('url');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
Error Handling

Try-Catch

try {
// risky code
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
} finally {
// always runs
}

Custom Errors

class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}

What is CodeSikhoWithAJ?

CodeSikhoWithAJ is a coding education platform dedicated to teaching programming skills to everyone who wants to learn. Our mission is to make coding accessible and help people start their journey in the tech industry.

Founded by Ajeet Yadav, CodeSikhoWithAJ provides comprehensive tutorials, practical examples, and hands-on projects to help you master web development and other programming skills.

Trusted by developers at:

Google
Microsoft
Facebook
Amazon
Netflix
Twitter