Skip to content
Laviyx Learn

Try

JavaScript Basics Cheat Sheet

Variables, types, strings, numbers, operators, conditions, loops, functions, errors, classes and modules at a glance.

Updated

Variables and types#

JavaScript
const name = "Asha";          // cannot be reassigned (use by default)
let count = 0;                // can be reassigned
// avoid var (function-scoped, hoisted as undefined)

typeof "hi";                  // "string"
typeof 42;                    // "number"
typeof true;                  // "boolean"
typeof undefined;             // "undefined"
typeof null;                  // "object" (historic quirk)
Array.isArray([1, 2]);        // true

Primitives: string, number, bigint, boolean, undefined, null, symbol. Everything else is an object.

Strings#

JavaScript
const s = "  Hello World  ";
`Hi ${name}, you have ${count + 1} messages`;   // template literal
s.trim(); s.toUpperCase(); s.toLowerCase();
s.includes("World"); s.startsWith("  H"); s.indexOf("o");
"asha@example.com".slice(0, 4);       // "asha"
"a,b,c".split(",");                   // ["a", "b", "c"]
["a", "b"].join(" | ");               // "a | b"
"tea".replace("t", "T"); "a-b-c".replaceAll("-", "+");
"7".padStart(3, "0");                 // "007"
"=".repeat(10);

Numbers and Math#

JavaScript
7 / 2;            // 3.5
7 % 2;            // 1 (remainder)
2 ** 10;          // 1024
0.1 + 0.2;        // 0.30000000000000004
(4.567).toFixed(2);              // "4.57" (a string)
Math.round(4.5); Math.floor(4.9); Math.ceil(4.1);
Math.max(3, 9, 4); Math.min(3, 9, 4);
Math.floor(Math.random() * 6) + 1;   // 1 to 6
Number("42"); parseInt("42px", 10); parseFloat("3.5kg");
Number.isNaN(Number("abc"));         // true
(1234567).toLocaleString("en-IN");   // "12,34,567"

Operators#

OperatorMeaning
===, !==Strict equality (always use these)
&&, ||, !And, or, not (short-circuit)
??Default only for null / undefined
?.Optional chaining: user?.address?.city
cond ? a : bTernary
+=, -=, ++, --Update

Falsy values: false, 0, -0, 0n, "", null, undefined, NaN.

Conditions and loops#

JavaScript
const marks = 82;
if (marks >= 90) {
  console.log("A");
} else if (marks >= 75) {
  console.log("B");
} else {
  console.log("C");
}

switch (new Date().getDay()) {
  case 0:
  case 6:
    console.log("Weekend");
    break;
  default:
    console.log("Weekday");
}

for (let i = 0; i < 3; i++) console.log(i);
for (const item of ["a", "b"]) console.log(item);       // values
for (const key in { x: 1, y: 2 }) console.log(key);     // object keys
let n = 3;
while (n > 0) n--;

Functions#

JavaScript
function add(a, b = 0) {             // default parameter
  return a + b;
}
const square = (n) => n * n;          // arrow function, implicit return
const sum = (...nums) => nums.reduce((t, n) => t + n, 0);   // rest parameters
const makeUser = (name, age) => ({ name, age });            // return an object

function counter() {                   // closure
  let c = 0;
  return () => ++c;
}

Errors#

JavaScript
try {
  JSON.parse("{bad json");
} catch (error) {
  console.log(error.name, error.message);
} finally {
  console.log("always runs");
}

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

Classes#

JavaScript
class Account {
  #balance = 0;                       // private field
  static bankName = "Laviyx Bank";    // static property

  constructor(owner) {
    this.owner = owner;
  }
  deposit(amount) {
    this.#balance += amount;
    return this;                      // allows chaining
  }
  get balance() {
    return this.#balance;
  }
}

class Savings extends Account {
  constructor(owner, rate) {
    super(owner);
    this.rate = rate;
  }
}

Modules#

JavaScript
// math.js
export const PI = 3.14159;
export function area(r) { return PI * r * r; }
export default class Circle {}

// main.js
// import Circle, { area, PI as pi } from "./math.js";
// const { readFile } = await import("node:fs/promises");

Want the full explanations? Go to the Learn JavaScript course →