Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

JavaScript Complete Guide: Core Concepts, Async JavaScript and the DOM

Learn JavaScript in depth: variables, types, functions, scope, closures, this, objects, arrays, the DOM, events, promises, async/await and the event loop, with clear examples.

jiocoder TeamUpdated Oct 7, 20267 min readJavaScript
JavaScript Complete Guide: Core Concepts, Async JavaScript and the DOM

JavaScript is the programming language of the web. HTML gives a page structure, CSS gives it style, and JavaScript makes it interactive. This guide walks through the core language, how JavaScript runs your code, and how to work with the DOM, events and asynchronous code.

Before you start

JavaScript changes HTML and CSS on the fly, so make sure you are comfortable with both. Our HTML guide and CSS guide cover what you need.

Variables: var, let and const#

Modern JavaScript uses const by default and let when a value must change. Avoid var in new code.

JavaScript
const name = "Asha";   // cannot be reassigned
let count = 0;         // can be reassigned
count = count + 1;

const user = { age: 21 };
user.age = 22;         // allowed: the object can change,
                       // only the binding is constant
  • var is function-scoped and is hoisted with the value undefined.
  • let and const are block-scoped ({ }). They are hoisted too, but sit in the temporal dead zone until their line runs, so using them early throws a ReferenceError.

Data types#

JavaScript has seven primitive types and one non-primitive type.

TypeExample
string"hello"
number42, 3.14, NaN
bigint9007199254740993n
booleantrue, false
undefinedA declared variable with no value
nullAn intentional "no value"
symbolSymbol("id"), a unique key
objectObjects, arrays, functions, dates, maps

Primitives are copied by value. Objects are copied by reference, so two variables can point to the same object.

JavaScript
const a = { score: 1 };
const b = a;      // same object
b.score = 5;
console.log(a.score); // 5

const c = { ...a };   // shallow copy
c.score = 9;
console.log(a.score); // still 5

Equality: == vs ===#

=== (strict equality) compares value and type. == converts types first, which leads to surprises like 0 == "" being true. Always use ===.

Truthy and falsy#

The falsy values are false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including [], {} and "0".

Functions#

JavaScript
// Function declaration: hoisted, usable before this line
function add(a, b) {
  return a + b;
}

// Function expression
const multiply = function (a, b) {
  return a * b;
};

// Arrow function: short, and no own "this"
const square = (n) => n * n;

// Default and rest parameters
function greet(name = "friend", ...others) {
  return `Hi ${name} and ${others.length} others`;
}

Functions are first-class values: you can store them in variables, pass them as arguments and return them from other functions. A function that takes or returns another function is a higher-order function; map, filter and setTimeout are examples.

Scope and closures#

Scope decides where a variable can be used. JavaScript has global scope, function scope and block scope. When code looks up a variable, it checks the current scope, then the outer one, and so on up the scope chain.

A closure is a function that remembers the variables of the scope where it was created, even after that outer function has returned.

JavaScript
function makeCounter() {
  let count = 0;            // private variable
  return function () {
    count++;
    return count;
  };
}

const counter = makeCounter();
counter(); // 1
counter(); // 2  (count is remembered)

Closures power data privacy, function factories, event handlers that remember values, and utilities like debounce and memoize.

The this keyword#

this depends on how a function is called, not where it is written.

Call styleValue of this
obj.method()obj
Plain call fn()undefined in strict mode (the global object otherwise)
new Fn()The new object
fn.call(x), fn.apply(x), fn.bind(x)x
Arrow functionInherits this from the surrounding scope

Objects and arrays#

Destructuring, spread and optional chaining#

JavaScript
const user = { name: "Ravi", city: "Pune", address: null };

const { name, city } = user;          // destructuring
const updated = { ...user, city: "Delhi" }; // spread copy
const pin = user.address?.pin;         // undefined, no error
const label = user.nickname ?? "Guest"; // fallback only for null/undefined

Essential array methods#

JavaScript
const prices = [120, 450, 80, 300];

prices.map((p) => p * 1.18);        // new array with tax
prices.filter((p) => p > 100);      // [120, 450, 300]
prices.reduce((sum, p) => sum + p, 0); // 950
prices.find((p) => p > 400);         // 450
prices.some((p) => p < 100);         // true
prices.toSorted((a, b) => a - b);    // sorted copy, original unchanged
Mutating vs non-mutating

push, pop, splice, sort and reverse change the original array. map, filter, slice, toSorted and toReversed return a new one. Frameworks like React rely on new arrays to detect changes.

Classes and prototypes#

Every object has a hidden link to a prototype object. When a property is missing, JavaScript looks it up the prototype chain. The class syntax is a cleaner way to write prototype-based code.

JavaScript
class Animal {
  #sound;                       // private field
  constructor(name, sound) {
    this.name = name;
    this.#sound = sound;
  }
  speak() {
    return `${this.name} says ${this.#sound}`;
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name, "woof");
  }
}

new Dog("Bruno").speak(); // "Bruno says woof"

How JavaScript runs your code#

JavaScript is single-threaded: it runs one piece of code at a time on the call stack. Slow work such as timers and network requests is handed to the browser's Web APIs. When that work finishes, its callback waits in a queue until the stack is empty. The event loop moves callbacks from the queues to the stack.

JavaScript event loop: call stack, Web APIs, microtask queue running before the task queue
  • Microtasks: promise callbacks (.then, code after await) and queueMicrotask. The whole microtask queue empties after each task.
  • Tasks (macrotasks): setTimeout, setInterval, user events. One runs per loop turn.
JavaScript
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");

// Output: 1, 4, 3, 2

Synchronous code runs first (1, 4), then microtasks (3), then the next task (2). This is one of the most common interview questions.

Asynchronous JavaScript#

From callbacks to promises#

Callbacks nested inside callbacks quickly become "callback hell". A Promise represents a value that will be available later.

JavaScript Promise states: pending, then fulfilled or rejected, handled with then, catch and finally

A promise starts pending and settles once, either fulfilled with a value or rejected with an error.

JavaScript
fetch("/api/products")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.error(err))
  .finally(() => console.log("done"));

async and await#

async/await is syntax on top of promises that reads like normal code. Use try...catch for errors, and check res.ok, because fetch only rejects on network failure, not on HTTP errors like 404.

JavaScript
async function loadProducts() {
  try {
    const res = await fetch("/api/products");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err) {
    console.error("Could not load products", err);
    return [];
  }
}

Running promises together#

MethodResolves when
Promise.allAll fulfil; rejects as soon as one rejects
Promise.allSettledAll settle; gives each result or error
Promise.raceThe first one settles
Promise.anyThe first one fulfils
JavaScript
const [user, orders] = await Promise.all([
  fetch("/api/user").then((r) => r.json()),
  fetch("/api/orders").then((r) => r.json()),
]);

The DOM#

The DOM (Document Object Model) is the browser's tree of objects built from your HTML. JavaScript reads and changes this tree to update the page.

JavaScript
const list = document.querySelector("#todo-list");
const item = document.createElement("li");
item.textContent = "Learn closures";   // safe: treated as text
item.classList.add("todo");
list.append(item);
Avoid innerHTML with user input

Setting innerHTML with text from users can run injected scripts (an XSS attack). Use textContent for text, and build elements with createElement.

Events#

JavaScript
const button = document.querySelector(".buy");
button.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("Clicked", event.target);
});

Capturing and bubbling#

JavaScript event propagation: capture phase down from window to the target, then bubble phase back up

An event travels in three phases: capture (from window down to the target), target, and bubble (back up to window). Listeners run in the bubble phase by default. event.stopPropagation() stops the journey.

Event delegation#

Instead of adding a listener to every item, add one to the parent and check event.target. It uses less memory and works for items added later.

JavaScript
list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (item) item.classList.toggle("done");
});

Modules#

ES modules split code into files with export and import. In the browser, load them with <script type="module">, which is deferred automatically.

JavaScript
// math.js
export const add = (a, b) => a + b;
export default function multiply(a, b) { return a * b; }

// app.js
import multiply, { add } from "./math.js";

Error handling and storage#

  • Use try...catch...finally around code that can fail, and throw new Error("message") for your own errors.
  • Store small data with localStorage.setItem("theme", "dark"). It only stores strings, so use JSON.stringify and JSON.parse for objects.

Best practices#

  • Use const by default, let when needed, never var.
  • Always use ===.
  • Prefer non-mutating array methods and small, pure functions.
  • Handle errors in every async function, and check res.ok after fetch.
  • Use event delegation for lists, and debounce search inputs and resize handlers.
  • Use a linter (ESLint) and a formatter (Prettier). Consider TypeScript for larger projects.
Next steps

Practise with our JavaScript interview questions for freshers, then move on to the React complete guide.

Key takeaways#

  • Use const and let; they are block-scoped and have a temporal dead zone.
  • Primitives copy by value; objects copy by reference.
  • A closure remembers variables from the scope where it was created.
  • this depends on how a function is called; arrow functions inherit it.
  • The event loop runs synchronous code, then all microtasks, then the next task.
  • Use async/await with try...catch, and event delegation for lists.