JavaScript Interview Questions for Freshers (with Scenarios and Code)
This lesson collects the JavaScript questions freshers and junior testers are asked most often, from campus placements to first automation roles. Each answer is short enough to say out loud in an interview, followed by a small code example that proves it (every output was produced by running the code with Node.js 26). Many questions are scenario-based, the way testing interviews are run today: “your test does X, why?”. Read a question, answer it yourself first, then compare. Each answer links back to the lesson that covers the topic in depth.
📖 What You’ll Learn: how to answer the most common fresher questions on variables and scope, data types and coercion, == vs ===, null vs undefined, truthy and falsy values, functions, arrow functions and hoisting, closures, arrays and objects, copying data, callbacks, promises and async/await, the DOM and events, error handling, and why JavaScript matters for test automation.
🧭 How to Answer in an Interview
- Definition first, in one sentence. Then one example. Then, if relevant, why it matters (a bug it causes, how it affects tests).
- If you do not know, say how you would find out (MDN, running a quick example in the console). Interviewers value honest reasoning.
- For testing roles, connect answers to automation: waits, flaky tests, test data, assertions.
📦 Variables, Types and Comparisons
Q1. What is the difference between var, let and const?
var is function-scoped and hoisted (initialised to undefined); let and const are block-scoped and cannot be used before their declaration. const cannot be reassigned, but an object stored in it can still change. Use const by default, let when the value changes, and avoid var.
📄 q1.js
if (true) {
var a = 1;
let b = 2;
}
console.log(a, typeof b); // var leaks out of the block
const config = { env: "qa" };
config.env = "staging"; // allowed: the object changes
console.log(config.env);
try {
config = {}; // not allowed: reassignment
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
⌨️ Terminal
node q1.js
🖥️ Output
1 undefined
staging
TypeError: Assignment to constant variable.
Q2. What are the data types in JavaScript?
Seven primitive types (string, number, bigint, boolean, undefined, null, symbol) plus object, which includes arrays, functions, dates and maps. typeof tells them apart, with two famous quirks:
📄 q2.js
const values = ["text", 42, 10n, true, undefined, null, Symbol("id"), {}, [], () => {}];
for (const v of values) console.log(typeof v, "<-", v === null ? "null" : Array.isArray(v) ? "[]" : String(v));
console.log(Array.isArray([]));
⌨️ Terminal
node q2.js
🖥️ Output
string <- text
number <- 42
bigint <- 10
boolean <- true
undefined <- undefined
object <- null
symbol <- Symbol(id)
object <- [object Object]
object <- []
function <- () => {}
true
typeof null is "object" (a historical bug) and arrays are objects, so use Array.isArray() to detect them.
Q3. What is the difference between == and ===?
=== (strict equality) compares value and type with no conversion. == converts types first, which gives surprising results. Always use ===; linters enforce it (eqeqeq rule).
📄 q3.js
console.log(5 == "5", 5 === "5");
console.log(0 == "", 0 === "");
console.log(null == undefined, null === undefined);
console.log(NaN === NaN, Number.isNaN(NaN));
⌨️ Terminal
node q3.js
🖥️ Output
true false
true false
true false
false true
Q4. null vs undefined?
undefined means “not assigned yet”: a declared variable without a value, a missing property, a function with no return. null is an intentional “no value” set by the programmer. Check both at once with value == null or provide defaults with ??.
📄 q4.js
let order;
const user = { name: "Asha", manager: null };
console.log(order, user.age, user.manager);
console.log(user.age ?? "age not set", user.manager ?? "no manager");
⌨️ Terminal
node q4.js
🖥️ Output
undefined undefined null
age not set no manager
Q5. Which values are falsy? (Scenario: a check skips a valid quantity of 0)
Exactly eight values are falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else is truthy, including "0", "false", [] and {}. A check like if (qty) wrongly treats 0 as “missing”:
📄 q5.js
function validateQty(qty) {
if (!qty) return "quantity required"; // bug: 0 is treated as missing
return `ok: ${qty}`;
}
function validateQtyFixed(qty) {
if (qty === undefined || qty === null) return "quantity required";
return `ok: ${qty}`;
}
console.log(validateQty(0), "|", validateQtyFixed(0));
console.log(Boolean("0"), Boolean([]), Boolean(""));
⌨️ Terminal
node q5.js
🖥️ Output
quantity required | ok: 0
true true false
Q6. What is type coercion? Give an example that surprises people.
Automatic conversion of a value to another type by an operator. + with a string concatenates, while -, * and / convert to numbers. Values read from inputs, URLs and environment variables are strings, so convert them explicitly with Number():
📄 q6.js
console.log("5" + 3, "5" - 3, "5" * "2", true + 1);
const fromInput = "10";
console.log(fromInput + 5, Number(fromInput) + 5);
⌨️ Terminal
node q6.js
🖥️ Output
53 2 10 2
105 15
🔧 Functions, Scope and Closures
Q7. Function declaration vs function expression vs arrow function?
A declaration (function add() {}) is hoisted, so it can be called before it appears. An expression (const add = function () {}) and an arrow function (const add = () => {}) exist only after that line runs. Arrow functions are shorter and do not have their own this, which makes them ideal for callbacks.
📄 q7.js
console.log(declared(2, 3)); // works: hoisted
function declared(a, b) { return a + b; }
try {
console.log(expressed(2, 3));
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
const expressed = (a, b) => a + b;
console.log(expressed(2, 3));
⌨️ Terminal
node q7.js
🖥️ Output
5
ReferenceError: Cannot access 'expressed' before initialization
5
Q8. What is hoisting?
Before running a scope, JavaScript registers its declarations. Function declarations are fully available; var variables exist with the value undefined; let/const exist but cannot be touched until their line runs (the “temporal dead zone”).
📄 q8.js
console.log(early); // undefined, not an error
var early = "var is hoisted";
try {
console.log(late);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
let late = "let is in the TDZ";
⌨️ Terminal
node q8.js
🖥️ Output
undefined
ReferenceError: Cannot access 'late' before initialization
Q9. What is a closure? Give a practical example.
A closure is a function that remembers the variables of the scope where it was created, even after that scope has finished. It is used for private state, factories and callbacks. Example: a counter that cannot be changed from outside, and a factory for test-id generators:
📄 q9.js
function createIdGenerator(prefix) {
let count = 0; // private, remembered by the closure
return () => `${prefix}-${String(++count).padStart(3, "0")}`;
}
const nextBugId = createIdGenerator("BUG");
const nextTestId = createIdGenerator("TC");
console.log(nextBugId(), nextBugId(), nextTestId());
⌨️ Terminal
node q9.js
🖥️ Output
BUG-001 BUG-002 TC-001
Q10. What is the difference between parameters and arguments, and what are default and rest parameters?
Parameters are the names in the function definition; arguments are the values passed when calling it. Default parameters provide fallback values; a rest parameter collects the remaining arguments into an array:
📄 q10.js
function login(user, password = "Test#123", ...flags) {
return `${user} / ${password} / flags: ${flags.join(",") || "none"}`;
}
console.log(login("qa_user"));
console.log(login("admin", "Admin#1", "remember-me", "skip-tour"));
⌨️ Terminal
node q10.js
🖥️ Output
qa_user / Test#123 / flags: none
admin / Admin#1 / flags: remember-me,skip-tour
📚 Arrays, Objects and Strings
Q11. Explain map, filter and reduce with one example.
map transforms every element into a new array, filter keeps the elements that pass a test, and reduce combines all elements into one value. None of them change the original array.
📄 q11.js
const results = [
{ test: "login", status: "passed", ms: 1200 },
{ test: "cart", status: "failed", ms: 3100 },
{ test: "search", status: "passed", ms: 800 },
];
console.log(results.map((r) => r.test));
console.log(results.filter((r) => r.status === "failed").map((r) => r.test));
console.log(results.reduce((total, r) => total + r.ms, 0), "ms in total");
⌨️ Terminal
node q11.js
🖥️ Output
[ 'login', 'cart', 'search' ]
[ 'cart' ]
5100 ms in total
Q12. How do you copy an array or object? (Scenario: changing test data in one test breaks another)
Assigning (const b = a) copies the reference, so both names point to the same object. Spread ([...a], { ...obj }) makes a shallow copy; structuredClone makes a deep copy including nested objects:
📄 q12.js
const baseUser = { name: "Test", roles: ["viewer"] };
const sameRef = baseUser;
const shallow = { ...baseUser };
const deep = structuredClone(baseUser);
sameRef.name = "Changed";
shallow.roles.push("admin"); // nested array is shared with the shallow copy!
deep.roles.push("lead");
console.log(baseUser);
console.log(deep.roles);
⌨️ Terminal
node q12.js
🖥️ Output
{ name: 'Changed', roles: [ 'viewer', 'admin' ] }
[ 'viewer', 'lead' ]
Q13. How do you remove duplicates from an array?
📄 q13.js
const browsers = ["chromium", "firefox", "chromium", "webkit", "firefox"];
console.log([...new Set(browsers)]);
⌨️ Terminal
node q13.js
🖥️ Output
[ 'chromium', 'firefox', 'webkit' ]
Q14. How do you check whether an object has a property, and loop over an object?
📄 q14.js
const config = { env: "qa", retries: 0 };
console.log("retries" in config, Object.hasOwn(config, "timeout"));
for (const [key, value] of Object.entries(config)) console.log(`${key} = ${value}`);
⌨️ Terminal
node q14.js
🖥️ Output
true false
env = qa
retries = 0
if (config.retries) would be false because the value is 0, which is why checking existence with in or Object.hasOwn is safer.
Q15. What are template literals?
Strings in backticks that allow ${expressions} and multiple lines, used everywhere in tests for messages, URLs and selectors: `${baseURL}/api/users/${id}`.
⏳ Asynchronous JavaScript
Q16. What is the difference between synchronous and asynchronous code?
Synchronous code runs line by line and each line waits for the previous one. Asynchronous operations (timers, network requests, file reads) start now and finish later; JavaScript continues with other code and handles the result through a callback, a promise or await.
📄 q16.js
console.log("1. start");
setTimeout(() => console.log("3. timer finished"), 0);
console.log("2. end of script");
⌨️ Terminal
node q16.js
🖥️ Output
1. start
2. end of script
3. timer finished
Even a 0 ms timer runs after the current script: JavaScript finishes the current work first, then the event loop runs queued callbacks.
Q17. What is a promise?
An object representing a value that will be available later. It is pending, then either fulfilled with a value or rejected with an error. Handle it with .then()/.catch() or await.
Q18. What does async/await do? (Scenario: a test checks a value before the page updates)
async functions always return a promise; await pauses that function until a promise settles, so asynchronous code reads like synchronous code. Forgetting await is the most common bug in automation code: the next line runs before the previous step has finished.
📄 q18.mjs
const fetchStatus = () => new Promise((resolve) => setTimeout(() => resolve("Order placed"), 50));
async function withoutAwait() {
const status = fetchStatus(); // forgot await
console.log("without await:", status);
}
async function withAwait() {
const status = await fetchStatus();
console.log("with await:", status);
}
await withoutAwait();
await withAwait();
⌨️ Terminal
node q18.mjs
🖥️ Output
without await: Promise { <pending> }
with await: Order placed
Q19. How do you handle errors in async code?
Wrap await calls in try...catch (with finally for clean-up), or attach .catch() to a promise. An unhandled rejection can crash a Node.js process or hide a failure.
📄 q19.mjs
const getUser = async (id) => { if (id < 1) throw new Error(`invalid user id ${id}`); return { id }; };
try {
await getUser(0);
} catch (e) {
console.log("caught:", e.message);
} finally {
console.log("clean-up runs either way");
}
⌨️ Terminal
node q19.mjs
🖥️ Output
caught: invalid user id 0
clean-up runs either way
🌐 DOM, Browser and Testing Basics
Q20. What is the DOM and how do you select an element?
The DOM is the browser’s tree of objects built from the HTML. Select elements with document.querySelector(css) (first match or null) and querySelectorAll(css) (all matches). Automation tools use the same idea for locators.
Q21. What is event bubbling?
After an event fires on an element, it travels up through its parents, so a click on a button inside a card also reaches the card’s listeners. Event delegation uses this to handle many children with one listener on the parent.
Q22. What is the difference between localStorage, sessionStorage and cookies?
localStorage keeps strings until deleted, shared by all tabs of a site; sessionStorage lasts for one tab; cookies are small, can expire and are sent to the server with requests (HttpOnly cookies cannot be read by JavaScript). Tests use them to set up state, such as being logged in.
Q23. Why is JavaScript important for a tester?
Modern automation tools (Playwright, Cypress, WebdriverIO) and many front ends are written in JavaScript or TypeScript. With JavaScript you can write UI and API tests, generate test data, read the app’s code, use the browser console to investigate bugs, and contribute to the same repository as developers.
Q24. Scenario: a Playwright test sometimes fails because an element is not found. What do you check?
Whether the step is awaited; whether the locator is stable (role, label, test id rather than position-based CSS); whether the element appears only after a network call or animation (use web-first assertions that wait, never fixed sleeps); whether it is inside an iframe or a different tab; and the trace or screenshot of the failure to see the real page state.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. What does console.log(typeof NaN, typeof [], typeof null) print, and why?
Show answer
📄 p1.js
console.log(typeof NaN, typeof [], typeof null);🖥️ Output
number object objectNaN is a special value of the number type; arrays are objects; typeof null is “object” because of a historical bug.
Q2. Write a function that returns true if a string is a palindrome, ignoring case and spaces.
Show answer
📄 p2.js
const isPalindrome = (s) => {
const clean = s.toLowerCase().replace(/\s+/g, "");
return clean === [...clean].reverse().join("");
};
console.log(isPalindrome("Never odd or even"), isPalindrome("QA"));🖥️ Output
true falseQ3. Fix the bug: the function should return the total of all prices, but it returns a string.
const prices = ["499", "799"];
const total = prices.reduce((sum, p) => sum + p, 0);Show answer
📄 p3.js
const prices = ["499", "799"];
console.log(prices.reduce((sum, p) => sum + p, 0)); // "0499799"
console.log(prices.reduce((sum, p) => sum + Number(p), 0)); // 1298🖥️ Output
0499799
1298The values are strings, so + concatenates. Convert each one with Number().
Q4. Count how many times each status appears in ["passed", "failed", "passed", "skipped", "passed"].
Show answer
📄 p4.js
const statuses = ["passed", "failed", "passed", "skipped", "passed"];
const counts = {};
for (const s of statuses) counts[s] = (counts[s] ?? 0) + 1;
console.log(counts);🖥️ Output
{ passed: 3, failed: 1, skipped: 1 }Q5. What is printed, and in which order?
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");Show answer
📄 p5.js
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");🖥️ Output
A
D
C
BSynchronous code first (A, D), then promise callbacks (microtasks: C), then timers (macrotasks: B).
Q6. Scenario: a login test passes on your machine but fails in CI with “Cannot read properties of undefined (reading ’email’)”. Name three possible causes.
Show answer
Test data or environment variables missing in CI (for example process.env.TEST_USER undefined); an API returned an error body instead of the expected user because of a different environment or missing authentication; a missing await so the value is read before it arrives; or a file path that is relative to the working folder and not found in CI. Check logs and the trace, then make the code fail fast with a clear message when required data is missing.
🧠 MCQ Quiz: Interview Questions: Freshers
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which keyword creates a block-scoped variable that can be reassigned?Answer: let. const cannot be reassigned; var is function-scoped.
- What is
typeof null?Answer: “object”. A long-standing quirk. - What does
"5" + 3give?Answer: “53”. + with a string concatenates. - Which value is truthy?Answer: “0”. Non-empty strings are truthy.
- What does
[1, 2, 3].filter(n => n > 1)return?Answer: [2, 3]. filter keeps elements that pass. - How do you make a deep copy of an object with nested arrays?Answer: structuredClone(obj). Spread and assign are shallow.
- What does an async function always return?Answer: A promise. Use await or then to get the value.
- What is a closure?Answer: A function that remembers variables from where it was created. Used for private state and factories.
- Which runs first: a promise .then callback or a setTimeout 0 callback?Answer: The promise callback. Microtasks before macrotasks.
- How do you remove duplicates from an array?Answer: […new Set(arr)]. A Set keeps unique values.
💼 Interview Questions and Answers
Q1. Tell me about a JavaScript bug you found or fixed.
Use a short STAR story: Situation, Task, Action, Result. For example: “A discount was applied twice for some carts. I reproduced it with a unit test and found the test data array was sorted in place by one function and reused by another. I changed the code to use toSorted(), added a regression test, and the issue stopped.” Concrete details (the bug, how you found it, the test you added) matter more than size.
Q2. How would you explain the event loop to a non-developer?
JavaScript is like a single cashier who serves one customer at a time. Long tasks such as waiting for a delivery are handed to helpers (the browser or Node.js); when a delivery arrives, a note goes into a queue. Whenever the cashier is free, they take the next note. Urgent notes (promises) are handled before ordinary ones (timers).
Q3. What do you do when you do not know the answer to a coding question?
Think aloud: restate the problem, try a small example by hand, write the simplest working solution first, test it with edge cases (empty input, one element, duplicates), and then improve it. Interviewers assess the approach as much as the final code.
Q4. How are you preparing to grow from manual testing to automation?
Mention concrete steps: learning JavaScript fundamentals and practising daily programs, automating a few real test cases with Playwright against practice sites, using Git and GitHub, writing API tests, and reading the developers’ code. A small public project, such as the to-do app or API checker from this course with tests and CI, is strong evidence.
❓ Frequently Asked Questions
🤔 How many questions should I prepare?
Understand the 24 here deeply rather than memorising hundreds. Interviewers ask follow-ups (“why?”, “show me”), so be able to write a small example for each.
🤔 Will I have to write code on paper or in an online editor?
Usually an online editor or a shared document. Practise writing small programs without autocomplete: string, array and object exercises are the most common for freshers.
🤔 Where can I practise more?
Use the coding programs lesson in this module and the SQA Tools practice program pages, then try the timed Playwright mock interviews.
🤔 Do I need TypeScript for fresher roles?
JavaScript fundamentals come first. Knowing that TypeScript adds types, and being able to read simple type annotations, is a plus for automation roles.
🏁 Summary
- Answer with a definition, an example and why it matters for testing.
- Know let/const/var, data types, === vs ==, null vs undefined, falsy values and coercion cold.
- Explain hoisting, closures, arrow functions, default and rest parameters with small examples.
- Use map/filter/reduce, copy data safely, and understand promises, async/await and the order of the event loop.
- Connect answers to automation: awaiting steps, stable locators, waiting for state, and clear test data.
Next, continue with Lesson 76: Interview Questions: 3-5 Years.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in