๐Ÿ“œ JavaScript ES6+
JavaScript Complete Cheatsheet
From variables to async/await โ€” everything you need for modern JS development.
๐Ÿ“– 10 sections
โฑ 18 min read
โœ… Quizzes included
๐ŸŒ™ Dark mode
01 Variables & Types โ–ผ
Declarations
JSVariable declarations
var   x = 10;      // function-scoped, avoid
let   y = 20;      // block-scoped, reassignable
const z = 30;      // block-scoped, constant reference
Data Types
Primitives
string, number, boolean, null, undefined, symbol, bigint
Type check
typeof 42 โ†’ 'number'
typeof null โ†’ 'object' โš ๏ธ
Type coercion
'5' + 3 โ†’ '53'
'5' - 3 โ†’ 2
Falsy values
false, 0, '', null, undefined, NaN
๐Ÿ’ก
Use === (strict equality) instead of == to avoid type coercion bugs.
02 Functions & Scope โ–ผ
Function Types
JSAll function syntaxes
// Declaration (hoisted)
function greet(name) {{ return `Hello ${{name}}`; }}

// Expression (not hoisted)
const add = function(a, b) {{ return a + b; }};

// Arrow function
const multiply = (a, b) => a * b;

// Default parameters
const power = (base, exp = 2) => base ** exp;

// Rest parameters
const sum = (...nums) => nums.reduce((a, b) => a + b, 0);
Scope
Closure
Inner function retains access to outer scope even after outer returns.
Hoisting
var and function declarations are moved to the top of scope.
IIFE
(function(){{ ... }})() โ€” runs immediately, creates own scope.
03 Arrays โ–ผ
Array Methods
JSEssential array methods
const nums = [1, 2, 3, 4, 5];

nums.map(x => x * 2);          // [2,4,6,8,10]
nums.filter(x => x > 2);       // [3,4,5]
nums.reduce((acc,x) => acc+x, 0); // 15
nums.find(x => x > 3);          // 4
nums.some(x => x > 4);          // true
nums.every(x => x > 0);         // true
nums.includes(3);               // true
[...1,2].concat([3,4]);           // spread + concat
nums.slice(1, 3);                 // [2,3] (non-destructive)
nums.splice(1, 2);                // removes 2 from index 1
๐Ÿ’ก
Array methods like map, filter, reduce are chainable and return new arrays โ€” they don't mutate the original.
04 Objects โ–ผ
Object Basics
JSObjects, destructuring, spread
const user = {{ name: 'Ali', age: 22, role: 'dev' }};

// Access
user.name;          // 'Ali'
user['age'];        // 22

// Destructuring
const {{ name, age }} = user;
const {{ name: n, role: r = 'user' }} = user; // rename + default

// Spread
const updated = {{ ...user, age: 23 }};

// Methods
Object.keys(user);    // ['name','age','role']
Object.values(user);  // ['Ali',22,'dev']
Object.entries(user); // [['name','Ali'],...]
Optional chaining
user?.address?.city โ€” safe access, returns undefined instead of error
Nullish coalescing
val ?? 'default' โ€” uses default only if val is null/undefined
Computed keys
const key='name'; {{[key]:'Ali'}}
05 DOM Manipulation โ–ผ
Selecting Elements
JSDOM selectors
document.getElementById('myId');
document.querySelector('.class');     // first match
document.querySelectorAll('div.box');  // NodeList
el.closest('.parent');               // nearest ancestor

// Modify
el.textContent = 'Hello';
el.innerHTML = '<b>Bold</b>';
el.style.color = 'red';
el.classList.add('active');
el.classList.toggle('open');
el.setAttribute('href', '#');

// Events
el.addEventListener('click', e => {{
  e.preventDefault();
  console.log('clicked!');
}});
๐Ÿ’ก
Use addEventListener rather than inline onclick to separate concerns and attach multiple listeners.
06 ES6+ Features โ–ผ
Modern JavaScript
JSES6+ essentials
// Template literals
const msg = `Hello ${{name}}, you are ${{age}} years old!`;

// Destructuring in params
const greet = ({{ name, age }}) => `${{name}} (${{age}})`;

// Modules
export default MyClass;
export {{ fn1, fn2 }};
import MyClass from './module';
import {{ fn1 }} from './utils';

// Classes
class Animal {{
  constructor(name) {{ this.name = name; }}
  speak() {{ return `${{this.name}} makes a sound`; }}
}}
class Dog extends Animal {{
  speak() {{ return `${{this.name}} barks`; }}
}}
Symbol
Unique identifier: const id = Symbol('id')
Generators
function* gen(){{ yield 1; yield 2; }}
WeakMap
Like Map but keys are weakly referenced โ€” good for private data.
07 Async / Promises โ–ผ
Promises & Async/Await
JSAsync patterns
// Promise
const p = new Promise((resolve, reject) => {{
  setTimeout(() => resolve('done'), 1000);
}});
p.then(val => console.log(val)).catch(err => console.error(err));

// Async/Await (cleaner)
async function fetchData(url) {{
  try {{
    const res = await fetch(url);
    const data = await res.json();
    return data;
  }} catch (err) {{
    console.error('Error:', err);
  }}
}}

// Run in parallel
const [a, b] = await Promise.all([fetchA(), fetchB()]);
๐Ÿ’ก
Always use async/await with try/catch. For parallel tasks, use Promise.all().
08 Error Handling โ–ผ
Error Types & Handling
JSError handling
try {{
  const result = riskyOperation();
}} catch (err) {{
  if (err instanceof TypeError) {{ console.log('Type error'); }}
  else if (err instanceof RangeError) {{ console.log('Range error'); }}
  console.log(err.message, err.stack);
}} finally {{
  cleanup(); // always runs
}}

// Custom error
class ValidationError extends Error {{
  constructor(msg) {{ super(msg); this.name = 'ValidationError'; }}
}}
throw new ValidationError('Invalid email');
SyntaxError
Invalid code syntax โ€” caught at parse time
TypeError
Wrong type used: calling non-function, accessing null property
RangeError
Value out of range: new Array(-1)
ReferenceError
Accessing undeclared variable
09 Useful Methods โ–ผ
String Methods
JSString manipulation
const s = '  Hello World  ';
s.trim()                    // 'Hello World'
s.toLowerCase()            // '  hello world  '
s.includes('World')         // true
s.replace('World','JS')     // '  Hello JS  '
s.split(' ')               // array of words
s.slice(2, 7)               // 'Hello'
s.padStart(10, '0')         // '0000  Hello World  '
'ha'.repeat(3)              // 'hahaha'
'a,b,c'.split(',').join('|') // 'a|b|c'
Regex
/pattern/flags. 'hello'.match(/l+/)โ†’['ll']
JSON
JSON.stringify(obj) / JSON.parse(str)
Math
Math.max/min/round/floor/ceil/random/abs/pow/sqrt
Date
new Date(), .getFullYear(), .toISOString()
10 Mini Quizzes โ–ผ
โ“ Quiz 1
What does typeof null return?
A known JS quirk! typeof null returns 'object' โ€” a bug from the early days that was never fixed for backward compatibility.
โ“ Quiz 2
Which array method does NOT mutate the original array?
map() returns a new array. push(), splice(), and sort() all mutate the original array in place.
โ“ Quiz 3
What is the output of: console.log(1 + '2' + 3)?
1 + '2' โ†’ '12' (number coerced to string), then '12' + 3 โ†’ '123'. JS evaluates left to right.
โ“ Quiz 4
What does const arr = []; arr.push(1,2,3); console.log(arr.length) log?
const prevents reassignment of the variable, NOT mutation of the array. push() adds 3 items โ†’ length is 3.