Programming & Web Development

JavaScript Interview Questions for Freshers: 15 Answers With Code

Fifteen JavaScript interview questions that freshers in Pakistan face most often, each with a short model answer and code you can test. Includes four predict-the-output puzzles, a way to handle questions you can't answer, current salary data and a 30-minute mock interview plan.

JavaScript interview questions for freshers poster with a code editor and question bubble

Quick answer

Most JavaScript interview questions for freshers cover a small set of topics: var, let and const, equality, closures, the this keyword, array methods, promises, async/await and the event loop. Prepare a one-line definition, a short code example and a real use for each, then practice predicting the output of small snippets.

Key takeaways

  • • Fifteen questions cover most fresher rounds: scope, equality, functions, arrays and async code.
  • • Answer each in three parts: a definition, a tiny code example and where it matters in a project.
  • • Promise callbacks run before setTimeout callbacks, even when the timer delay is zero.
  • • Use === by default; MDN discourages loose equality because its results are hard to predict.
  • • Indeed Pakistan lists a Rs. 102,425 monthly average for JavaScript developers, from only 17 salaries.
Table of contents 30 sections
  1. What Are Interviewers Testing With JavaScript Interview Questions?
  2. 15 JavaScript Interview Questions and the Skill Each One Checks
  3. Round 1: Variables, Types and Equality
  4. 1. What Is the Difference Between var, let and const?
  5. 2. What Is Hoisting?
  6. 3. What Is the Difference Between == and ===?
  7. 4. What Is the Difference Between null and undefined?
  8. Round 2: Functions, Scope and this
  9. 5. What Is a Closure in JavaScript?
  10. 6. How Does the this Keyword Work?
  11. 7. How Are Arrow Functions Different From Regular Functions?
  12. 8. What Is a Callback Function?
  13. Round 3: Arrays, Objects and Modern Syntax
  14. 9. When Do You Use map, filter and reduce?
  15. 10. What Do Spread, Rest and Destructuring Do?
  16. 11. What Is the Difference Between a Shallow and a Deep Copy?
  17. Round 4: Promises, async/await and the Event Loop
  18. 12. What Is a Promise?
  19. 13. How Do async and await Work, and How Do You Handle Errors?
  20. 14. How Does the Event Loop Work?
  21. 15. What Is Event Delegation?
  22. Predict the Output: Four Snippets Freshers Get Wrong
  23. Snippet A: Timers Inside a var Loop
  24. Snippet B: Promise vs setTimeout
  25. Snippet C: Adding Strings and Numbers
  26. Snippet D: Comparing Arrays
  27. How Should You Answer When You Don't Know?
  28. What Do JavaScript Jobs in Pakistan Pay?
  29. Where PSTA's 12-Week JavaScript Course Fits
  30. Run a 30-Minute Mock Interview Tomorrow

"Which JavaScript questions will they actually ask me?" It's one of the most common worries before a first technical interview at a software house in Islamabad, Lahore or Rawalpindi. The short answer: JavaScript interview questions for freshers come from a small, predictable pool. Scope, equality, closures, this, array methods and async code cover most of a first technical round.

This guide gives you 15 of those questions with model answers, short code you can type out yourself, and a few output puzzles of the kind interviewers love to put on a whiteboard.

Here is what you will walk away with:

  • The skill each common question is really checking
  • Answers short enough to say out loud in under a minute
  • Four "predict the output" snippets, with the reasoning behind each result
  • A way to respond when you don't know an answer
  • Realistic salary numbers and a mock interview plan for this week

What Are Interviewers Testing With JavaScript Interview Questions?

A fresher interview is not a trivia contest. Most interviewers have a short list of things they want to confirm. Can you predict what a few lines of code will print? Do you understand why, or did you memorize it? Can you write a small function without an AI assistant open in another tab?

JavaScript stays the language most developers use: two in three respondents (66%) to Stack Overflow's 2025 survey reported working with it, rising to 68.8% among professionals. That popularity means interviewers have seen every memorized answer. What stands out is a clear explanation plus a tiny example.

So for each of the JavaScript interview questions below, practice three parts: a one-line definition, a code example of two to five lines, and one sentence on where it matters in a real project.

15 JavaScript Interview Questions and the Skill Each One Checks

Use this table as a revision sheet for the most common JavaScript coding interview topics. If you can answer the left column without looking at the right, you're in good shape for most first rounds.

# Question Skill Being Checked
1 var vs let vs const Scope and reassignment
2 What is hoisting? How code is prepared before it runs
3 == vs === Type coercion
4 null vs undefined Data types
5 What is a closure? Functions and scope
6 How does this work? Function call context
7 Arrow vs regular functions Syntax and this binding
8 Callback functions Passing functions around
9 map, filter and reduce Array processing
10 Spread, rest and destructuring Modern ES6+ syntax
11 Shallow vs deep copy References in memory
12 What is a promise? Async basics
13 async/await and error handling Async code you can read
14 How does the event loop work? Execution order
15 What is event delegation? DOM events

Round 1: Variables, Types and Equality

1. What Is the Difference Between var, let and const?

Model answer: var is function-scoped and can be declared again. let and const are block-scoped, so they only exist inside the nearest pair of curly braces. You can reassign a let but not a const.

function demo() {
  var a = 1;
  { var a = 2; }   // same variable
  console.log(a);  // 2

  let b = 1;
  { let b = 2; }   // a new variable
  console.log(b);  // 1
}

Add one detail that most candidates skip: const blocks reassignment, not change. A const array can still receive push(). In practice, start with const and switch to let only when a value must change.

JavaScript interview questions grid comparing var, let and const by scope and reassignment
Scope and reassignment rules for var, let and const.

2. What Is Hoisting?

Model answer: Before a block runs, JavaScript sets up its declarations. A var is created and set to undefined, so reading it early gives undefined. A let or const also exists from the start of the block, but touching it before its declaration line throws a ReferenceError.

That gap has a name: the temporal dead zone. The MDN reference for let describes it as the span from the start of the block to the line where the variable is initialized. Using the term correctly shows you've read beyond tutorials.

3. What Is the Difference Between == and ===?

Model answer: === compares value and type with no conversion. == converts both sides to a common type first, which leads to results like 0 == "0" being true. MDN's guide to equality calls strict equality the right choice almost every time and discourages loose equality.

A strong follow-up: NaN === NaN is false, while Object.is(NaN, NaN) is true. Object.is also treats +0 and -0 as different, which === does not. Also, two separate objects with the same contents are never equal under any of the three operators, because they are different references.

4. What Is the Difference Between null and undefined?

Model answer: undefined means a value was never assigned, such as a declared variable or a missing object property. null is a value you set on purpose to say "empty". A classic trap: typeof null returns "object", a long-standing quirk of the language. Mention that you check for both with value == null only when you mean it, or with the ?? operator when you want a default.

Round 2: Functions, Scope and this

5. What Is a Closure in JavaScript?

Model answer: A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has returned. MDN's closures guide points out that every function in JavaScript creates one.

function makeCounter() {
  let count = 0;
  return function () {
    count = count + 1;
    return count;
  };
}
const next = makeCounter();
next(); // 1
next(); // 2

Give a real use: the count variable is private. Nothing outside makeCounter can reset it. Closures also power event handlers, debounce functions in search boxes, and React hooks.

6. How Does the this Keyword Work?

Model answer: In a regular function, this is decided by how the function is called, not where it is written. Called as user.greet(), it points to user. Passed as a bare callback, it loses that link. In strict mode it becomes undefined. You can fix it with bind() or by using an arrow function.

Keep the answer short and offer an example from a click handler. Interviewers mostly want to see that you know the call site matters.

7. How Are Arrow Functions Different From Regular Functions?

Model answer: Arrow functions are shorter, and they don't get their own this or arguments. They take this from the surrounding code. That makes them great for callbacks inside methods, and a poor choice for object methods that need this to point at the object. You also can't use an arrow function as a constructor with new.

8. What Is a Callback Function?

Model answer: A callback is a function you pass to another function so it can be called later. addEventListener("click", handleClick) and setTimeout(save, 1000) both take callbacks. Then mention the problem: deeply nested callbacks are hard to read and harder to handle errors in, which is one reason promises arrived.

Round 3: Arrays, Objects and Modern Syntax

9. When Do You Use map, filter and reduce?

Model answer: map transforms every item and returns a new array of the same length. filter keeps only the items that pass a test. reduce folds the array into a single value, such as a total.

const orders = [
  { item: "Shirt", price: 1800, paid: true },
  { item: "Shoes", price: 4500, paid: false },
  { item: "Cap", price: 700, paid: true }
];
const paidTotal = orders
  .filter(o => o.paid)
  .reduce((sum, o) => sum + o.price, 0); // 2500

Expect a follow-up asking you to write this with a plain for loop. Do it calmly. It proves you understand what the methods do underneath.

10. What Do Spread, Rest and Destructuring Do?

Model answer: Spread (...arr) expands an array or object into individual items, handy for copying or merging. Rest uses the same three dots in a parameter list to collect leftover arguments into an array. Destructuring pulls values out into variables: const { name, city } = student;. You'll see all three in nearly every React component.

11. What Is the Difference Between a Shallow and a Deep Copy?

Model answer: A shallow copy, such as { ...obj }, copies the top level only. Nested objects are still shared, so changing copy.address.city also changes the original. A deep copy duplicates every level. Modern browsers and Node.js offer structuredClone(obj) for that.

Round 4: Promises, async/await and the Event Loop

12. What Is a Promise?

Model answer: A promise is an object that stands for a result that isn't ready yet. It starts as pending, then becomes fulfilled with a value or rejected with an error. You react with .then() and .catch(). fetch() returns one, which is why API calls are the usual example.

13. How Do async and await Work, and How Do You Handle Errors?

Model answer: An async function always returns a promise. Inside it, await pauses that function until a promise settles, so the code reads top to bottom. You catch failures with try...catch.

async function loadCourses() {
  try {
    const res = await fetch("/api/courses");
    if (!res.ok) throw new Error("HTTP " + res.status);
    return await res.json();
  } catch (err) {
    console.error("Could not load courses:", err.message);
    return [];
  }
}

The detail that impresses interviewers is the res.ok check. fetch only rejects on network failure. A 404 or 500 response still resolves, so you have to test the status yourself.

14. How Does the Event Loop Work?

Model answer: JavaScript runs one job at a time on a single thread. Synchronous code runs first until the call stack is empty. Then the engine empties the microtask queue, which holds promise callbacks. Only after that does it take the next task, such as a setTimeout callback. The MDN page on the execution model explains that microtasks have higher priority and are drained before the task queue.

Event loop process flow: sync code, microtasks, one task, then repeat
The order in which the event loop runs your code.

Also mention run-to-completion: once a job starts, nothing interrupts it. That's why a heavy loop freezes a page, and why long work should be split up.

15. What Is Event Delegation?

Model answer: Instead of adding a listener to every list item, you add one listener to the parent. Events bubble up from the clicked element, and you check event.target to see which child was clicked. It saves memory and also works for items added to the page later, such as rows loaded from an API.

document.querySelector("#cart").addEventListener("click", (e) => {
  const btn = e.target.closest(".remove");
  if (btn) removeItem(btn.dataset.id);
});

Predict the Output: Four Snippets Freshers Get Wrong

Some interviewers add a short written or whiteboard round with snippets like these. Try each one before you read the answer.

Snippet A: Timers Inside a var Loop

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Output: 3, 3, 3. All three callbacks share one function-scoped i, and they run after the loop ends. Change var to let and you get 0, 1, 2, because each pass of the loop gets its own binding.

Snippet B: Promise vs setTimeout

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");

Output: A, D, C, B. Synchronous logs come first, then the promise microtask, then the timer task, even with a delay of zero.

Snippet C: Adding Strings and Numbers

console.log("5" + 3);
console.log("5" - 3);

Output: "53", then 2. The + operator joins strings when either side is a string. The - operator only works on numbers, so it converts "5" first.

Snippet D: Comparing Arrays

console.log([1, 2] === [1, 2]);

Output: false. Each array literal creates a new object, and strict equality compares references, not contents.

Equality cheat sheet comparing ==, === and Object.is results
Loose equality, strict equality and Object.is compared.

How Should You Answer When You Don't Know?

You will get at least one question you can't fully answer. That's normal, and how you handle it counts. Try this sequence:

  1. Say what you do know. "I haven't used WeakMap in a project, but I know Map stores key-value pairs with any type of key."
  2. Reason out loud. Walk through the code line by line. Interviewers often care more about your thinking than the final answer.
  3. Ask a clarifying question. "Is this running in the browser or in Node.js?" is a fair thing to ask.
  4. Offer to check it. "I'd confirm that in the MDN docs before shipping it" sounds like someone who works carefully.

Guessing with confidence and getting it wrong does more damage than an honest "I'm not sure, but here's how I'd find out."

It also helps to know what's new. ECMAScript 2026, the 17th edition of the language standard, was approved on June 30, 2026, according to InfoWorld's report. Additions include Math.sumPrecise, Error.isError and Array.fromAsync. Nobody expects a fresher to know them all, but naming one recent feature shows you keep up.

What Do JavaScript Jobs in Pakistan Pay?

Salary data for Pakistan is thin, so treat any single figure with care. Indeed Pakistan lists an average of Rs. 102,425 a month for a JavaScript developer, based on just 17 reported salaries as of July 29, 2026. That mixes junior and experienced people, so a fresher's first offer will usually sit below it.

Junior job ads in Pakistan rarely say "JavaScript developer" alone. You'll see titles such as frontend developer, React developer, MERN stack intern and WordPress developer, and each of them involves JavaScript. If you're aiming at React roles, follow this round with our list of React interview questions for junior developers, and read TypeScript vs JavaScript since many ads now list TypeScript as a plus.

If you're still at the stage of planning what to learn in which month, the frontend developer roadmap for Pakistan lays out the full order from HTML to deployment.

Where PSTA's 12-Week JavaScript Course Fits

Reading model answers to JavaScript interview questions helps, but interviews reward people who have written the code many times. PSTA's JavaScript course (Beginner to React) is a 12-week program pitched at beginners. Its modules cover functions and closures, array and object operations, DOM events, callbacks and promises, the Fetch API with error handling, ES6+ syntax and modules, then React basics with hooks and routing.

When this guide was published, the fee shown was Rs. 24,000, reduced from a regular Rs. 28,000. Pick whichever suits you: the Abbottabad classroom, live online sessions from your own city, or a blend. Fresh batches open monthly. Students finish with projects deployed on GitHub, which gives you something concrete to talk about when an interviewer says "show me something you built."

When you're ready for the next level, the Advanced React.js course picks up from there. You can compare options on the full course list or start your form on the admission page. Have a question about class timings first? The admissions team answers on WhatsApp at +92 314 5424399.

Run a 30-Minute Mock Interview Tomorrow

Turn this list of JavaScript interview questions into a rehearsal. Ask a friend or classmate to pick five numbers between 1 and 15 from the table above. Answer each question out loud with a phone timer set to 60 seconds, then type the code example in your browser console without looking. Finish with the four output snippets. Wherever you hesitated, that's your revision list for the next two days.

Frequently asked questions

How many JavaScript questions are asked in a fresher interview?

There is no fixed number. A first technical round usually mixes a few concept questions, one or two output puzzles and a small coding task. Instead of counting questions, make sure you can explain scope, equality, closures, this, array methods and async code clearly, with a short example for each. Those topics come up again and again.

Should I learn React before my first JavaScript interview?

Get comfortable with plain JavaScript first. Most interviewers for React roles still start with closures, array methods and promises, because React code depends on them. Once you can answer the 15 questions in this guide without notes, learning React basics such as components, props and hooks becomes much easier, and your answers in a React round will be stronger.

Can I use ChatGPT or other AI tools during a technical interview?

Only if the interviewer says you can. Many companies treat it as cheating in a live round. AI tools are fine for preparation, for example to quiz yourself or explain an error, but practice writing small functions on your own. Interviewers want to see how you think when the screen is blank.

Do I need TypeScript for a junior JavaScript job?

Not always, but it helps. Many junior ads list TypeScript as a plus rather than a requirement. Learn JavaScript properly first, since TypeScript is JavaScript with types added on top. After that, a week or two of converting a small project to TypeScript gives you enough to talk about it with confidence.

What small coding tasks should I practice for a JavaScript interview?

Practice short problems you can finish in 10 to 15 minutes: reverse a string, count how often each character appears, remove duplicates from an array, find the largest number, check for a palindrome, and group a list of objects by a key. Write each one with a loop first, then again with array methods.

How long does it take to prepare for a JavaScript interview?

If you already know the basics, two to three weeks of daily practice is a sensible target. Spend the first week revising concepts, the second on output puzzles and small coding tasks, and the third on mock interviews out loud. Starting from zero takes longer, since you need to build and deploy a few projects first.

Can I join PSTA's JavaScript course online?

Yes. The JavaScript Programming Course: Beginner to React runs on campus in Abbottabad, live online across Pakistan, or as a mix of both. It lasts 12 weeks, starts a new batch every month, and ends with portfolio projects deployed on GitHub. Check the course page for the current fee and batch timings.

Sources & references

  1. Stack Overflow 2025 Developer Survey: Technology survey.stackoverflow.co
  2. MDN: Closures developer.mozilla.org
  3. MDN: let and the temporal dead zone developer.mozilla.org
  4. MDN: Equality comparisons and sameness developer.mozilla.org
  5. MDN: JavaScript execution model developer.mozilla.org
  6. InfoWorld: ECMAScript 2026 specification approved infoworld.com
  7. Indeed Pakistan: JavaScript developer salaries pk.indeed.com

Last reviewed & updated on by Umar Qureshi. Written by the PSTA team in Abbottabad, Pakistan.

Share this article
Umar Qureshi
About the author

Umar Qureshi

Trainer at Professional Skills & Tech Academy

Umar Qureshi is an IT skills trainer and instructor at Professional Skills & Tech Academy (PSTA) in Abbottabad. He teaches programming, digital marketing and practical computer skills, with a focus on hands-on projects that students can use in jobs and freelancing. His articles turn technical topics into clear, step-by-step guidance for students and job seekers across Pakistan.

JavaScript Programming Course in Abbottabad: Beginner to React course at PSTA
Recommended course

JavaScript Programming Course in Abbottabad: Beginner to React

Turn this guide into a career: hands-on training with real projects, online across Pakistan or on-campus in Abbottabad · 12 Weeks.

Rs. 24,000.00 Rs. 28,000.00

Comments

No comments yet — ask a question or share your experience.

Leave a comment

Comments are moderated. Please be respectful — no links to spam.