JS

JavaScript Cheat Sheet

The core syntax and built-in methods from the JavaScript track, from your first script to fetch and async. The arrow (→) shows the result of a row; follow the lesson links for worked examples.

JavaScript lessons Take the quiz

Getting started Lesson

<script src="app.js" defer></script>Loads a script that runs after the HTML is parsed
<script> … </script>Inline script, placed before </body>
console.log(total);Prints a value in the DevTools console
document.querySelector('#out').textContent = 'Hi';Shows a result on the page
// one lineSingle-line comment
/* several lines */Multi-line comment
let total = 10;End statements with a semicolon to be safe

JavaScript is case-sensitive: total and Total are different names.

Variables and data types Lesson

let score = 0;A variable you can reassign
const city = 'Madurai';Cannot be reassigned; use it by default
'text' "text" `text`String (text)
42 3.14 -7Number (integers and decimals)
true falseBoolean
null undefinedEmpty on purpose / not set yet
typeof 42→ 'number'
typeof null→ 'object' (a famous old quirk)
Number('42')→ 42; converts text to a number
'5' + 3→ '53'; + joins when one side is text
'5' * 2→ 10; other maths operators convert to numbers

Operators Lesson

+ - * /Add, subtract, multiply, divide
7 % 3→ 1; the remainder
2 ** 3→ 8; exponent (power)
x += 5Same as x = x + 5
count++Adds 1 to count
a === bStrictly equal: same value and same type
a !== bStrictly not equal
5 == '5'→ true; loose equality converts types – avoid it
< > <= >=Comparisons
a && bAND: true only if both are truthy
a || bOR: true if either is truthy
!isOpenNOT: flips true and false

Conditions Lesson

if (age >= 18) { … }Runs the block when the condition is true
else if (age >= 13) { … }Checks another condition
else { … }Runs when nothing above matched
const label = isMember ? 'Member' : 'Guest';Ternary: a short if/else that gives a value
switch (day) { case 'Sat': … break; default: … }Compares one value against many cases
false 0 '' null undefined NaNThe main falsy values; almost everything else is truthy
if (!name) { … }Runs when name is empty or missing

Forgetting break in a switch makes the next case run too.

Loops Lesson

for (let i = 0; i < 5; i++) { … }Counts from 0 to 4
while (tries < 3) { … }Repeats while the condition is true
do { … } while (x < 3);Runs at least once, then checks
for (const city of cities) { … }Each value of an array or string
for (const key in obj) { … }Each property name of an object
break;Leaves the loop immediately
continue;Skips to the next round
cities.forEach((city, i) => { … });Array method that runs a function per item

Functions Lesson

function greet(name) { return `Hi ${name}`; }Function declaration
greet('Asha')→ 'Hi Asha'; calling the function
function area(w, h = 1) { … }Default value when an argument is missing
const add = (a, b) => a + b;Arrow function with an implicit return
const double = n => n * 2;One parameter needs no brackets
const fn = function () { … };Function expression stored in a variable
setTimeout(() => { … }, 1000);Passes a callback to run after 1 second
return;Ends the function; it returns undefined

Variables declared with let or const inside { } exist only in that block.

Arrays: basics Lesson

const fruits = ['mango', 'banana', 'guava'];Creates an array
fruits[0]→ 'mango'; indexes start at 0
fruits.length→ 3
fruits.at(-1)→ 'guava'; negative counts from the end
fruits.push('apple')Adds to the end
fruits.pop()Removes and returns the last item
fruits.unshift('fig') fruits.shift()Add to / remove from the start
fruits.includes('mango')→ true
fruits.indexOf('banana')→ 1; -1 if not found
fruits.slice(1, 3)New array of items 1 and 2
fruits.splice(1, 1)Removes 1 item at index 1 (changes the array)
fruits.join(', ')→ 'mango, banana, guava'

Arrays: transform and copy Lesson

nums.map(n => n * 2)New array with each item changed
nums.filter(n => n > 10)New array of the items that pass
nums.find(n => n > 10)First item that passes, or undefined
nums.some(n => n < 0)true if any item passes
nums.every(n => n > 0)true if all items pass
nums.reduce((sum, n) => sum + n, 0)Combines all items into one value
nums.sort((a, b) => a - b)Sorts numbers ascending (changes the array)
nums.toSorted((a, b) => a - b)Sorted copy; the original is unchanged
[...nums]A shallow copy of the array
Array.isArray(nums)→ true for arrays

Without a compare function, sort() sorts as text: [10, 9, 1] becomes [1, 10, 9].

Objects Lesson

const user = { name: 'Ravi', age: 28 };Creates an object
user.name→ 'Ravi'; dot notation
user['first name']Bracket notation for odd or dynamic keys
user.city = 'Pune';Adds or changes a property
delete user.age;Removes a property
'name' in user→ true if the property exists
Object.keys(user)Array of property names
Object.entries(user)Array of [key, value] pairs
greet() { return this.name; }A method; this is the object
JSON.stringify(user)Object → JSON text
JSON.parse(text)JSON text → object
structuredClone(user)A deep copy, nested objects included

const b = a copies the reference: both names point to the same object.

DOM manipulation Lesson

document.querySelector('.card')First matching element, or null
document.querySelectorAll('li')All matches, as a NodeList
document.getElementById('menu')The element with that id
el.textContent = 'Saved';Sets plain text (safe for user input)
el.innerHTML = '<b>Saved</b>';Sets HTML – only for content you trust
el.classList.add('open')Also remove, toggle and contains
el.style.color = 'teal';Sets an inline style
el.setAttribute('aria-expanded', 'true')Sets any attribute
el.dataset.priceReads data-price
const li = document.createElement('li');Creates a new element
list.append(li);Adds it as the last child
el.remove();Removes the element from the page

Events Lesson

btn.addEventListener('click', handleClick);Runs a function on every click
'click' 'input' 'change' 'submit' 'keydown'Common event names
event.targetThe element where the event started
event.currentTargetThe element the listener is attached to
event.preventDefault();Stops the default, e.g. a form submitting
if (event.key === 'Enter') { … }Checks which key was pressed
e.target.closest('li')Delegation: in a parent's listener, finds the clicked item
{ once: true }Option: the listener runs only once
btn.removeEventListener('click', handleClick);Removes a listener (needs the same function)

Modern features (ES6+) Lesson

`Total: ₹${price * qty}`Template literal with an embedded expression
const { name, age } = user;Object destructuring
const [first, second] = list;Array destructuring
const all = [...a, ...b];Spread: joins arrays
const updated = { ...user, age: 29 };Copy of an object with one change
function sum(...nums) { … }Rest: collects arguments into an array
user?.address?.cityOptional chaining: undefined instead of an error
qty ?? 1Nullish coalescing: 1 only if qty is null or undefined
class Product { constructor(name) { this.name = name; } }A class with a constructor
export function formatPrice(n) { … }Exports from a module file
import { formatPrice } from './utils.js';Imports into another module
<script type="module" src="app.js"></script>Loads a file as a module

Fetch and async Lesson

async function loadUsers() { … }An async function always returns a promise
const res = await fetch(url);Waits for the response
if (!res.ok) throw new Error(`HTTP ${res.status}`);fetch does not reject on 404 or 500 – check ok
const data = await res.json();Reads the body as JSON
try { … } catch (err) { … }Handles network and parsing errors
fetch(url).then(res => res.json()).then(show);The same idea with .then()
{ method: 'POST', body: JSON.stringify(data) }Second fetch argument for sending data
headers: { 'Content-Type': 'application/json' }Tells the server you are sending JSON
await Promise.all([p1, p2]);Waits for several promises at once