JavaScript Cheatsheet

JavaScript Basics for Software Engineering

Use this JavaScript reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Variables

KeywordScopeReassignableRedeclarableHoisted
varfunctionyesyesyes (as undefined)
letblockyesnono (TDZ)
constblocknonono (TDZ)
var x = 1;        // function-scoped, avoid in modern code
let y = 2;        // block-scoped, reassignable
const z = 3;      // block-scoped, can't be reassigned

const obj = {};
obj.key = "value"; // ok — const prevents reassignment, not mutation

Temporal Dead Zone (TDZ): accessing let/const before declaration throws ReferenceError.

Data Types

Primitives — immutable, compared by value:

TypeExampletypeof result
Number42, 3.14, NaN, Infinity"number"
BigInt9007199254740991n"bigint"
String"hello", 'world', ` hi `"string"
Booleantrue, false"boolean"
undefinedundefined"undefined"
nullnull"object" (legacy quirk)
SymbolSymbol("id")"symbol"

Reference types — mutable, compared by reference:

typeof []           // "object"
typeof {}           // "object"
typeof function(){} // "function"
Array.isArray([])   // true  — use this to distinguish arrays

Type Checking

typeof 42          // "number"
typeof "hi"        // "string"
typeof true        // "boolean"
typeof undefined   // "undefined"
typeof null        // "object"   ← famous bug, not fixed for compat
typeof {}          // "object"
typeof []          // "object"
typeof Symbol()    // "symbol"
typeof 1n          // "bigint"
typeof function(){} // "function"

// Better checks
Array.isArray([])           // true
value === null              // exact null check
value == null               // null OR undefined
x instanceof RegExp         // prototype chain
Object.prototype.toString.call(x) // "[object Array]" etc.

Falsy Values

// Exactly eight falsy values:
false
0
-0
0n         // BigInt zero
""         // empty string (also '' and ``)
null
undefined
NaN

// Everything else is truthy — including:
Boolean({})   // true
Boolean([])   // true
Boolean("0")  // true
Boolean(-1)   // true

Type Conversion

// To Number
Number("42")        // 42
Number("")          // 0
Number(null)        // 0
Number(false)       // 0
Number(undefined)   // NaN
Number("abc")       // NaN
+"42"               // 42  (unary plus)
parseInt("42px")    // 42
parseInt("0xFF", 16)// 255
parseFloat("3.14x") // 3.14

// To String
String(42)          // "42"
String(null)        // "null"
String(undefined)   // "undefined"
(42).toString()     // "42"
(255).toString(16)  // "ff"
`${42}`             // "42"
42 + ""             // "42"

// To Boolean
Boolean(0)          // false
Boolean("")         // false
!!value             // double-NOT coerce

Numbers

42          // integer
3.14        // float
0xFF        // hex → 255
0b1010      // binary → 10
0o17        // octal → 15
1_000_000   // numeric separator (ES2021)
Infinity
-Infinity
NaN         // typeof NaN === "number"

Number.MAX_SAFE_INTEGER   // 9007199254740991
Number.MIN_SAFE_INTEGER   // -9007199254740991
Number.EPSILON            // 2.220446049250313e-16
Number.MAX_VALUE
Number.MIN_VALUE          // smallest positive

Number.isNaN(NaN)         // true  (no coercion — prefer over global isNaN)
Number.isFinite(Infinity) // false
Number.isInteger(4.0)     // true
Number.isSafeInteger(2**53) // false

(1234.5678).toFixed(2)     // "1234.57"
(1234.5678).toPrecision(6) // "1234.57"
(255).toString(16)         // "ff"
(255).toString(2)          // "11111111"

Math Object

Math.abs(-5)       // 5
Math.ceil(4.1)     // 5
Math.floor(4.9)    // 4
Math.round(4.5)    // 5
Math.trunc(4.9)    // 4   (truncates, no rounding)
Math.sign(-3)      // -1  (1, -1, or 0)
Math.max(1, 2, 3)  // 3
Math.min(1, 2, 3)  // 1
Math.pow(2, 8)     // 256
Math.sqrt(16)      // 4
Math.cbrt(27)      // 3
Math.log(Math.E)   // 1
Math.log2(8)       // 3
Math.log10(1000)   // 3
Math.random()      // [0, 1)
Math.hypot(3, 4)   // 5
Math.clamp          // doesn't exist — use Math.min(Math.max(val, min), max)
Math.PI            // 3.141592653589793
Math.E             // 2.718281828459045
Math.LN2           // 0.693...
Math.SQRT2         // 1.414...

// Random integer in [min, max] inclusive
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

Operators

Arithmetic & Assignment

5 + 2    // 7    5 - 2   // 3
5 * 2    // 10   5 / 2   // 2.5
5 % 2    // 1    5 ** 2  // 25  (ES2016)

x = 1   x += 1   x -= 1   x *= 2   x /= 2
x %= 2  x **= 2
x++  ++x  x--  --x

Comparison

===   !==   // strict (no coercion) — always prefer
==    !=    // loose (coerces — avoid)
<   >   <=  >=

Logical

&&   // AND — returns first falsy or last value
||   // OR  — returns first truthy or last value
!    // NOT
??   // nullish coalescing (ES2020): only null/undefined triggers right side

false && "x"     // false
true  && "x"     // "x"
false || "x"     // "x"
null  ?? "default" // "default"
0     ?? "default" // 0   (0 is not null/undefined)
0     || "default" // "default"  (0 is falsy)

Logical Assignment (ES2021)

a ||= b   // a = a || b
a &&= b   // a = a && b
a ??= b   // a = a ?? b

Other Operators

condition ? ifTrue : ifFalse   // ternary
typeof x                       // returns type string
x instanceof Y                 // prototype chain check
void 0                         // evaluates expr, returns undefined
delete obj.key                 // removes own property
in                             // "key" in obj

Optional Chaining (ES2020)

obj?.prop        // undefined if obj is null/undefined
obj?.method()    // undefined instead of error
arr?.[0]         // safe index
obj?.a?.b?.c     // deep chain
func?.()         // call only if func is not null/undefined

Bitwise

5 & 3    // 1   (AND)
5 | 3    // 7   (OR)
5 ^ 3    // 6   (XOR)
~5       // -6  (NOT)
5 << 1   // 10  (left shift)
5 >> 1   // 2   (signed right shift)
-5 >>> 1 // 2147483645 (unsigned right shift)

Equality Gotchas

NaN === NaN          // false  — NaN is not equal to itself
Number.isNaN(NaN)    // true   — the right check
Object.is(NaN, NaN)  // true   — strict identity
Object.is(0, -0)     // false  (=== considers them equal)

null == undefined    // true   (only loose equality)
null === undefined   // false

typeof null === "object"  // true — historical bug

Scoping and Hoisting

// var: declaration hoisted, initialized as undefined
console.log(a); // undefined (no error)
var a = 1;

// let/const: hoisted but in TDZ — accessing throws ReferenceError
console.log(b); // ReferenceError
let b = 1;

// Function declarations: fully hoisted
greet(); // works
function greet() { return "hi"; }

// Function expressions: not hoisted
sayHi(); // TypeError or ReferenceError
const sayHi = () => "hi";

// Block scope
{
  let x = 1;
  const y = 2;
  var z = 3; // leaks out
}
// x → ReferenceError, y → ReferenceError, z → 3

Symbols and BigInt

// Symbol — unique primitive, useful as non-colliding object keys
const id = Symbol("id");
const id2 = Symbol("id");
id === id2         // false — always unique
Symbol.for("app")  // global registry lookup/create
Symbol.keyFor(s)   // reverse lookup

const obj = { [id]: 42 };
obj[id]            // 42

// Well-known symbols
Symbol.iterator
Symbol.toPrimitive
Symbol.hasInstance

// BigInt — arbitrary-precision integers
const big = 9007199254740991n;
big + 1n           // 9007199254740992n
typeof big         // "bigint"
BigInt(42)         // 42n
// Cannot mix with Number
big + 1            // TypeError — use explicit conversion

Comments

// Single-line comment

/*
  Multi-line
  comment
*/

/**
 * JSDoc comment
 * @param {string} name - The name to greet
 * @param {number} [times=1] - How many times
 * @returns {string}
 */
function greet(name, times = 1) {
  return `Hello, ${name}! `.repeat(times);
}