LearnFrenzy
Sign in Take a free test

JavaScript interview · Set 1 of 10

JavaScript Core Concepts

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

Concepts behind “what does this print?”

Output questions test scope, hoisting, closures and this. Explain the rule behind each answer and interviewers will trust you with real code.

  • Scopevar, let, const and hoisting.
  • FunctionsClosures, this and bind.
  • ObjectsPrototypes, classes and modern syntax.

Front-end and full-stack interviews love “what does this code print?” questions. They are not trick questions — each one checks a single concept: scope, hoisting, closures or this. Understand the concept and you can answer any variation.

1. var, let and const — what is the difference?

var is function-scoped and hoisted with the value undefined. let and const are block-scoped and live in the temporal dead zone until their line runs, so using them earlier throws. const prevents reassignment, not mutation — a const array can still be pushed to.

console.log(a);   // undefined (var is hoisted)
var a = 1;

console.log(b);   // ReferenceError: cannot access 'b' before initialization
let b = 2;

const list = [];
list.push(1);     // fine — the binding is constant, not the array

2. What is a closure? Give a practical use.

A closure is a function that remembers the variables of the scope where it was created, even after that scope has finished. Closures power private state, function factories, memoisation and event handlers.

function createCounter() {
  let count = 0;                       // private
  return {
    increment: () => ++count,
    value: () => count,
  };
}
const c = createCounter();
c.increment(); c.increment();
console.log(c.value());               // 2

3. Why does this loop print 3, 3, 3 — and how do you fix it?

With var there is one i shared by all callbacks, and by the time they run the loop has finished. let creates a new binding per iteration.

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));   // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j));   // 0 1 2

4. How is the value of this decided?

It depends on how a function is called, not where it is written: a method call (obj.fn()) sets this to obj; a plain call gives undefined in strict mode; new sets it to the new object; call/apply/bind set it explicitly. Arrow functions have no own this — they use the surrounding one.

const user = {
  name: 'Asha',
  greet() { return `Hi ${this.name}`; },
  later() { setTimeout(() => console.log(this.name), 100); },   // arrow keeps this = user
};
const g = user.greet;
console.log(user.greet());   // Hi Asha
console.log(g());            // TypeError in strict mode: this is undefined

5. What is the difference between call, apply and bind?

All three set this. call invokes immediately with arguments listed; apply invokes immediately with arguments as an array; bind returns a new function with this fixed, to call later.

function intro(city, role) { return `${this.name}, ${role} from ${city}`; }
const p = { name: 'Ravi' };
intro.call(p, 'Pune', 'developer');
intro.apply(p, ['Pune', 'developer']);
const bound = intro.bind(p, 'Pune');
bound('tester');

6. How does prototypal inheritance work?

Every object has a hidden link ([[Prototype]]) to another object. When a property is not found on the object, JavaScript looks up the chain. class syntax is a cleaner way to set up the same prototype chain.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${this.name} barks`; }
}
const d = new Dog('Bruno');
console.log(Object.getPrototypeOf(d) === Dog.prototype);   // true

7. == vs === ?

=== compares value and type with no conversion. == converts types first, which gives surprises like 0 == '' being true. Use === everywhere; the one common exception is x == null, which checks for both null and undefined.


8. Which modern features should every JavaScript developer use?

Destructuring, spread and rest, template literals, optional chaining ?., nullish coalescing ??, arrow functions, modules (import/export), Array.prototype.at(), structuredClone() for deep copies, and immutable array helpers such as toSorted().

const { name, address: { city } = {} } = user;
const pin = order?.shipping?.pincode ?? 'Not set';
const merged = { ...defaults, ...settings };
const sorted = prices.toSorted((a, b) => a - b);   // original array unchanged

Remember

Key points

  • let in loops

    A new binding per iteration fixes closure bugs.

  • this depends on the call

    Arrow functions borrow the outer this.

  • Always ===

    Except x == null for null-or-undefined.

  • ?? is not ||

    ?? keeps 0 and empty strings; || does not.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 What is the temporal dead zone? Intermediate

    The time between entering a block and the line where a let/const is declared. Accessing the variable then throws a ReferenceError.

  2. 2 How do you deep-copy an object? Basic

    structuredClone(obj) copies nested data, dates, maps and sets. The spread operator only makes a shallow copy.

  3. 3 What is the difference between null and undefined? Basic

    undefined means “not assigned yet”; null is an intentional “no value”. typeof null is "object" — a historical bug.

  4. 4 What are WeakMap and WeakSet for? Advanced

    They hold object keys weakly, so entries disappear when the object is garbage-collected — useful for caching data about DOM nodes without leaking memory.

  5. 5 Implement a function that runs only once. Intermediate

    A closure remembers whether it already ran and the result.

    function once(fn) {
      let done = false, result;
      return (...args) => {
        if (!done) { done = true; result = fn(...args); }
        return result;
      };
    }

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links