Prescreen Interview Questions
1. What difference between const
, let
and var
?
var
was used in the old version of JavaScript, it doesn’t depend on scope. JavaScript creates VAR first, and it pops up on the stack.var
declarations are globally scoped.let
allows to keep variables sticked to its scope.const
values can’t be reassigned, only its property if it’s an array or object.
2. Explain Prototypical Inheritance.
Considering the fact that in JavaScript, everything is an object, each object has a private property called prototype
. This property contains the link to the parent object with its properties, continuing until it reaches the object with a prototype equal to null.
3. What is this
in JS?
this
refers to the object that is executing the current code
- In a method,
this
refers to the object the method belongs to. - In a function,
this
refers to the global object or undefined in strict mode. - In a constructor (when a function is used as a constructor with
new
),this
refers to the newly created instance. - In event handlers,
this
typically refers to the element that triggered the event.
4. What is the Data Structure of the DOM?
Tree (a hierarchical tree-like structure).
5. What is a Stack? What is a Queue? How to create in js?
Stack and Queue are data structures. A Stack follows the Last In, First Out (LIFO) principle, Queue is based on the First In, First Out (FIFO) principle. Methods associated with a Stack include pop
and push
, whereas a Queue includes enqueue
and dequeue
operations using push
and shift
.
Stack in JavaScript
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return "Underflow";
}
return this.items.pop();
}
peek() {
return !this.isEmpty() ? this.items[this.items.length - 1] : null;
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
}
Queue in JavaScript
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
if (this.isEmpty()) {
return "Underflow";
}
return this.items.shift();
}
front() {
return !this.isEmpty() ? this.items[0] : null;
}
isEmpty() {
return this.items.length === 0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
}
6. How can you tell if an image element is loaded on a page?
You can use the callback of an onload
event of the image element if it has loaded:
const image = document.getElementById('yourImageId');
image.onload = function() {
// Actions to perform when the image is loaded
console.log('Image loaded!');
};
7. What are call()
and apply()
?
call()
and apply()
are JS methods used to invoke functions explicitly, allowing you to set the value of this
within the function, altering the context (scope), and to pass arguments.
call()
allows you to call a function, specifying the context (this
) and passing arguments individually. Syntax is:functionName.call(thisArg, arg1, arg2, ...)
apply()
is similar tocall()
, but it passes arguments as an array. The syntax is:functionName.apply(thisArg, [arg1, arg2, ...])
.
Both methods facilitate setting the function context and passing arguments, with call()
accepting arguments individually and apply()
using an array for arguments.
// Example using call()
function greet(name) {
console.log(`Hello, ${name}! I am ${this.role}.`);
}
const person = { role: 'an AI' };
greet.call(person, 'User'); // Output: Hello, User! I am an AI.
// Example using apply()
const person2 = { role: 'a Moderator' };
greet.apply(person2, ['Another User']); // Output: Hello, Another User! I am a Moderator.
8. What is Event Delegation?
Delegation is attaching a single event listener to a common parent element, rather than multiple listeners on individual child elements, associated with event bubbling.
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<script>
const myList = document.getElementById("myList");
myList.addEventListener("click", function (event) {
if (event.target.tagName === "LI") {
alert(`Clicked on ${event.target.textContent}`);
}
});
</script>
9. What is a Worker? When would you use one?
Implement background heavy operations such a sorting, heavy calculations, real-time updates, periodic data syncing, ongoing data analysis etc. Workers are executed without blocking the main user interface. Have no access to DOM model.
if (window.Worker) {
const worker = new Worker('worker.js');
// Send a message to the Worker
worker.postMessage(5); // Calculating factorial of 5
// Listen for messages from the Worker
worker.onmessage = function(event) {
console.log('Factorial calculated:', event.data);
};
} else {
console.log("Web Workers are not supported in this browser.");
}
JavaScript File (worker.js):
// Listen for messages from the main thread
self.onmessage = function(event) {
const number = event.data;
// Calculate the factorial of the number
const result = factorial(number);
// Send the result back to the main thread
self.postMessage(result);
};
// Function to calculate the factorial of a number
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
10. What difference between Attributes and Properties?
- Attributes: Metadata specified in HTML markup. Static and manipulated using
getAttribute
andsetAttribute
. Defined in HTML.
<input type="text" id="username" class="input-field">
- Properties: Actual values or states of elements in the DOM. Dynamic and manipulated directly in JavaScript. Accessed and updated through JavaScript. Reflect the current state of the element.
const inputElement = document.getElementById('username');
const inputType = inputElement.type;
11. What is Scope in JavaScript?
In JavaScript, “scope” refers to the context in which variables are declared and accessed. It determines the visibility and accessibility of variables in different parts of the code. There are global scope, local scope (function scope), and block scope (introduced with let
and const
in ES6). Variables declared in a specific scope are only accessible within that scope unless explicitly passed or shared. Understanding scope is crucial for managing variable lifetimes and avoiding naming conflicts in a program.
12. Hoisting is a JavaScript
Hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase before the code is executed. This allows you to use variables and functions before they are declared in the code.
console.log(myVar); // Output: undefined
var myVar = 42;
console.log(myVar); // Output: 42
sayHello(); // Output: "Hello, World!"
function sayHello() {
console.log("Hello, World!");
}
13. What is Temporal Dead Zone (TDZ)?
Temporal Dead Zone (TDZ) is specific to let
and const
variables, it’s the period between the start of the scope and the actual declaration where the variable cannot be accessed, resulting in a ReferenceError
if accessed during this period.
14. Difference between null
and undefined
undefined
represents the absence of a value or an uninitialized variable.null
represents the intentional absence of any object value or a deliberate assignment to indicate no value.undefined
is both a value and a type.null
is an object type.undefined
often arises when a variable is declared but not assigned a value.null
is often used to explicitly signify the absence of a meaningful value or reference.undefined == null
evaluates totrue
in loose equality comparison.undefined === null
evaluates tofalse
in strict equality comparison.
15. What are Arrow Functions?
Arrow functions have implicit return for single expressions, don’t have their own this
context (inherit from the surrounding scope), and don't have an arguments
object. Can be more concise, especially for simple one-liner functions.
16. What is Closure?
Closure in JavaScript is the combination of a function and the lexical environment in which it was declared. It allows a function to access variables from its outer scope even after the outer function has finished executing. Closures are created when an inner function is defined within an outer function, and they play a key role in data encapsulation, callback functions, and functional programming in JavaScript.
function outerFunction() {
const outerVariable = "I am from the outer function";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const closureExample = outerFunction();
closureExample(); // Output: "I am from the outer function"
17. What is async
/ await
in JavaScript?
async/await
is a feature in JavaScript that simplifies working with asynchronous code. The async
keyword is used to define asynchronous functions that always return a promise, and the await
keyword is used to pause the execution of an async function until a promise is resolved. This syntax enhances readability, error handling, and sequential execution of asynchronous operations, making code look more like synchronous programming.
async function example() {
const result = await someAsyncFunction();
console.log(result);
}
18. Difference between ==
and ===
==
(Equality Operator):
- Performs type coercion, attempting to convert operands to the same type before comparison.
- Examples:
'5' == 5
evaluates totrue
.
'5' == 5; // true (String '5' is coerced to a number)
null == undefined; // true (both are loosely considered equal)
===
(Strict Equality Operator):
- Does not perform type coercion; operands must be of the same type to be considered equal.
- Examples:
'5' === 5
evaluates tofalse
.
'5' === 5; // false (String '5' is not equal to the number 5 in strict comparison)
null === undefined; // false (strictly not equal)
It’s generally recommended to use ===
for strict equality checks to avoid unexpected type coercion and ensure predictable comparisons.