[go: up one dir, main page]

0% found this document useful (0 votes)
2 views6 pages

JavaScript Interview Questions for Freshers

This document outlines essential JavaScript interview questions for freshers, covering core concepts such as data types, variable scope, functions, and ES6 features. It also addresses DOM manipulation, event handling, asynchronous programming, and debugging techniques. The content is structured to help candidates prepare for technical interviews by understanding key JavaScript principles and practices.

Uploaded by

lawojim575
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

JavaScript Interview Questions for Freshers

This document outlines essential JavaScript interview questions for freshers, covering core concepts such as data types, variable scope, functions, and ES6 features. It also addresses DOM manipulation, event handling, asynchronous programming, and debugging techniques. The content is structured to help candidates prepare for technical interviews by understanding key JavaScript principles and practices.

Uploaded by

lawojim575
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

JavaScript Interview Questions for Freshers

Core JavaScript Basics


• What are the different data types in JavaScript? JavaScript has seven primitive data types –
Boolean, Number, String, Symbol, Undefined, Null, and BigInt – plus reference types like Objects
and Arrays 1 . For example, typeof 42 is "number" , typeof "hello" is "string" ,
and arrays/objects are complex types that can hold multiple values.
• What is the difference between == and === ? The == operator (loose equality) compares
values after performing type coercion, whereas === (strict equality) checks both value and type
2 . For instance, 3 == "3" is true (because "3" is coerced to number 3), but 3 === "3"
is false since the types differ 3 .
• What is hoisting? Hoisting is JavaScript’s default behavior of moving all variable and function
declarations to the top of their containing scope before execution 4 . This means you can
reference a function or a var -declared variable before its declaration; however, only the
declaration is hoisted (initialized values are not). For example, calling a function before its
definition still works, and a console.log(x) before var x = 5; will log undefined (not
an error) 4 .
• What does the this keyword refer to? In JavaScript, this refers to the object context of
the current function call. Its value depends on how a function is invoked 5 . For example, in a
regular function call this is the global object (or undefined in strict mode); in an object
method, this is that object; in a constructor, it’s the new instance; and in an arrow function,
this is lexically inherited from the surrounding scope 6 .
• How do you debug JavaScript code? Common techniques include using the browser’s
developer tools (e.g. pressing F12 in Chrome) to set breakpoints and step through code, or
inserting console.log(...) statements to print variable values. You can also use the
debugger; statement to programmatically pause execution at a line 7 . Understanding error
messages (syntax vs. runtime errors) and using try/catch blocks for error handling are also key
for debugging.

Variables and Scope (var, let, const)


• What is the difference between var , let , and const ? Variables declared with var are
function-scoped (or globally-scoped if outside any function) and can be redeclared or reassigned.
In contrast, let and const (introduced in ES6) are block-scoped 8 . Both let and const
cannot be redeclared in the same scope; let variables can be reassigned (but not redeclared),
whereas const variables cannot be reassigned after initialization 8 . For example,
const x = 3; x = 5; will throw an error because x is a constant. Also, var variables are
hoisted (initialized as undefined ), but let / const are in a “temporal dead zone” until their
declaration.
• What is scope? Scope determines where a variable is accessible. In JavaScript, global scope
(variables declared outside any function) makes a variable available everywhere. Function scope
(variables declared with var inside a function) limits access to that function. Block scope
(variables declared with let or const inside {} ) limits access to that block. For example, a
let declared in a loop or if block is not visible outside it. Proper understanding of scope
helps avoid unintended globals and bugs.

1
Functions, Closures, and Callbacks
• What is a function declaration vs. a function expression? A function declaration uses the
function keyword at the top level (e.g. function foo() {} ), while a function expression
assigns a function to a variable (e.g. const foo = function() {} ). Declarations are hoisted
(you can call foo() before its declaration in code), whereas expressions are not (the variable
must exist first) 9 .
• What are arrow functions? Arrow functions ( => ) provide a shorter syntax for writing
functions. For example, const add = (a, b) => a + b; . They also inherit this lexically
from the enclosing scope 10 . Arrow functions cannot be used as constructors and do not have
their own arguments object.
• What is a callback function? A callback is a function passed as an argument to another
function, which is then invoked inside the outer function. Callbacks are widely used for
asynchronous operations or event handling. For example:

function greet(name, callback) {


console.log("Hello " + name);
callback();
}
function sayGoodbye() { console.log("Goodbye!"); }
greet("Alice", sayGoodbye); // Hello Alice \n Goodbye!

Here, sayGoodbye is a callback that runs after greet logs its message 11 .
• What are closures? A closure occurs when an inner function retains access to variables from its
outer (enclosing) function scope, even after the outer function has finished executing 12 . In
other words, the inner function “closes over” the outer scope. For example:

function outer() {
let x = 10;
return function inner() {
console.log(x);
}
}
const fn = outer();
fn(); // logs 10

Here, inner still accesses x even after outer has returned 12 . Closures are useful for data
privacy and callbacks.
• What is strict mode ( "use strict" )? Strict mode is a way to opt in to a restricted variant of
JavaScript. It disallows certain bad syntax (like duplicate parameter names), prevents creation of
implicit globals, and makes errors more visible. You enable it by adding "use strict"; at the
top of your script or function. In strict mode, for example, assigning to an undeclared variable
throws a ReferenceError 13 .

ES6+ Features
• What are rest parameters and the spread operator? The rest parameter syntax ...args in
a function definition collects all remaining arguments into an array (e.g. function
sum(...nums) {} ) 14 . The spread operator ( ... ) does the opposite: it expands an iterable

2
(like an array) into individual elements. For example, Math.max(...[3,5,1]) is equivalent to
Math.max(3,5,1) . It can also spread object properties into a new object 15 .
• What is destructuring assignment? Destructuring lets you unpack values from arrays or
properties from objects into distinct variables. For example, const [a, b] = [1, 2]; sets
a=1 and b=2 . For objects: const {x, y} = {x:10, y:20}; extracts x and y into
variables 16 . This syntax makes it easy to work with data by extracting only needed parts.
• What are Promises? A Promise is an object representing the eventual completion (success) or
failure of an asynchronous operation 17 . It has three possible states: pending (initial), fulfilled
(completed successfully), or rejected (failed). Promises provide .then() and .catch()
methods to handle success or error cases. For example:

const p = new Promise((resolve, reject) => {


// do async work, then:
if (success) resolve("Done");
else reject("Error");
});
p.then(res => console.log(res)).catch(err => console.error(err));

• What are async/await keywords? async / await provide syntax for writing asynchronous
code in a synchronous style. Marking a function async means it returns a Promise. Within it,
the await keyword can pause execution until a Promise resolves or rejects. For example,
await fetch(url) waits for the HTTP request to complete. Using try / catch with async/
await simplifies error handling. Under the hood, it’s syntactic sugar over Promises 18 .

DOM Manipulation and Event Handling


• How do you access HTML elements in JavaScript? Common DOM methods include
document.getElementById("id") , document.getElementsByClassName("class") ,
document.getElementsByTagName("tag") , and
document.querySelector("selector") . The querySelector method is very flexible as it
takes any CSS selector and returns the first matching element 19 20 . Once you have an
element, you can read or modify its properties (e.g. innerHTML , value , classList , etc.).
• How do you handle events? You can attach event handlers using methods like
element.addEventListener(event, handler) . Common events include click ,
mouseover , keydown , keyup , and change 21 . For example:
button.addEventListener("click", () => { /* do something */ }); .
• What is event bubbling (or propagation)? Event bubbling means that an event fired on a
nested (child) element will propagate up through its parent elements. That is, clicking on an
inner element first triggers its own handler, then its parent’s handler, and so on up to the root
22 . You can stop propagation using event.stopPropagation() .

• How do you prevent default browser behavior for an event? Inside an event handler, call
event.preventDefault() to stop the browser’s default action. For example,
link.addEventListener("click", e => { e.preventDefault(); /* handle click
without navigating */ }); 23 .
• What is localStorage vs. sessionStorage ? Both are web Storage APIs for persisting key-
value data in the browser. The difference is lifetime: localStorage data persists indefinitely
(even after closing the browser) and is shared across tabs of the same origin, whereas
sessionStorage data is limited to a single tab session and is cleared when that tab is closed
24 . Both store only strings (you can JSON-encode objects).

3
Objects and Arrays
• How do you create objects and arrays? An object can be created using an object literal: e.g.
const obj = {name: "John", age: 17}; . You can also use constructors or
Object.create() . An array is created with brackets: e.g. let arr = [1, 2, 3] or new
Array(5) .
• What is the difference between an array and an object? Arrays are specialized objects used
for ordered collections indexed by numbers; they come with array methods and a numeric
length . Objects are unordered collections of key-value pairs indexed by string keys. In
practice, arrays should be used when data is list-like, and plain objects for records or maps 25 .
• How do you iterate over arrays? You can use loops ( for , for...of ), or array methods like
.forEach() , .map() , .filter() . For example, arr.forEach(x =>
console.log(x)); or const doubled = arr.map(x => x*2) .
• How can you remove duplicates from an array? One simple way is to use a Set : e.g.
[...new Set(arr)] creates a new array of unique values. Alternatively, you can filter with
index checking. For example:

const unique = arr.filter((item, index) => arr.indexOf(item) === index);

This returns a new array without duplicates 26 .


• How do you check if an array contains a value? Use the includes() method:
arr.includes(value) returns true if the value is present (using strict equality) 27 .
• What are some common array methods? map() transforms each element (returning a new
array) 28 , filter() keeps elements that meet a condition, and reduce() combines
elements into a single value (e.g. summing) 29 . For example, const sum =
nums.reduce((acc, x) => acc + x, 0) computes the sum of an array.

Prototypes and Inheritance


• What is a prototype in JavaScript? Every JavaScript object has a prototype: another object from
which it can inherit properties and methods 30 . The prototype essentially serves as a shared
template. For example, if you add a method to Object.prototype , all objects will inherit it.
The prototype chain is used during property lookup: if a property isn’t found on an object, JS
looks up its prototype chain 31 .
• How does prototypal inheritance work? When you create an object (for example via a
constructor or class), it links to the constructor’s prototype. Objects then inherit properties/
methods from that prototype. In practice, this means you can define methods once on a
prototype and all instances share them. JavaScript does not use class-based inheritance
internally; ES6 class syntax is mostly syntactic sugar over prototypes.
• What is the difference between classical (class-based) and prototypal inheritance? In
classical (e.g. Java/C++) you define classes and subclasses. JavaScript’s prototypal inheritance
means that objects directly inherit from other objects. For example, using Person.prototype
to give methods to all person objects is prototypal inheritance; ES6 classes compile down to this
mechanism 32 .

Asynchronous JavaScript and Event Loop


• What is setTimeout() and how is it used? setTimeout(callback, ms) schedules the
callback function to run after at least ms milliseconds. It’s often used to delay execution or

4
schedule tasks. Note that callbacks run via the event loop and do not block other code. (Similarly,
setInterval() repeats execution at intervals.) For example:
js
console.log("Start");
setTimeout(() => { console.log("Delayed"); }, 2000);
console.log("End");
// Output: Start, End, (2s pause), Delayed 33 .
• What is the event loop? JavaScript uses a single-threaded runtime with an event loop. When
functions are called, their execution contexts go on the call stack. Asynchronous callbacks (from
setTimeout , I/O, promises, etc.) go into a task (callback) queue. The event loop continuously
checks: if the call stack is empty, it takes the next callback from the queue and pushes it onto the
stack 34 . This mechanism allows JS to handle asynchronous operations without blocking, even
though the main thread is single-threaded.
• How do promises and callbacks fit into this? A callback passed to an async API will be queued
when the operation completes (e.g. after a timeout or HTTP response). Promises work similarly
but allow chaining. For example, fetch(url).then(response => ...) will queue the
then handler via the event loop when the HTTP request finishes. Understanding the event loop
helps explain why setTimeout(fn, 0) still defers fn until after the current code.

Debugging and Common Errors


• What are common error types? Syntax errors occur when code is malformed. Runtime errors
happen when code is syntactically correct but fails during execution (e.g. ReferenceError for
an undefined variable, TypeError for invalid operations, etc.). Logic errors are mistakes in
code logic that don’t throw errors but produce wrong results. Knowing typical error names
(SyntaxError, TypeError, ReferenceError) helps debugging.
• How do you catch errors? Use try { ... } catch(err) { ... } blocks around code that
may throw. For example:

try {
JSON.parse(badString);
} catch(e) {
console.error("Invalid JSON:", e);
}

Browsers also show uncaught errors in the console with stack traces, which helps locate the
problem.
• What is the debugger statement? Inserting debugger; into code acts like a breakpoint: it
pauses execution at that line when DevTools are open, allowing you to step through code line by
line 7 . This is useful for inspecting state at a precise point.

Browser APIs and Tools


• What is the window object? In a browser, window is the global object representing the
browser window 35 . All global variables and functions are its properties. The document object
(the DOM) is a property of window . You can access browser features (like window.location
or window.history ) through this object.
• What is fetch() ? The fetch() function is a modern API for making HTTP requests. It
returns a Promise that resolves with the response. For example, fetch('/api/

5
data').then(res => res.json()).then(data => console.log(data)) makes an
asynchronous request without callbacks 36 .
• What is localStorage ? The localStorage API allows storing key-value string data in the
browser persistently. You use localStorage.setItem(key, value) and
localStorage.getItem(key) to store and retrieve data. It has no expiration (unlike cookies)
and is scoped per domain.
• What is sessionStorage ? Similar to localStorage , but it stores data for only one session
(it is cleared when the tab/window is closed) 37 . Use it for data that should not persist beyond
the current browsing session.

Execution Context and Call Stack (Advanced)


• What is the execution context and call stack? Every time JavaScript runs code, it creates an
execution context (environment) that holds the scope, variables, and code to be executed. The call
stack is a stack data structure of execution contexts: when a function is invoked, a new context is
pushed onto the stack; when it returns, it’s popped off. The top of the stack is the currently
executing context. Understanding this model helps explain function call order and why recursion
or deeply nested calls can cause a stack overflow. (Internally, the event loop works with this stack
to manage async callbacks as mentioned above.)
• What is a closure in terms of execution context? A closure occurs when a function retains
access to its lexical environment (execution context) even after the outer function has finished. In
terms of the stack, the outer function’s context remains available in memory for the inner
function’s use. This is why variables do not get garbage-collected if an inner function still refers
to them.

Sources: Core concepts here are gathered and summarized from JavaScript interview guides and
documentation 1 2 4 10 38 24 30 12 . These cover data types, operators, scoping, ES6
features, DOM methods, and other frequently asked topics. Each answer above is supported by these
authoritative references.

1 7 9 10 13 18 20 21 22 23 24 25 26 27 28 29 33 35 36 37 55 Top JavaScript Interview


Questions with Example Answers | Built In
https://builtin.com/software-engineering-perspectives/javascript-interview-questions

2 4 5 6 8 11 12 17 34 JavaScript Interview Questions and Answers - GeeksforGeeks


https://www.geeksforgeeks.org/javascript/javascript-interview-questions/

3 14 15 16 19 32 38 90+ Essential Javascript Interview Questions and Answers


https://www.simplilearn.com/tutorials/javascript-tutorial/javascript-interview-questions

30 31 JavaScript Prototype - GeeksforGeeks


https://www.geeksforgeeks.org/javascript/js-prototype/

You might also like