Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

JavaScript Documentation

The language of the web — runs in every browser and, with Node.js, on servers too.

JavaScript (JS) is the programming language of the web. Every browser runs it to make pages interactive, and with Node.js it also runs on servers, in command-line tools and in desktop apps. It is dynamically typed, single-threaded and event-driven.

1. Introduction & Installation

You already have a JS engine — your browser. Press F12 → Console and type 2 + 2.

To run files on your computer, install Node.js (LTS) from nodejs.org:

node --version
node app.js
// app.js
console.log("Hello, Codify!");

Output:

Hello, Codify!

In a web page, add a script before </body>:

<script src="app.js"></script>

⚠️ Common error: ReferenceError: document is not defined — document and window exist only in the browser, not in Node.js.

2. Basic Syntax

  • Statements usually end with ; (optional, but recommended).
  • Blocks use { }; names are case-sensitive (myVar ≠ myvar).
  • Comments: // line and /* block */.
  • Use "use strict"; or ES modules to catch silent mistakes.
const name = "Asha";
let score = 90;
score += 5;
if (score > 90) {
  console.log(`${name} scored ${score} — excellent!`);   // template literal
}
console.log(typeof name, typeof score);

Output:

Asha scored 95 — excellent!
string number

⚠️ Common error: using a template literal with normal quotes — "Hi ${name}" prints literally. Use backticks: `Hi ${name}`.

3. Variables & Data Types

Declare with const (can't be reassigned — use by default) or let (can change). Avoid the old var (function-scoped, hoisted).

Primitive types: string, number (all numbers are 64-bit floats), bigint, boolean, undefined, null, symbol. Everything else is an object (arrays, functions, dates…).

const city = "Delhi";
let count = 10;
const price = 99.99;
const big = 2n ** 64n;
const isOpen = true;
let nothing;                 // undefined
const empty = null;
const user = { name: "Ravi", age: 22 };
const tags = ["js", "web"];

console.log(typeof count, typeof big, typeof nothing, typeof empty, Array.isArray(tags));
console.log(0.1 + 0.2, (0.1 + 0.2).toFixed(2), Number.MAX_SAFE_INTEGER);
console.log(Number("42") + 1, "5" + 3, "5" - 3, parseInt("12px"), String(7) + 7);

Output:

number bigint undefined object true
0.30000000000000004 0.30 9007199254740991
43 53 2 12 77

⚠️ Common error: TypeError: Assignment to constant variable. — you reassigned a const. Note: a const object's properties can still change.

4. Operators

Category Operators
Arithmetic + - * / % **
Comparison === !== (strict — use these), == != (loose, converts types), < > <= >=
Logical `&&
Nullish / optional ?? (default only for null/undefined), ?. (safe property access)
Assignment `= += -= *= /= ??=
Spread / rest ...
Others typeof, instanceof, in, ternary ?:
console.log(7 / 2, 7 % 2, 2 ** 10, Math.floor(7 / 2));
console.log(5 == "5", 5 === "5", null == undefined, null === undefined);
const settings = { theme: null, size: 0 };
console.log(settings.theme ?? "dark", settings.size || 12, settings.size ?? 12);
console.log(settings.user?.name, "theme" in settings);
const a = [1, 2], b = [...a, 3];
console.log(b, Math.max(...b));

Output:

3.5 1 1024 3
true false true false
dark 12 0
undefined true
[ 1, 2, 3 ] 3

⚠️ Common error: 0 || 10 gives 10 even though 0 is a valid value. Use ?? when only null/undefined should fall back.

5. Conditional Statements

const hour = 15;
let greeting;
if (hour < 12) greeting = "Good morning";
else if (hour < 18) greeting = "Good afternoon";
else greeting = "Good evening";
console.log(greeting);

const role = "editor";
switch (role) {
  case "admin":
    console.log("Full access");
    break;
  case "editor":
  case "author":
    console.log("Can write posts");
    break;
  default:
    console.log("Read only");
}

const age = 19;
console.log(age >= 18 ? "adult" : "minor");

Output:

Good afternoon
Can write posts
adult

Falsy values: false, 0, -0, 0n, "", null, undefined, NaN. Everything else (including [] and {}) is truthy.

⚠️ Common error: if (arr) is always true for arrays — check if (arr.length) instead.

6. Loops

for (let i = 0; i < 3; i++) console.log("i =", i);

const fruits = ["apple", "mango", "kiwi"];
for (const f of fruits) console.log(f);              // values of an iterable

const marks = { asha: 91, ravi: 78 };
for (const key in marks) console.log(key, marks[key]); // keys of an object

let n = 5, fact = 1;
while (n > 1) fact *= n--;
console.log("5! =", fact);

fruits.forEach((f, i) => console.log(i, f.toUpperCase()));

Output:

i = 0
i = 1
i = 2
apple
mango
kiwi
asha 91
ravi 78
5! = 120
0 APPLE
1 MANGO
2 KIWI

⚠️ Common error: using for...in on arrays — it iterates keys as strings (and inherited properties). Use for...of or array methods.

7. Functions

function add(a, b = 0) {                 // declaration (hoisted) + default param
  return a + b;
}
const multiply = function (a, b) {       // function expression
  return a * b;
};
const square = (x) => x * x;             // arrow function
const sum = (...nums) => nums.reduce((s, x) => s + x, 0);   // rest parameter

console.log(add(5), multiply(3, 4), square(9), sum(1, 2, 3, 4));

function makeCounter() {                 // closure: inner function remembers `count`
  let count = 0;
  return () => ++count;
}
const next = makeCounter();
next(); next();
console.log("counter:", next());

const apply = (fn, value) => fn(value);  // higher-order function
console.log(apply(square, 12));

Output:

5 12 81 10
counter: 3
144

⚠️ Common error: arrow functions don't have their own this. Don't use them as object methods that need this.

8. Arrays & Data Structures

const nums = [5, 3, 8, 1, 9, 2];
console.log(nums.length, nums[0], nums.at(-1), nums.indexOf(8), nums.includes(4));

const evens = nums.filter((n) => n % 2 === 0);
const doubled = nums.map((n) => n * 2);
const total = nums.reduce((s, n) => s + n, 0);
const sorted = [...nums].sort((a, b) => a - b);      // numeric sort, copy first
console.log(evens, doubled, total);
console.log(sorted, nums.find((n) => n > 5), nums.some((n) => n > 8), nums.every((n) => n > 0));
console.log(nums.slice(1, 3), [1, [2, [3]]].flat(Infinity), "a,b,c".split(","));

const user = { name: "Neha", skills: ["js", "react"], address: { city: "Pune" } };
const { name, address: { city } } = user;            // destructuring
const updated = { ...user, name: "Neha S." };        // spread copy
console.log(name, city, Object.keys(user), updated.name);

const visits = new Map();
visits.set("home", 3).set("docs", 5);
const unique = new Set([1, 2, 2, 3, 3]);
console.log(visits.get("docs"), visits.size, [...unique], unique.has(2));
console.log(JSON.stringify({ id: 1, ok: true }), JSON.parse('{"x":5}').x);

Output:

6 5 2 2 false
[ 8, 2 ] [ 10, 6, 16, 2, 18, 4 ] 28
[ 1, 2, 3, 5, 8, 9 ] 8 true true
[ 3, 8 ] [ 1, 2, 3 ] [ 'a', 'b', 'c' ]
Neha Pune [ 'name', 'skills', 'address' ] Neha S.
5 2 [ 1, 2, 3 ] true
{"id":1,"ok":true} 5

⚠️ Common error: [10, 9, 1].sort() gives [1, 10, 9] because the default sort compares strings. Pass a comparator: .sort((a, b) => a - b).

9. Object-Oriented Programming

JS uses prototypes; the class syntax (ES6) makes them easy to use.

class Animal {
  #sound;                                   // private field
  static count = 0;                         // static field

  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
    Animal.count++;
  }
  speak() {
    return `${this.name} says ${this.#sound}`;
  }
  get description() {                       // getter
    return `Animal: ${this.name}`;
  }
}

class Dog extends Animal {                  // inheritance
  constructor(name) {
    super(name, "woof");
  }
  speak() {                                 // override
    return super.speak() + "!";
  }
}

const pets = [new Animal("Cat", "meow"), new Dog("Bruno")];
pets.forEach((p) => console.log(p.speak()));
console.log(pets[1].description, Animal.count, pets[1] instanceof Animal);

Output:

Cat says meow
Bruno says woof!
Animal: Bruno 2 true

⚠️ Common error: losing this when passing a method as a callback (setTimeout(obj.method, 100)). Use an arrow wrapper () => obj.method() or .bind(obj).

10. Advanced Concepts

The event loop — JS runs one thing at a time. Slow work (timers, network, files) is handed off, and its callback runs later from the queue. Promise callbacks (microtasks) run before timer callbacks (macrotasks):

console.log("1 start");
setTimeout(() => console.log("4 timeout"), 0);
Promise.resolve().then(() => console.log("3 promise"));
console.log("2 end");
1 start
2 end
3 promise
4 timeout

Promises and async/await:

const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function main() {
  const a = await wait(100, "first");
  console.log(a);
  const [b, c] = await Promise.all([wait(50, "second"), wait(10, "third")]);
  console.log(b, c);
  try {
    await Promise.reject(new Error("network down"));
  } catch (err) {
    console.log("caught:", err.message);
  }
}
main();
first
second third
caught: network down

Fetch API (browser and Node 18+):

async function getUser(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const user = await res.json();
  return user.name;
}
getUser(1).then(console.log).catch(console.error);

DOM and events (browser):

<button id="btn">Clicked 0 times</button>
<script>
  const btn = document.querySelector("#btn");
  let clicks = 0;
  btn.addEventListener("click", () => {
    clicks++;
    btn.textContent = `Clicked ${clicks} times`;
  });
</script>

Modules split code into files:

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

// app.js
import area, { PI } from "./math.js";

Other topics: this rules, prototypes, generators, Symbol, WeakMap, error types, localStorage, and the difference between debounce and throttle.

⚠️ Common error: forgetting await — you get a Promise { <pending> } instead of the value. Every function using await must be async.

11. Examples with Output

Example 1 — Count character frequency

const text = "mississippi";
const freq = {};
for (const ch of text) freq[ch] = (freq[ch] || 0) + 1;
console.log(freq);
{ m: 1, i: 4, s: 4, p: 2 }

Example 2 — Debounce (run only after the user stops typing)

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}
const search = debounce((q) => console.log("searching", q), 50);
search("j"); search("ja"); search("jav"); search("java");
searching java

Example 3 — Group an array of objects

const students = [
  { name: "Asha", dept: "CSE" },
  { name: "Ravi", dept: "ECE" },
  { name: "Neha", dept: "CSE" },
];
const byDept = students.reduce((acc, s) => {
  (acc[s.dept] ||= []).push(s.name);
  return acc;
}, {});
console.log(byDept);
{ CSE: [ 'Asha', 'Neha' ], ECE: [ 'Ravi' ] }

12. Practice Problems

Solve on Codify (choose JavaScript; read input with require('fs').readFileSync(0, 'utf8')):

  1. Sum of Two Numbers — parsing input (Easy)
  2. Reverse a String — [...s].reverse().join('') (Easy)
  3. Check Palindrome (Easy)
  4. Two Sum — Map (Easy)
  5. Binary Search (Easy)
  6. Valid Parentheses — array as a stack (Medium)
  7. Maximum Subarray Sum (Medium)

Front-end practice: build a to-do list (add, delete, mark done, save in localStorage), a counter with a debounced search box, and a page that fetches and lists users from an API.

13. Interview Questions

1. var vs let vs const? var is function-scoped and hoisted (initialised as undefined); let/const are block-scoped and live in the "temporal dead zone" until declared. const can't be reassigned.

2. == vs ===? === compares value and type; == converts types first ("5" == 5 is true). Prefer ===.

3. What is a closure? A function plus the variables from the scope where it was created — it keeps access to them even after that outer function has returned.

4. What is hoisting? Declarations are processed before code runs: function declarations are fully hoisted, var is hoisted as undefined, let/const/class are hoisted but not initialised.

5. Explain the event loop. The call stack runs synchronous code; async callbacks wait in queues. When the stack is empty, all microtasks (promises) run, then the next macrotask (timers, I/O).

6. What is this? Depends on how a function is called: the object before the dot, undefined/global in plain calls, the new object with new, and lexical (outer) this in arrow functions.

7. Promise vs async/await? Both handle async results; async/await is syntax over promises that reads like synchronous code and uses try/catch for errors.

8. Shallow vs deep copy? {...obj} / Object.assign copy only the top level; structuredClone(obj) makes a deep copy.

9. What are map, filter and reduce? Array methods that return a transformed array, a subset, or a single accumulated value — without mutating the original.

10. What is event delegation? Attaching one listener to a parent and using event.target to handle events from many children — events bubble up.

14. Cheat Sheet & References

Variables and output

const x = 1; let y = 2;
console.log(`x is ${x}`); console.table([{ a: 1 }]);
typeof x; Array.isArray(arr); Number("5"); String(5);

Strings

s.length; s.toUpperCase(); s.trim(); s.includes("a");
s.split(","); s.slice(1, 4); s.replace(/a/g, "b"); s.padStart(3, "0");
[...s].reverse().join("");

Arrays

arr.push(x); arr.pop(); arr.unshift(x); arr.shift();
arr.map(f); arr.filter(f); arr.reduce((s, x) => s + x, 0);
arr.find(f); arr.findIndex(f); arr.some(f); arr.every(f);
arr.sort((a, b) => a - b); arr.slice(a, b); arr.splice(i, 1);
arr.includes(x); arr.indexOf(x); arr.flat(); Array.from({ length: n }, (_, i) => i);

Objects, Map, Set

const { a, b = 2 } = obj; const copy = { ...obj, c: 3 };
Object.keys(obj); Object.values(obj); Object.entries(obj);
const m = new Map(); m.set(k, v); m.get(k); m.has(k);
const s = new Set(arr); s.add(x); s.has(x); [...s];
JSON.stringify(obj); JSON.parse(str);

Functions and classes

const add = (a, b = 0) => a + b;
function sum(...nums) { return nums.reduce((s, x) => s + x, 0); }
class A extends B { #secret = 1; constructor() { super(); } static make() {} }

Async

const res = await fetch(url); const data = await res.json();
await Promise.all([p1, p2]);
setTimeout(fn, 1000); setInterval(fn, 1000); clearTimeout(id);
try { await risky(); } catch (e) { console.error(e.message); }

DOM

document.querySelector("#id"); document.querySelectorAll(".item");
el.textContent = "Hi"; el.classList.toggle("active"); el.style.color = "red";
el.addEventListener("click", (e) => e.preventDefault());
document.createElement("li"); parent.append(child); el.remove();
localStorage.setItem("k", "v"); localStorage.getItem("k");

Official documentation