JavaScript logoJavaScript BEGINNER

JavaScript

JavaScript fundamentals cheat sheet with ES6+ syntax, destructuring, modules, closures, scope, and modern best practices with examples.

12 min read
javascriptes6fundamentalsprogramming

Variables & Data Types

Understanding variables and primitive types

Variable Declaration

Different ways to declare variables

javascript
💡 Always prefer const by default, use let when reassignment is needed
⚡ const prevents reassignment but not mutation of objects/arrays
📌 Block scope means variables exist only within { }
🚫 Avoid var due to hoisting and function scope issues

Primitive Data Types

JavaScript primitive types

javascript
💡 JavaScript has 7 primitive types: string, number, boolean, undefined, null, symbol, bigint
⚡ Primitives are immutable - operations create new values
📌 Use null for intentional empty values, undefined for uninitialized
🔥 BigInt is for integers beyond Number.MAX_SAFE_INTEGER

Type Checking & Conversion

Checking and converting between types

javascript
💡 typeof null returns "object" - a known bug kept for compatibility
⚡ Use Array.isArray() to check for arrays, not typeof
📌 Prefer explicit conversion over implicit coercion
🔥 Falsy values: false, 0, "", null, undefined, NaN

Operators

All JavaScript operators

Arithmetic & Assignment

Math and assignment operators

javascript
💡 + operator concatenates strings but performs addition with numbers
⚡ Pre-increment (++x) returns new value, post-increment (x++) returns old
📌 Use ** for exponentiation instead of Math.pow()
🔥 Assignment operators provide shorthand for common operations

Comparison & Logical

Comparing values and logical operations

javascript
💡 Always use === and !== to avoid type coercion surprises
⚡ Logical operators use short-circuit evaluation
📌 && returns first falsy or last truthy, || returns first truthy or last falsy
🔥 ?? (nullish coalescing) only checks for null/undefined, not all falsy values

Ternary & Special Operators

Conditional and other special operators

javascript
💡 Ternary operator is great for simple conditions, avoid nesting
⚡ Optional chaining prevents "Cannot read property of undefined" errors
📌 Spread creates shallow copies, not deep copies
🔥 Comma operator evaluates all expressions, returns the last one

Control Flow

Controlling program execution

Conditional Statements

if, else, switch statements

javascript
💡 Always use braces {} even for single-line if statements
⚡ Switch uses strict equality (===) for comparisons
📌 Don't forget break in switch cases to prevent fall-through
🔥 Switch is cleaner than multiple if/else for many conditions

Loops

for, while, do-while, for...of, for...in, break, and continue

javascript
💡 for...of iterates VALUES (arrays, strings, Maps, Sets) — use for most loops
⚡ for...in iterates KEYS/properties (objects) — avoid on arrays, use for...of instead
📌 break exits the loop entirely; continue skips to the next iteration
🟢 for...of works on any iterable — arrays, strings, Maps, Sets, generators

Functions

Function declarations, expressions, and arrow functions

Function Declarations, Expressions & Arrows

Three ways to define functions — declarations, expressions, and arrow functions

javascript
💡 Arrow functions inherit "this" from the parent scope — perfect for callbacks and closures
⚡ Single-expression arrows have implicit return — no curly braces, no return keyword
📌 Don't use arrows for object methods or constructors — they have no own "this"
🟢 Declarations are hoisted; expressions and arrows are NOT — order matters

Parameters & Arguments

Function parameters, defaults, rest, spread

javascript
💡 Default parameters can reference previous parameters
⚡ Rest parameters must be the last parameter
📌 Spread operator expands arrays into individual arguments
🔥 Arrow functions don't have arguments object, use rest parameters

Scope & Closures

Understanding scope and closure behavior

javascript
💡 Functions create new scope, blocks create scope for let/const
⚡ Closures remember variables from outer scope even after function returns
📌 var is function-scoped, let/const are block-scoped
🔥 Closures are commonly used for data privacy and factory functions

Hoisting & Strict Mode

JavaScript hoisting behavior and strict mode

Hoisting

Variable and function hoisting behavior

javascript
💡 Function declarations are fully hoisted and can be called before declaration
⚡ var declarations are hoisted but initialized as undefined
📌 let/const are in "temporal dead zone" until declaration
🔥 Always declare variables at the top of their scope to avoid confusion

Strict Mode

Using strict mode for safer JavaScript

javascript
💡 Always use strict mode to catch common mistakes
⚡ Modules and classes are automatically in strict mode
📌 Strict mode must be first statement in script or function
🔥 Strict mode makes this undefined in regular functions

Objects & Arrays

Working with objects and arrays

Object Basics

Creating and manipulating objects

javascript
💡 Use dot notation for simple keys, brackets for dynamic/special keys
⚡ Object.assign and spread create shallow copies only
📌 in operator checks prototype chain, hasOwnProperty doesn't
🟢 See also: Array Methods sheet (map, filter, reduce) and String Methods sheet (split, slice, replace)

Map & Set

Key-value collections and unique value sets beyond plain objects and arrays

javascript
💡 Map accepts ANY key type (objects, functions, numbers) — Object only accepts strings/symbols
⚡ [...new Set(array)] is the fastest way to deduplicate an array
📌 Map preserves insertion order and has .size — Object needs Object.keys().length
🟢 Use Map for dynamic key-value data; use Object for structured data with known properties
mapsetcollections

Array Basics

Creating and manipulating arrays

javascript
💡 Use at() for negative indexing to access from end
⚡ push/pop are faster than unshift/shift
📌 splice mutates original, slice returns new array
🟢 See also: Array Methods sheet for map, filter, reduce, find, sort, and 20+ more methods

JSON

Parse and serialize data with JSON.parse() and JSON.stringify()

javascript
💡 JSON.stringify(obj, null, 2) pretty-prints with indentation — great for debugging
⚡ Use structuredClone() instead of JSON parse/stringify for deep cloning — handles Dates, Maps, Sets
📌 JSON cannot serialize undefined, functions, Symbols, or circular references
🟢 response.json() in fetch is a shorthand for JSON.parse(await response.text())
jsonparsestringify

The "this" Keyword

Understanding this binding in different contexts

this Binding Rules

How this is determined in different contexts

javascript
💡 Arrow functions don't have own this, they inherit from parent
⚡ In strict mode, this is undefined in regular functions
📌 Method borrowing loses this context
🔥 Event handlers set this to the element that triggered event

Explicit this Binding

Using call, apply, and bind

javascript
💡 call and apply invoke immediately, bind returns new function
⚡ Use call for known args, apply for array of args
📌 bind is commonly used to fix this in event handlers
🔥 Arrow functions are often simpler than bind for callbacks

Prototypes & Inheritance

JavaScript prototypal inheritance

Prototype Basics

Understanding the prototype chain

javascript
💡 Prototype chain: object -> prototype -> prototype -> null
⚡ Methods on prototype are shared, properties usually on instance
📌 Use Object.getPrototypeOf() instead of __proto__
🔥 instanceof checks entire prototype chain

Prototypal Inheritance

Implementing inheritance with prototypes

javascript
💡 Use Object.create() to set up prototype chain
⚡ Don't forget to reset constructor after changing prototype
📌 Call parent constructor with ParentConstructor.call(this)
🔥 Classes (ES6) provide cleaner syntax for same behavior

Classes

ES6 class syntax and inheritance

Class Basics

Creating and using classes

javascript
💡 Classes are syntactic sugar over prototypes
⚡ Class methods are non-enumerable by default
📌 Class declarations are not hoisted
🔥 Always use new with classes, calling without throws error

Class Inheritance

Extending classes with inheritance

javascript
💡 super() must be called before using this in constructor
⚡ Use super.method() to call parent methods
📌 Private fields start with # and are truly private
🔥 Static methods are inherited but not instance methods

Error Handling

Handling errors and exceptions

Try/Catch/Finally

Handling exceptions with try/catch

javascript
💡 finally block runs whether error occurs or not
⚡ Catch specific error types with instanceof
📌 Rethrow errors when you can't fully handle them
🟢 See also: Async JavaScript sheet for async error handling with try/catch + await

Throwing Errors

Creating and throwing custom errors

javascript
💡 Create custom error classes for specific error types
⚡ Include relevant data in custom errors for better debugging
📌 Error.cause helps chain errors with context
🔥 Always throw Error objects, not strings

Error Types

Common JavaScript error types

javascript
💡 Use specific error types for clearer error handling
⚡ TypeError is most common runtime error
📌 SyntaxError usually can't be caught (parse-time)
🔥 AggregateError useful for Promise.allSettled() results

Modern JavaScript (ES6+)

Modern JavaScript features

Spread & Rest Operators (...)

Expand iterables and collect remaining elements with the ... syntax

javascript
💡 Spread (...) expands; Rest (...) collects — same syntax, opposite operations
⚡ { ...obj } and [...arr] create SHALLOW copies — nested objects are still references
📌 const { password, ...safeUser } = user is the cleanest way to remove a property immutably
🟢 Rest params (...args) replace the old "arguments" object — they give a real array
spreadrestes6

Template Literals

String templates and tagged templates

javascript
💡 Template literals preserve whitespace and newlines
⚡ Use String.raw for paths and regex patterns
📌 Tagged templates can process and transform strings
🟢 See also: String Methods sheet for split, slice, replace, trim, and more

Destructuring

Extracting values from arrays and objects

javascript
💡 Use default values to handle undefined properties
⚡ Rest operator must be last in destructuring pattern
📌 Destructuring is shallow, not deep copying
🔥 Great for extracting multiple return values

Modules

ES6 module system

javascript
💡 Use named exports for utilities, default for main class/component
⚡ Dynamic imports enable code splitting and lazy loading
📌 Module code runs only once, regardless of imports
🔥 Modules are always in strict mode

Optional Chaining & Nullish Coalescing

Safe property access and default values

javascript
💡 ?. stops evaluation and returns undefined if null/undefined
⚡ ?? only replaces null/undefined, not other falsy values
📌 Use ?? for numeric values that could be 0
🔥 Combine ?. and ?? for safe access with defaults