🎓 A1Learner
🔍

Home / Blog / Programming / JavaScript

Top 50 JavaScript Interview Questions with Answers

Programming · JavaScript · 23 min read

Fifty JavaScript interview questions with answers and programs run on Node.js: basics, scope, functions, objects, async, DOM, and ES6.

How this sheet works

Fifty JavaScript interview questions sit on this page, grouped by topic. The first group covers the basics. The middle groups cover variables, functions, objects, and arrays. The later groups cover async code, the page, and modern features. Seven short coding tasks finish the sheet.

Each program below ran on Node.js version 24, and the page shows the exact lines the run printed. No output here is invented. The three answers about the page use a small stand-in for the browser document, and the stand-in is printed inside the program so you can see exactly what ran.

Read one question at a time. Say your answer out loud before you read the one on the page. Then type the program out and run it yourself. Speaking an answer from memory shows what you know better than reading it does.

The JavaScript Beginner course here holds 55 lessons. Most answers name the lesson that teaches the idea, so a wrong answer points straight at what to study next. Six answers have no lesson behind them yet, and the page says so on each one.

Two honest limits. Closures, promises, async and await, the event loop, and destructuring get full answers here, but the JavaScript course has no lesson on any of them yet. Modules, prototypes, and fetch appear in neither the course nor this sheet, so questions on those will find no help here.

1. What is JavaScript, and what is it used for?

JavaScript is the language that makes a web page respond. HTML builds the page. CSS styles it. JavaScript adds the actions. A button that answers a click is JavaScript. A form that checks its own input is JavaScript. A list that updates without a reload is JavaScript.

It runs in every major browser, so no install is needed to try it. It also runs outside the browser, on servers, through Node.js. One language covers both sides of a web app.

The JavaScript Intro lesson opens the course with a first message in the console.

2. Where does JavaScript code go in a web page?

Inside a script element. The element sits in the page, usually near the end of the body. The browser runs the code inside it when the page loads.

A script element can also point at a separate file. The src attribute names the file, and the browser fetches it. Keeping code in its own file keeps the page tidy.

The JavaScript Intro lesson shows a first script running when the page loads.

console.log("The page loaded.");
console.log("The script ran.");

Output:
The page loaded.
The script ran.

3. How do you print a value in JavaScript?

With console.log. The call takes a value and prints it to the console. The console is the panel in the browser that shows messages from a script.

One call can print several values. The console joins them with spaces. Strings print as they are. Numbers print as they are. Objects print in a readable shape.

The JavaScript Output lesson works through console.log with more cases.

console.log("Score:", 42, "points");
console.log(true);
console.log({ name: "Ana" });

Output:
Score: 42 points
true
{ name: 'Ana' }

4. What is a statement, and what does a semicolon do?

A statement is one instruction. A program is a list of statements, and the browser runs them in order. Each statement tells the browser to do one thing.

A semicolon marks the end of a statement. Most statements end with one. JavaScript can guess where a statement ends without it, but the guess is not always right. Writing the semicolon keeps the meaning clear.

The JavaScript Statements lesson lists the kinds of statement a program holds.

let total = 2 + 3;
console.log(total);
let greeting = "Hi";
console.log(greeting);

Output:
5
Hi

5. What are the data types in JavaScript?

A data type names the kind of a value. JavaScript has seven basic kinds: string, number, bigint, boolean, undefined, symbol, and null. Objects and arrays sit on top of them.

typeof tells you the kind of a value. typeof "hi" gives string. typeof 42 gives number. typeof true gives boolean. Two traps: typeof null gives object, and typeof an array gives object too.

The JavaScript Data Types lesson lists every type with a short example.

console.log(typeof "hi");
console.log(typeof 42);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof null);
console.log(typeof []);

Output:
string
number
boolean
undefined
object
object

6. What is the difference between == and ===?

== checks the value and allows the types to differ. === checks the value and the type together. "5" == 5 is true. "5" === 5 is false.

The loose check converts types before it compares. That conversion causes surprises. 0 == false is true, and "" == false is true. The strict check never converts, so it never surprises you that way.

The JavaScript Comparisons lesson shows every test in the set.

console.log("5" == 5);
console.log("5" === 5);
console.log(0 == false);
console.log(0 === false);
console.log(null == undefined);
console.log(null === undefined);

Output:
true
false
true
false
true
false

7. What does + do when you mix strings and numbers?

It joins them into a string. "5" + 3 gives "53". 5 + "3" gives "53". The number turns into text first, and then the two texts join.

The other operators behave differently. "5" - 3 gives 2. "5" * 2 gives 10. Minus, times, and divide turn the string into a number first. Only + prefers joining.

The JavaScript Operators lesson works through each operator with its own cases.

console.log("5" + 3);
console.log(5 + "3");
console.log("5" - 3);
console.log("5" * 2);
console.log(1 + 2 + "3");

Output:
53
53
2
10
33

8. What is the difference between var, let, and const?

All three declare a variable. var is the old way. let is the new way for values that change. const is the new way for values that stay fixed.

let and const stay inside the block they are declared in. var leaks out of blocks and lives in the whole function. const also refuses reassignment: writing a new value into a const variable throws an error.

The JavaScript Let lesson and the JavaScript Const lesson cover the two modern words in full.

let count = 1;
count = 2;
console.log(count);
const limit = 10;
try {
  limit = 20;
} catch (err) {
  console.log(err.message);
}
var old = 3;
console.log(old);

Output:
2
Assignment to constant variable.
3

9. What is scope in JavaScript?

Scope is the reach of a name in a program. A variable declared inside a function lives in that function. A variable declared at the top level lives everywhere in the file.

Blocks have scope too. A let variable declared inside curly braces dies at the closing brace. Code outside the braces cannot see it. That rule keeps names from colliding.

The JavaScript Scope lesson shows global, function, and block scope side by side.

const outside = "top";
function show() {
  const inside = "middle";
  console.log(outside);
  console.log(inside);
}
show();
console.log(outside);

Output:
top
middle
top

10. What is hoisting?

Hoisting moves a declaration to the top of its scope before any code runs. A var declaration moves, but its value stays on its own line. Reading it before that line gives undefined, not an error.

let and const are hoisted too, but they sit in a dead zone until their line runs. Reading one early throws a ReferenceError. The variable exists, but it cannot be touched yet.

The JavaScript Scope lesson names hoisting as one of its scope rules.

console.log(lifted);
var lifted = "up";
try {
  console.log(early);
} catch (err) {
  console.log(err.name);
}
let early = "down";

Output:
undefined
ReferenceError

11. What is the difference between null and undefined?

undefined means no value was ever given. A variable declared without a value holds undefined. A missing object property reads as undefined too.

null means a value was given on purpose, and that value is empty. A programmer writes null to say: nothing is here yet, by design. Both mean empty, but only one is a choice.

The JavaScript Data Types lesson covers both empty values with its other types.

let empty;
console.log(empty);
console.log(typeof empty);
let chosen = null;
console.log(chosen);
console.log(typeof chosen);
console.log(empty == chosen);
console.log(empty === chosen);

Output:
undefined
undefined
null
object
true
false

12. How do you change a value from one type to another?

With a conversion call. Number("42") gives 42. String(42) gives "42". Boolean(0) gives false. Each call takes a value and hands back the same value in a new type.

Some conversions fail quietly. Number("hi") gives NaN, not an error. A short cut exists too: putting + in front of a string turns it into a number. +"42" gives 42.

The JavaScript Type Conversion lesson works through each conversion with more cases.

console.log(Number("42"));
console.log(String(42));
console.log(Boolean(0));
console.log(Boolean("hi"));
console.log(+"42");
console.log(Number("hi"));

Output:
42
42
false
true
42
NaN

13. What is NaN, and how do you test for it?

NaN stands for Not-a-Number. It is the result of a number operation that has no sensible answer. 0 divided by 0 gives NaN. Number("hi") gives NaN too.

NaN is strange: it is not equal to itself. NaN === NaN is false. So never test for it with ===. Use Number.isNaN, which answers true only for NaN itself.

The JavaScript Numbers lesson covers NaN with the other number values.

console.log(0 / 0);
console.log(NaN === NaN);
console.log(Number.isNaN(NaN));
console.log(Number.isNaN("hi"));
console.log(isNaN("hi"));

Output:
NaN
false
true
false
true

14. What is a function, and how do you call one?

A function is a named piece of code that runs when called. You define it once and call it as often as you like. Parameters carry values in. return hands a value back out.

A call is the function name followed by round brackets. The values inside the brackets become the parameters. A function without return hands back undefined.

The JavaScript Functions lesson builds several functions from scratch.

function add(a, b) {
  return a + b;
}
console.log(add(2, 3));
console.log(add(10, 20));
function greet(name) {
  console.log("Hello, " + name);
}
greet("Ana");

Output:
5
30
Hello, Ana

15. How does a function declaration differ from a function expression?

A declaration names the function at the start: function add() {}. An expression stores an anonymous function in a variable: const add = function () {}. Both make a callable function.

The difference is timing. A declaration is hoisted, so you can call it before its line. An expression is not hoisted, so calling it early throws an error. The variable exists, but it holds nothing yet.

The JavaScript Functions lesson shows both shapes and when each one fits.

console.log(double(4));
function double(n) {
  return n * 2;
}
const triple = function (n) {
  return n * 3;
};
console.log(triple(4));

Output:
8
12

16. What are arrow functions?

An arrow function is a short way to write a function. The shape is (a, b) => a + b. The arrow replaces the word function and the braces. A single expression is returned without the word return.

Arrows suit short callbacks. Passing (x) => x * 2 to map is shorter than writing a full function. For longer work, a named function stays easier to read.

The JavaScript Arrow Functions lesson works through arrows with more cases.

const square = (n) => n * n;
console.log(square(5));
const nums = [1, 2, 3];
console.log(nums.map((n) => n * 2));

Output:
25
[ 2, 4, 6 ]

17. What is a callback?

A callback is a function handed to another function. The other function calls it back when the time comes. forEach takes a callback and runs it once for every item.

Callbacks let one method serve many jobs. The same forEach runs a different callback for logging, for adding, or for filtering. The method handles the loop. The callback handles the item.

The JavaScript Array Iteration lesson introduces callbacks through forEach.

const nums = [1, 2, 3];
nums.forEach((n, i) => {
  console.log(i + ": " + n);
});

Output:
0: 1
1: 2
2: 3

18. What is a closure?

Some functions remember the variables around them. When a function is made inside another function, it keeps a link to the outer variables. Those variables stay alive as long as the inner function does.

The classic use is a counter. The outer function holds a count. The inner function adds one and hands the count back. Each call to the outer function makes a fresh count that no other code can touch.

The JavaScript course has no lesson on closures yet, so this answer stands on its own. The JavaScript Scope lesson covers the scope rules a closure relies on.

function makeCounter() {
  let count = 0;
  return function () {
    count = count + 1;
    return count;
  };
}
const next = makeCounter();
console.log(next());
console.log(next());
console.log(next());

Output:
1
2
3

19. What is recursion?

Recursion is a function that calls itself. Each call works on a smaller piece of the problem. A stop test ends the chain. Without the stop test, the calls never end.

Factorial is the classic case. 5! is 5 times 4!. 4! is 4 times 3!. The chain stops at 1, whose factorial is 1. Then the answers multiply back up the chain.

The JavaScript Recursion lesson works through factorial and a second example.

function factorial(n) {
  if (n <= 1) {
    return 1;
  }
  return n * factorial(n - 1);
}
console.log(factorial(5));
console.log(factorial(0));

Output:
120
1

20. What is an object, and how do you read its properties?

An object is a value that holds named values. Each name is a key. Each key holds one value. A person object can hold a name, an age, and a city under three keys.

Dot notation reads a value by its key: person.name. Bracket notation does the same with a string: person["name"]. Brackets suit keys that come from a variable.

The JavaScript Objects lesson builds objects with more keys and values.

const person = { name: "Ana", age: 9, city: "Oslo" };
console.log(person.name);
console.log(person["age"]);
const key = "city";
console.log(person[key]);

Output:
Ana
9
Oslo

21. How do you add, change, and delete a property?

Assign to add or change. person.country = "Norway" adds a country key. person.age = 10 changes the age. Assignment creates the key when it is missing and overwrites it when it is there.

delete removes a key. delete person.city takes the city key away. Reading it afterwards gives undefined. The rest of the object stays as it was.

The JavaScript Objects lesson shows the same three moves in context.

const person = { name: "Ana", age: 9 };
person.country = "Norway";
person.age = 10;
console.log(person);
delete person.age;
console.log(person);

Output:
{ name: 'Ana', age: 10, country: 'Norway' }
{ name: 'Ana', country: 'Norway' }

22. What does `this` mean inside a method?

A method is a function that lives in a property. Inside that method, this is the object before the dot in the call. user.fullName() runs fullName with this set to user.

That link lets a method read its own object. fullName builds a full name from this.first and this.last. A birthday method adds one to this.age. The same method on a different object reads that object instead.

The JavaScript Object Methods lesson works through this with two more methods.

const user = {
  first: "Mina",
  last: "Kaur",
  age: 30,
  fullName: function () {
    return this.first + " " + this.last;
  },
  birthday: function () {
    this.age = this.age + 1;
  },
};
console.log(user.fullName());
user.birthday();
console.log(user.age);

Output:
Mina Kaur
31

23. What is an array, and how do you read its items?

An array is a list of values in order. Each value sits at a numbered slot called an index. The first item is at index 0. The last item is at index length minus one.

Square brackets read an item by its index: fruits[0]. length tells how many items the array holds. Reading past the end gives undefined, not an error.

The JavaScript Arrays lesson builds lists with more items and indexes.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);
console.log(fruits[2]);
console.log(fruits.length);
console.log(fruits[5]);

Output:
apple
cherry
3
undefined

24. How do push, pop, shift, and unshift work?

push adds to the end. pop takes from the end. shift takes from the start. unshift adds to the start. All four change the array itself.

pop and shift hand back the item they removed. push and unshift hand back the new length. That return value is easy to forget, and interviewers like to ask about it.

The JavaScript Array Methods lesson works through all four moves with more cases.

const nums = [2, 3];
nums.push(4);
console.log(nums);
console.log(nums.pop());
console.log(nums);
nums.unshift(1);
console.log(nums);
console.log(nums.shift());

Output:
[ 2, 3, 4 ]
4
[ 2, 3 ]
[ 1, 2, 3 ]
1

25. What is the difference between map and forEach?

map builds a new array. It runs a callback on every item and collects the results. The old array stays untouched. forEach runs a callback on every item and builds nothing.

Use map when you want a changed copy. Use forEach when you want an effect, such as logging each item. Reaching for forEach to build a list is the common mistake: that job belongs to map.

The JavaScript Array Iteration lesson shows map and forEach side by side.

const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2);
console.log(doubled);
console.log(nums);
nums.forEach((n) => console.log(n + "!"));

Output:
[ 2, 4, 6 ]
[ 1, 2, 3 ]
1!
2!
3!

26. How do you find and filter items in an array?

find returns the first item that passes a test. filter returns every item that passes, in a new array. includes answers true or false for one value. indexOf gives the position of a value, or -1 when it is missing.

All four take a test or a value and leave the array alone. filter never changes the old array. It builds a fresh one with the matches only.

The JavaScript Array Search lesson covers find, filter, and the rest of the search methods.

const nums = [5, 12, 8, 20];
console.log(nums.find((n) => n > 10));
console.log(nums.filter((n) => n > 10));
console.log(nums.includes(8));
console.log(nums.indexOf(20));

Output:
12
[ 12, 20 ]
true
3

27. How do you sort an array of numbers?

With a compare function. sort on its own turns items into strings and orders those. [10, 9, 80] sorts to [10, 80, 9]. That surprises everyone once.

A compare function takes two items and returns a number. A negative result puts the first item first. (a, b) => a - b sorts numbers from small to large. (a, b) => b - a flips the order.

The JavaScript Array Sort lesson works through the compare function with more cases.

const nums = [10, 9, 80];
console.log([...nums].sort());
console.log([...nums].sort((a, b) => a - b));
console.log([...nums].sort((a, b) => b - a));

Output:
[ 10, 80, 9 ]
[ 9, 10, 80 ]
[ 80, 10, 9 ]

28. What does setTimeout do?

setTimeout runs a function once, after a delay. The delay is in milliseconds. setTimeout(() => console.log("later"), 1000) prints after one second.

The delay is a minimum, not a promise of exact timing. The function waits in line behind code that is already running. It runs when the line reaches it.

The JavaScript Timeouts lesson shows setTimeout with a real delay and a second example.

console.log("first");
setTimeout(() => console.log("third"), 0);
console.log("second");

Output:
first
second
third

29. What does setInterval do, and how do you stop it?

setInterval runs a function again and again, once per delay. It keeps going until stopped. clearInterval stops it. The interval call hands back an id, and clearInterval takes that id.

Always keep the id. Without it, the interval runs forever. The classic shape is a count that clears its own interval when it reaches a limit.

The JavaScript Timeouts lesson covers setInterval next to setTimeout.

let ticks = 0;
const id = setInterval(() => {
  ticks = ticks + 1;
  console.log("tick " + ticks);
  if (ticks === 3) {
    clearInterval(id);
    console.log("stopped");
  }
}, 10);

Output:
tick 1
tick 2
tick 3
stopped

30. What is a promise?

A promise is a value that stands for a result that is not ready yet. It starts pending. It ends fulfilled with a value, or rejected with a reason. The code that waits does not block the rest of the program.

then runs a function when the promise fulfils. The function receives the value. catch runs a function when the promise rejects. Chaining then calls lets each step feed the next.

The JavaScript course has no lesson on promises yet, so this answer stands on its own. The JavaScript Timeouts lesson covers the delay a promise often wraps.

const done = Promise.resolve(42);
done.then((value) => console.log("got " + value));
console.log("waiting");

Output:
waiting
got 42

31. What do async and await do?

async marks a function that works with promises. The function always returns a promise. await pauses that function until a promise settles, then hands back its value.

await only works inside an async function. The pause is local: the rest of the program keeps running. The code reads like a straight list of steps, with no callback nesting.

The JavaScript course has no lesson on async and await yet, so this answer stands on its own. The JavaScript Functions lesson covers the plain functions they build on.

async function getAnswer() {
  const value = await Promise.resolve(7);
  return value * 2;
}
getAnswer().then((v) => console.log(v));
console.log("asked");

Output:
asked
14

32. What happens when a promise fails?

A rejected promise skips its then steps and looks for a catch. catch takes the reason and handles it. Without a catch, the failure is unhandled, and Node prints a warning.

Inside an async function, await throws the rejection like an ordinary error. A try block around the await catches it. That shape keeps failure handling in one place.

The JavaScript course has no lesson on promise failure yet, so this answer stands on its own. The JavaScript Errors lesson covers try and catch for plain errors.

async function risky() {
  try {
    await Promise.reject(new Error("boom"));
  } catch (err) {
    console.log("caught: " + err.message);
  }
}
risky();
Promise.reject(new Error("late")).catch((err) =>
  console.log("caught late: " + err.message)
);

Output:
caught: boom
caught late: late

33. What is the event loop?

The event loop is the rule that decides what runs next. JavaScript runs one thing at a time. When a task finishes, the loop picks the next one from the queues. Promise callbacks wait in one queue. Timers wait in another.

Promise callbacks always run before timers. That order is the whole interview point. A promise made now beats a timer set for now, even a timer set for zero milliseconds.

The JavaScript course has no lesson on the event loop yet, so this answer stands on its own. The JavaScript Timeouts lesson covers the timers the loop schedules.

console.log("one");
setTimeout(() => console.log("four"), 0);
Promise.resolve().then(() => console.log("three"));
console.log("two");

Output:
one
two
three
four

34. What is the DOM?

The DOM is the browser's model of a page. It turns the HTML into a tree of objects. Each element becomes an object with properties. Scripts read and change those objects, and the page updates.

document is the entry point. document.getElementById finds one element by its id. The object it hands back has the element's text, its styles, and its children.

The JavaScript DOM Intro lesson introduces the document tree with its first example.

// Node has no document, so this small stand-in plays its part.
// A browser gives you the real one. The lines after it are the page code.
const document = {
  elements: { demo: { textContent: "Old text" } },
  getElementById(id) {
    return this.elements[id];
  },
};
const el = document.getElementById("demo");
console.log(el.textContent);
el.textContent = "New text";
console.log(el.textContent);

Output:
Old text
New text

35. How do you find an element on a page?

By id, by class, or by a selector. getElementById takes an id and hands back one element. querySelector takes a CSS selector and hands back the first match. querySelectorAll hands back every match.

An id is unique, so getElementById is the fastest pick for one element. A class or a tag name suits groups. querySelector covers the rest, with any selector CSS allows.

The JavaScript DOM Methods lesson covers the lookup methods with more selectors.

// Node has no document, so this small stand-in plays its part.
// A browser gives you the real one. The lines after it are the page code.
const document = {
  elements: [
    { id: "demo", tag: "p", textContent: "First" },
    { id: "note", tag: "p", textContent: "Second" },
  ],
  getElementById(id) {
    return this.elements.find((el) => el.id === id);
  },
  querySelector(sel) {
    return this.elements.find((el) => el.tag === sel);
  },
};
console.log(document.getElementById("note").textContent);
console.log(document.querySelector("p").textContent);

Output:
Second
First

36. How do you change the text and style of an element?

textContent sets the text inside an element. Writing to it replaces what was there. The style property sets CSS, one property at a time: el.style.color = "red" colours the text.

Both changes show at once. The browser redraws the element with its new text and style. Nothing else on the page moves unless the change shifts the layout.

The JavaScript DOM Styles lesson changes text and styles on a real page.

// Node has no document, so this small stand-in plays its part.
// A browser gives you the real one. The lines after it are the page code.
const document = {
  elements: { demo: { textContent: "Old text", style: {} } },
  getElementById(id) {
    return this.elements[id];
  },
};
const el = document.getElementById("demo");
el.textContent = "New text";
el.style.color = "red";
console.log(el.textContent);
console.log(el.style.color);

Output:
New text
red

37. How do you run code when a button is clicked?

With a listener. addEventListener takes an event name and a function. The browser calls the function when the event happens. The page code never polls or waits in a loop.

The listener stays attached until removed. One element can hold several listeners for the same event. Each one runs in the order it was added.

The JavaScript DOM Events lesson wires a click listener to a real button.

const button = new EventTarget();
button.addEventListener("click", () => console.log("first listener"));
button.addEventListener("click", () => console.log("second listener"));
button.dispatchEvent(new Event("click"));
console.log("done");

Output:
first listener
second listener
done

38. What is the difference between addEventListener and onclick?

addEventListener stacks listeners. Two listeners on one element both run. onclick holds one function. Assigning a second one replaces the first.

addEventListener also takes options, such as once, which removes the listener after one run. onclick has no options. Modern code uses addEventListener for both reasons.

The JavaScript DOM Events lesson covers both ways of wiring a handler.

const button = new EventTarget();
button.addEventListener("click", () => console.log("listener one"));
button.addEventListener("click", () => console.log("listener two"));
button.onclick = () => console.log("handler one");
button.onclick = () => console.log("handler two");
button.dispatchEvent(new Event("click"));
button.onclick();

Output:
listener one
listener two
handler two

39. What are template literals?

Template literals are strings written with backticks. They allow placeholders inside the text: `Hello, ${name}` puts the name into the greeting. The placeholder can hold any expression.

They also span lines. A normal string cannot hold a line break without an escape. A template literal keeps the break as it is, which suits multi-line text.

The JavaScript Template Strings lesson builds greetings with more placeholders.

const name = "Ana";
const age = 9;
console.log(`Hello, ${name}. You are ${age}.`);
console.log(`Next year: ${age + 1}`);

Output:
Hello, Ana. You are 9.
Next year: 10

40. What does the spread operator do?

Spread unpacks a value. ...nums in a call spreads an array into separate arguments. [...a, ...b] joins two arrays into one. {...obj} copies an object.

The copy is shallow. Top-level properties are fresh, but nested objects are still shared. Changing a nested value through the copy changes the original too.

The JavaScript Spread lesson unpacks arrays and objects with more cases.

const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b]);
const user = { name: "Ana", age: 9 };
const copy = { ...user, age: 10 };
console.log(copy);
console.log(user);

Output:
[ 1, 2, 3, 4 ]
{ name: 'Ana', age: 10 }
{ name: 'Ana', age: 9 }

41. What is destructuring?

Destructuring unpacks values into variables in one move. const { name, age } = person pulls two properties out at once. const [first, second] = pair pulls two array items out.

It shines in function parameters. A function can take { name } and use the property straight away, with no dot in the body. Default values cover missing keys: const { city = "Oslo" } = person.

The JavaScript course has no lesson on destructuring yet, so this answer stands on its own. The JavaScript Spread lesson covers the unpacking operator it pairs with.

const person = { name: "Ana", age: 9 };
const { name, age } = person;
console.log(name);
console.log(age);
const pair = [1, 2];
const [first, second] = pair;
console.log(first + second);

Output:
Ana
9
3

42. What are Sets and Maps?

A Set holds unique values. Adding a value twice keeps one copy. A Map holds key-value pairs, and the key can be any value, not just a string.

Sets suit dedup and membership tests. Maps suit lookups where the key is an object or a number. Plain objects only take string keys, so a number key on an object becomes a string.

The JavaScript Sets lesson and the JavaScript Maps lesson cover each one in full.

const seen = new Set([1, 2, 2, 3]);
console.log(seen.size);
console.log(seen.has(2));
const ages = new Map();
ages.set("Ana", 9);
console.log(ages.get("Ana"));

Output:
3
true
9

43. What are classes, and what does inheritance add?

A class is a template for objects. It holds the data the objects share and the methods they share. new User("Ana") builds one object from the template. The constructor sets the first values.

Inheritance lets one class build on another. class Admin extends User takes everything User has and adds its own methods. super calls the parent constructor from the child one.

The JavaScript Classes lesson builds a first class, and the JavaScript Class Inheritance lesson extends it.

class User {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return "Hi, " + this.name;
  }
}
class Admin extends User {
  greet() {
    return super.greet() + " (admin)";
  }
}
const a = new Admin("Ana");
console.log(a.greet());

Output:
Hi, Ana (admin)

44. Write a program that reverses a string.

Split the string into characters, reverse the list, and join it back. split("") turns "abc" into ["a", "b", "c"]. reverse flips the list. join("") glues it back into a string.

Strings cannot change in place, so the round trip through an array is the standard move. The same three calls reverse any short string.

The JavaScript String Methods lesson covers split and join with more cases.

function reverse(s) {
  return s.split("").reverse().join("");
}
console.log(reverse("hello"));
console.log(reverse("racecar"));

Output:
olleh
racecar

45. Write a program that finds the largest number in an array.

Walk the array and keep the biggest value seen so far. Start with the first item. Each later item replaces the keeper when it is bigger. The keeper at the end is the largest.

Math.max with spread does the same in one line. Math.max(...nums) spreads the array into arguments and returns the biggest. The loop is the version to explain in an interview.

The JavaScript Array Methods lesson and the JavaScript For Of lesson cover the two moves used here.

const nums = [4, 9, 2, 15, 7];
let biggest = nums[0];
for (const n of nums) {
  if (n > biggest) {
    biggest = n;
  }
}
console.log(biggest);
console.log(Math.max(...nums));

Output:
15
15

46. Write a program that counts how many times each word appears.

Split the text into words, then count with an object. Each word becomes a key. The first sight sets its count to 1. Each later sight adds one.

The object ends up holding every word and its count. Object.entries turns it into pairs for printing. Sorting the pairs by count shows the most common word first.

The JavaScript Objects lesson builds counting objects with more keys.

const text = "red fish blue fish red fish";
const counts = {};
for (const word of text.split(" ")) {
  counts[word] = (counts[word] || 0) + 1;
}
console.log(counts);

Output:
{ red: 2, fish: 3, blue: 1 }

47. Write a program that removes duplicates from an array.

Put the array into a Set. A Set keeps one copy of each value. Spread the Set back into an array, and the duplicates are gone.

The order survives. A Set keeps values in the order they first appeared. The result holds each value once, in its first position.

The JavaScript Sets lesson shows the same dedup move with more values.

const nums = [1, 2, 2, 3, 1, 4];
console.log([...new Set(nums)]);

Output:
[ 1, 2, 3, 4 ]

48. Write a program that checks whether a word is a palindrome.

A palindrome reads the same backwards as forwards. Reverse the word and compare it with the original. Equal means palindrome. Different means it is not.

Lowercase the word first when case should not matter. "Racecar" reversed is "racecaR", which looks different until both sides are lowered.

The JavaScript String Methods lesson covers the lowercasing and splitting used here.

function isPalindrome(word) {
  const lower = word.toLowerCase();
  return lower === lower.split("").reverse().join("");
}
console.log(isPalindrome("racecar"));
console.log(isPalindrome("Racecar"));
console.log(isPalindrome("hello"));

Output:
true
true
false

49. Write a program that prints the Fibonacci sequence.

Each Fibonacci number is the sum of the two before it. The sequence starts 0, 1. Then 1, 2, 3, 5, 8, and so on. A loop keeps the last two numbers and adds them.

The loop runs once per number after the first two. Each pass prints the next number, then shifts the pair forward. Ten numbers need eight passes after the starting pair.

The JavaScript For Loop lesson builds the same counting loop with more cases.

const fib = [0, 1];
for (let i = 2; i < 10; i++) {
  fib.push(fib[i - 1] + fib[i - 2]);
}
console.log(fib.join(", "));

Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

50. Write a debounce function.

Debounce waits for quiet. Each call cancels the last timer and starts a fresh one. The work runs only after the calls stop for the full delay. Fast repeated calls produce one run.

Search boxes use it. Each keystroke restarts the wait. The search runs only when the user pauses typing. The shape is a closure around one timer id.

The JavaScript Timeouts lesson covers the timer that debounce resets.

function debounce(fn, delay) {
  let id;
  return function (...args) {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), delay);
  };
}
const save = debounce((text) => console.log("saved: " + text), 50);
save("a");
save("ab");
save("abc");
setTimeout(() => console.log("done"), 100);

Output:
saved: abc
done

Questions readers ask

How should I use this sheet over one week?

Take one group a day, in order. Read the question, answer it aloud, then read the page answer. Run every program yourself. Spend the last two days on the coding tasks and the questions you missed. A little each day beats cramming it all into one night.

Must I memorise all fifty answers?

Not all of them. A few patterns carry the whole sheet: scope, the difference between a value and a reference, how arrays change, and the order async code runs in. Most questions here dress one of those patterns up in new words. If you can explain scope, sort an array, and trace a promise, you can work out the rest from those.

Which JavaScript version should I practise with?

Modern JavaScript as Node.js 24 runs it. Each one ran on that version. Older versions change little at this level, so the current one is the safe pick for interviews today.

What does this sheet leave out?

Modules, prototypes, and fetch. The JavaScript course covers none of those three yet, so this sheet leaves them out. Closures, promises, async and await, the event loop, and destructuring get full answers here, although the course teaches none of them yet. Each remaining answer here points at a lesson on this site.