Skip to content
JavaScript Reference & Cheatsheet — Quick API Lookup

JavaScript Reference & Cheatsheet — Quick API Lookup

DodaTech Updated Jun 6, 2026 8 min read

Quick reference for essential JavaScript syntax and built-in APIs. Use this page to look up syntax, methods, and operators when you’re coding.

What You’ll Learn

  • Console methods for debugging
  • Variable declarations and data types
  • All operators by category
  • String, array, number, Math, Date, Set, and Map methods
  • Promise states and module syntax
  • Common event types and type conversion
Prerequisites: This is a reference page, not a tutorial. You should already understand JavaScript before using this as a quick lookup.
  • Console, variable declarations, and data types
  • All operators by category
  • String, array, number, Math, and Date methods
  • Promise states and module syntax
  • Common event types and falsy values

Why a Reference Matters

Even experienced developers need quick lookups. This cheatsheet collects the most-used JavaScript APIs in one place — no scrolling through full tutorials. Bookmark this page for when you need to remember the exact method name or syntax.

Security note: Understanding Js Reference helps build more secure applications — a core principle at DodaTech, where tools like Durga Antivirus Pro and Doda Browser rely on solid implementation practices.

Console Methods

console.log('text');           // General output
console.error('text');         // Error output
console.warn('text');          // Warning output
console.info('text');          // Info output
console.debug('text');         // Debug output
console.table(array);          // Tabular display
console.time('label');         // Start timer
console.timeEnd('label');      // End timer
console.trace();               // Stack trace
console.group('label');        // Collapsible group
console.groupEnd();
console.count('label');        // Counter

Variable Declarations

varletconst
ScopeFunctionBlockBlock
ReassignableYesYesNo
HoistedYes (undefined)Yes (TDZ)Yes (TDZ)
RedeclarableYesNoNo

Primitive Data Types

string, number, boolean, null, undefined, symbol, bigint

Operators

Arithmetic

+, -, *, /, % (remainder), ** (exponentiation), ++ (increment), -- (decrement)

Assignment

=, +=, -=, *=, /=, %=, **=

Comparison (use strict always)

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

Logical

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

Special

... (spread/rest), ?. (optional chaining), delete, typeof, instanceof

String Methods

MethodReturnsExample
lengthnumber'hi'.length → 2
toUpperCase()string'hi'.toUpperCase() → ‘HI’
toLowerCase()string'HI'.toLowerCase() → ‘hi’
trim()string' hi '.trim() → ‘hi’
includes(s)boolean'hello'.includes('ell') → true
indexOf(s)number'hello'.indexOf('l') → 2
slice(s,e)string'hello'.slice(1,4) → ’ell'
split(d)array'a,b'.split(',') → [‘a’,‘b’]
replace(a,b)string'hi'.replace('i','ello') → ‘hello’
repeat(n)string'ha'.repeat(3) → ‘hahaha’
startsWith(s)boolean'hi'.startsWith('h') → true
endsWith(s)boolean'hi'.endsWith('i') → true

Array Methods

MethodReturnsMutates?
push(v)new lengthYes
pop()removed itemYes
shift()removed itemYes
unshift(v)new lengthYes
splice(i,n)removed itemsYes
slice(s,e)new arrayNo
concat(a)new arrayNo
indexOf(v)indexNo
includes(v)booleanNo
find(fn)item or undefinedNo
filter(fn)new arrayNo
map(fn)new arrayNo
reduce(fn, i)single valueNo
forEach(fn)undefinedNo
some(fn)booleanNo
every(fn)booleanNo
sort(fn)same arrayYes
reverse()same arrayYes
join(s)stringNo
flat(d)new arrayNo
flatMap(fn)new arrayNo

Number Properties & Methods

Number.MAX_VALUE          // ~1.79e+308
Number.MIN_VALUE          // 5e-324
Number.EPSILON            // ~2.22e-16
Number.POSITIVE_INFINITY  // Infinity
Number.NaN                // NaN

Number.isNaN(v)           // Check NaN
Number.isFinite(v)        // Check finite
Number.isInteger(v)       // Check integer
Number.parseInt(s)        // String → int
Number.parseFloat(s)      // String → float

n.toFixed(d)              // Fixed decimal places
n.toPrecision(p)          // Significant digits
n.toString(r)             // To string (radix 2-36)

Math Methods

Math.round(n)       // Nearest integer
Math.floor(n)       // Round down
Math.ceil(n)        // Round up
Math.trunc(n)       // Remove decimals
Math.abs(n)         // Absolute value
Math.max(...n)      // Largest
Math.min(...n)      // Smallest
Math.random()       // 0 to < 1
Math.pow(b, e)      // Exponent
Math.sqrt(n)        // Square root
Math.sign(n)        // -1, 0, or 1
Math.PI             // 3.14159...

Date Methods

new Date()              // Now
new Date(ms)            // From timestamp
new Date(y, m, d)       // Month 0-indexed!

d.getFullYear()         // 4-digit year
d.getMonth()            // 0-11
d.getDate()             // 1-31
d.getDay()              // 0 (Sun) - 6 (Sat)
d.getHours()            // 0-23
d.getMinutes()          // 0-59
d.getSeconds()          // 0-59
d.toISOString()         // '2024-01-15T...'
d.toLocaleDateString()  // Locale format
Date.now()              // Current ms timestamp

Promise States

pending → fulfilled (resolved)
pending → rejected
Promise.all(iterable)         // All resolve or first rejects
Promise.allSettled(iterable)  // Never rejects
Promise.race(iterable)        // First settled
Promise.any(iterable)         // First fulfilled

Set Methods

new Set([iterable])   // Create set
set.add(value)        // Add value
set.has(value)        // Check existence
set.delete(value)     // Remove value
set.clear()           // Remove all
set.size              // Number of values

Map Methods

new Map([iterable])   // Create map
map.set(key, value)   // Add entry
map.get(key)          // Get value
map.has(key)          // Check key
map.delete(key)       // Remove entry
map.clear()           // Remove all
map.size              // Number of entries

Common Event Types

click, dblclick, mouseenter, mouseleave
keydown, keyup
submit, change, input, focus, blur
load, DOMContentLoaded, resize, scroll

Falsy Values

false, 0, '' (empty string), null, undefined, NaN
// Everything else is truthy

Module Syntax

// Export
export const x = 1;
export function fn() {}
export default class {}
export { x as y };

// Import
import { x } from './module.js';
import * as mod from './module.js';
import def from './module.js';
import('./module.js').then(mod => {});

JSON Methods

JSON.parse(str)            // String → object
JSON.stringify(obj)        // Object → string
JSON.stringify(obj, null, 2)  // Pretty-print with 2-space indent

typeof Operator Results

ExpressionResult
typeof "hello""string"
typeof 42"number"
typeof true"boolean"
typeof undefined"undefined"
typeof null"object" (bug)
typeof Symbol()"symbol"
typeof 42n"bigint"
typeof function(){}"function"
typeof {}"object"
typeof []"object"

Type Conversion Cheatsheet

// To string
String(42)             // '42'
(42).toString()        // '42'
'' + 42                // '42'

// To number
Number('42')           // 42
+'42'                  // 42
parseInt('42px')       // 42
parseFloat('3.14em')   // 3.14

// To boolean
Boolean(0)             // false
Boolean('')            // false
Boolean(null)          // false
!!42                   // true
!!'hello'              // true

String Template Syntax

// Interpolation
`Hello, ${name}!`

// Multi-line
`Line 1
Line 2
Line 3`

// Expressions
`Total: ${price * (1 + tax)}`

// Tagged templates
fn`string ${value}`

Loop Types Reference

// For — known iterations
for (let i = 0; i < n; i++) { }

// For...of — iterable values
for (const item of array) { }

// For...in — object keys
for (const key in obj) { }

// While — unknown iterations
while (condition) { }

// Do-While — at least once
do { } while (condition);

Common Mistakes to Remember

  • Use === not == for comparison
  • Use const by default, let when needed, never var
  • Strings are immutable — methods return new strings
  • 0.1 + 0.2 !== 0.3 — floating point precision issue
  • Months are 0-indexed in new Date(year, month, day)
  • typeof null === 'object' — known JavaScript bug
  • Always wrap JSON.parse() in try/catch
  • Check response.ok when using fetch

Learning Path

    flowchart LR
  A[JavaScript Basics] --> B[Intermediate JS]
  B --> C[Advanced JS]
  C --> D[JavaScript Reference]
  D --> E[Frameworks & Tools]
  D --> F[You Are Here]
  

Practice Questions

  1. What does typeof null return? "object" — this is a known bug from JavaScript’s early days.

  2. What’s the difference between Array.map() and Array.filter()? map() transforms every element and returns a new array of the same length. filter() returns a subset of elements that pass a test.

  3. How do you deep-copy an object? structuredClone(obj) — handles circular references and special types. JSON.parse(JSON.stringify(obj)) is a common alternative but loses functions and special types.

  4. What does Promise.allSettled() do? Waits for all promises to settle (resolve or reject) and never rejects itself. Returns an array of result objects.

FAQ

How do I check if a value is an array?
Use Array.isArray(value). typeof [] returns 'object' which is not useful.
What is the best way to copy an array?
Use the spread operator: const copy = [...original]. Or original.slice().
How do I remove falsy values from an array?
arr.filter(Boolean) — removes false, 0, '', null, undefined, NaN.
What is the difference between setTimeout and setInterval?
setTimeout runs a function once after a delay. setInterval runs repeatedly at the specified interval.
How do I get the current timestamp?
Date.now() returns milliseconds since Jan 1, 1970. new Date().getTime() does the same.
What is the difference between event.target and event.currentTarget?
event.target is the element that triggered the event. event.currentTarget is the element the listener is attached to.

Try It Yourself

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JS Reference Playground</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 2rem; }
    pre { background: #f4f4f4; padding: 1rem; border-radius: 5px; }
  </style>
</head>
<body>
  <h1>JavaScript Reference Sandbox</h1>
  <pre id="output"></pre>
  <script>
    const out = document.getElementById('output');
    let result = 'Quick lookups:\n\n';

    // Type check
    result += `typeof 42 = ${typeof 42}\n`;
    result += `typeof "hi" = ${typeof "hi"}\n`;
    result += `Array.isArray([1,2]) = ${Array.isArray([1,2])}\n\n`;

    // Date
    const now = new Date();
    result += `Now: ${now.toLocaleString()}\n`;
    result += `Timestamp: ${Date.now()}\n\n`;

    // Array methods
    const nums = [5, 2, 8, 1, 9];
    result += `Array: [${nums}]\n`;
    result += `Sorted: [${nums.sort((a,b) => a-b)}]\n`;
    result += `Filtered (>5): [${nums.filter(n => n > 5)}]\n`;

    out.textContent = result;
  </script>
</body>
</html>

What’s Next

LessonDescription
JavaScript HomeBack to the JavaScript tutorials hub
https://tutorials.dodatech.com/programming-languages/javascript/js-basics/Start from the beginning
HTML ReferenceHTML elements and attributes
CSS ReferenceCSS properties and selectors
Node.jsJavaScript on the server

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

What’s Next

Congratulations on completing this Js Reference tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro