JavaScript Interview Questions & Answers
Complete Guide for JavaScript Developers - ES6+, Functions, Async Programming, Arrays, OOP, DOM & More
What is JavaScript?
Ans: JS is a dynamic language means data types of the variables can change during the runtime.
JS is client-side scripting language. JS language primarily used to make web pages interactive.
JS is client-side scripting language. JS language primarily used to make web pages interactive.
Pseudo-classes and pseudo-elements?
Ans:
Pseudo-classes: A pseudo-class is used to style elements based on their state, position in the DOM, or user interaction. It doesn't affect the element's actual content but targets it in specific conditions.
Pseudo-elements: A pseudo-element is used to style a part of an element, such as inserting content before or after the content of the element.
Pseudo-classes: A pseudo-class is used to style elements based on their state, position in the DOM, or user interaction. It doesn't affect the element's actual content but targets it in specific conditions.
:hover, :focus, :first-child, :last-child, :disabled, :checked and others are pseudo-classes used to target elements based on their state or position.Pseudo-elements: A pseudo-element is used to style a part of an element, such as inserting content before or after the content of the element.
::before and ::after are pseudo-elements used to insert content before or after an element's actual content.
Undefined vs Null?
Ans: Undefined means the variable has been declared but no value is assigned to it.
Null indicates intentional absence of data. Null indicates it's not empty, it's just absence of data.
Null indicates intentional absence of data. Null indicates it's not empty, it's just absence of data.
Template literals?
Ans: Template literals (also called template strings) are a modern way to create strings, especially when including variables or expressions inside the string.
Use backticks (
Insert variables or expressions using
Use backticks (
` ` ) instead of quotes.Insert variables or expressions using
${ ... }.const result = `Sum: ${a + b}`;
What is hoisting?
Ans: Hoisting is a JavaScript mechanism that allows functions/variables to be used before they are declared in the code. In other words, JavaScript moves function declarations to the top of their respective scope, allowing them to be used even if they are declared later in the code.
Ex:
Ex:
this.Fun();
Fun() {
console.log('Hello, world!');
}
Data types in JS?
Ans:
a) Primitive Data Types: These are immutable (unable to be changed) and stored by value.
Ex:
b) Non-Primitive (Reference) Data Types: These are stored by reference.
Ex:
a) Primitive Data Types: These are immutable (unable to be changed) and stored by value.
Ex:
string, number, boolean, BigInt, undefined, null, Symbolb) Non-Primitive (Reference) Data Types: These are stored by reference.
Ex:
object, array, function
Difference between let, const and var?
Ans:
Note:
| Feature | var | let | const |
|---|---|---|---|
| Scope | Functional scope | Block scope | Block scope |
| Redeclaration | Can be redeclared | Cannot be redeclared (SyntaxError) | Cannot be redeclared (SyntaxError) |
| Reassignment | Can be reassigned | Can be reassigned | Cannot be reassigned |
| Declaration without value | Can be declared without value | Can be declared without value | Cannot be declared without value (SyntaxError) |
| Hoisting | Variable hoisting possible | Cannot hoist (ReferenceError) | Cannot hoist (ReferenceError) |
Note:
const a = {}a['newkey'] = 5 // it will successfully added in json
What is the Temporal Dead Zone (TDZ)?
Ans: The Temporal Dead Zone (TDZ) in JavaScript is the period between when a variable is declared with
Only
let or const and when it is initialized, during which accessing the variable throws a ReferenceError.Only
let and const have a Temporal Dead Zone — var does not.console.log(a); // ❌ ReferenceError: Cannot access 'a' before initialization
let a = 10;
What is the difference between == and ===?
Ans:
== (Loose Equality): Compares values, after converting types if needed.
== (Loose Equality): Compares values, after converting types if needed.
'5' == 5 // true
null == undefined // true
=== (Strict Equality): Compares both value and type without conversion.null === undefined // false
5 === 5 // true
What is the spread operator (...) and how is it used?
Ans: The spread operator (
Using for shallow copy.
...) in JavaScript is used to expand elements of an iterable (like arrays or strings) or to copy/merge objects and arrays.Using for shallow copy.
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const combined = { ...obj1, ...obj2 };
Deep copy and shallow copy in JavaScript?
Ans: A deep copy means that all of the values of the new variable are copied and disconnected from the original variable.
const billiardGame = deepCopy(billiard);
const billiardGame = JSON.parse(JSON.stringify(billiard))
A shallow copy means that certain (sub-)values are still connected to the original variable.const billiardGame = { ...billiard };
const billiardGame = Object.assign({}, billiard);
What is argument & parameter?
Ans:
- Arguments are values passed to the function when it is invoked.
- Parameters are variables listed as a part of the function definition.
- Function parameters are the names of variables present in the function definition. Function arguments are the real values that are passed to the function and received by them.
Binary operator in JS?
Ans:
- Multiplicative Operators
- Additive Operators
- Bitwise Shift Operators
- Relational Operators
- Equality Operators
- Binary Bitwise Operators
- Binary Logical Operators
Arrow function?
Ans: An arrow function expression is a compact alternative to a traditional function expression.
The arrow function syntax is a shorthand way to define a function, which makes code more short and easier to read.
The
Arrow function having lexical scope so it can use
Useful in functional programming patterns like
The arrow function syntax is a shorthand way to define a function, which makes code more short and easier to read.
The
{ braces } and ( parentheses ) and "return" are not required in Arrow function.Arrow function having lexical scope so it can use
this keyword.Useful in functional programming patterns like
.map(), .filter(), .reduce()const add = (a, b) => a + b;
What is callback function?
Ans: "I'll call you back when I'm done."
A callback function in JavaScript is a function passed as an argument to another function — and it's usually called later.
This technique allows a function to call another function.
Callbacks are commonly used to handle asynchronous operations.
A callback function in JavaScript is a function passed as an argument to another function — and it's usually called later.
This technique allows a function to call another function.
Callbacks are commonly used to handle asynchronous operations.
Higher order functions?
Ans: A higher-order function (HOF) in JavaScript is a function that does either 'Takes one or more functions as arguments' or 'Returns a function'.
* Takes one or more functions as arguments:
* Takes one or more functions as arguments:
function greet(name) {
return `Hello, ${name}`;
}
function processUserInput(callback) {
const name = 'Alice';
return callback(name);
}
console.log(processUserInput(greet)); // "Hello, Alice"
* Returns a function:
function multiplier(factor) {
return function (number) {
return number * factor;
};
}
const double = multiplier(2); // storing the returned function
console.log(double(5)); // calls the returned function and result is 10
What is an IIFE (Immediately Invoked Function Expression)?
Ans: It is a function that runs immediately after it's defined, without being called explicitly later in the code.
Using to create local scope, Runs code immediately.
Using to create local scope, Runs code immediately.
(function() {
console.log('IIFE executed!');
})();
Nested Callbacks = "Callback Hell"?
Ans: When callbacks are deeply nested, it can become hard to read and maintain, to overcome this situation we can use Promises or async/await instead, or any other asynchronous operations.
What are Promises and how do they help avoid callback hell?
Ans: A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
It has three states: Pending (Initial state) -> resolve Or reject
It has three states: Pending (Initial state) -> resolve Or reject
const myPromise = new Promise((resolve, reject) => {
// async operation
if (/* success */) {
resolve("Success!");
} else {
reject("Something went wrong.");
}
});
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
How async/await works for asynchronous programming in JavaScript?
Ans: async/await is a syntactic feature in JavaScript that simplifies working with asynchronous code, making it more readable and maintainable. It's built on top of promises and provides a way to write asynchronous code that looks and behaves a bit more like synchronous code.
async function myFunction() {
try {
const result = await someAsyncOperation();
console.log(result);
} catch (error) {
console.error("Error:", error);
}
}
Sorting methods in JS?
Ans:
Array.sort(): Sorting alphabetically works well for strings.Array.reverse(): Reverse method reverses the elements in an array.Array.sort((a, b) => a - b): Sort numbers in ascending order.Array.sort((a, b) => b - a): Sort numbers in descending order.
Array iteration methods in JS?
Ans:
Examples:
forEach(): method calls a function (a callback function) once for each array element.map(): method creates a new array by performing a function on each array element.filter(): method creates a new array with array elements that pass a test.reduce(): method runs a function on each array element to produce (reduce it to) a single value.reduceRight(): method runs a function on each array element to produce (reduce it to) a single value works from right-to-left.every(): method checks if all array values pass a test.some(): method checks if some array values pass a test.indexOf(): method searches an array for an element value and returns its position.lastIndexOf(): is the same as indexOf(), but returns the position of the last occurrence of the specified element.find(): method returns the value of the first array element that passes a test function.findIndex(): method returns the index of the first array element that passes a test function.from(): method returns an Array object from any object with a length property or any iterable object.keys(): method returns an Array Iterator object with the keys of an array.entries(): method returns an Array Iterator object with key/value pairs.includes(): method allows us to check if an element is present in an array (including NaN, unlike indexOf).
Examples:
[1, 2, 3].length; // 3
[1, 2, 3].push(4); // [1, 2, 3, 4] *
[1, 2, 3].unshift(0); // [0, 1, 2, 3] *
[1, 2, 3].pop(); // [1, 2]
[1, 2, 3].shift(); // [2, 3] *
[1, 2, 3].at(2); // 3
[1, 2, 3].indexOf(3); // 2
[1, 2, 3].includes(3); // true
[1, 2, 3].map((num) => num * 2); // [2, 4, 6]
[1, 2, 3].filter((num) => num > 1); // [2, 3]
[1, 2, 3].every((num) => num > 0); // true
[1, 2, 3].some((num) => num > 2); // true
[1, 2, 3].fill(0); // [0, 0, 0]
[1, 2, 3].reduce((acc, num) => acc + num, 0); // 6
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]
[1, 2, 3].reverse(); // [3, 2, 1]
[1, 2, 3].sort(); // [1, 2, 3]
[1, 2, 3].join("-"); // "1-2-3"
[1, 2, 3].flat(); // [1, 2, 3]
[1, 2, 3].find((num) => num === 1); // 1
[1, 2, 3].findIndex((num) => num === 2); // 1
[1, 2, 3].toString(); // "1,2,3"
[1, 2, 3].toLocaleString(); // "1,2,3"
[1, 2, 3].slice(1, 2); // [2]
[1, 2, 3].splice(1, 1, "a"); // [1, 'a', 3]
Array.isArray([1, 2, 3]); // true
Array.from("123"); // ['1', '2', '3']
Difference between for & foreach loop?
Ans:
| Feature | for | forEach |
|---|---|---|
| Type | Original way of iterating over an array | Newer way with lesser code to iterate over an array |
| Performance | Faster in performance | Slower than the traditional loop in performance |
| Break statement | Can use break statement to come out from the loop | Cannot be used because of the callback function |
| Parameters | for(let i = 1; i<=5; i++) or for(iterator, counter, increment) |
forEach(a, i, array) or forEach(iterator, index, and array to iterate) |
| await keyword | Works with await keyword | Cannot be used due to the callback function |
Difference between filter & map?
Ans:
- filter method is used to filter the elements from an array based on a given condition.
map does not discard any element instead it manipulates the value of elements. - filter changes the new array length.
map doesn't change the length of new Array
Difference between slice and splice?
Ans: slice and splice are methods used in JavaScript arrays to retrieve certain elements or remove elements from the array.
slice(): It is used to cut out elements from an array. It does not affect the original array.
splice(): It is used to remove elements from an array or replace them.
slice(): It is used to cut out elements from an array. It does not affect the original array.
array.slice(start, end)splice(): It is used to remove elements from an array or replace them.
array.splice(start, deleteCount, newElem1, newElem2, ..., newElemN);
JavaScript String Methods?
Ans:
Examples:
String.lengthproperty returns the length of a string.slice(start, end)extracts a part of a string and returns the extracted part in a new string.substring(start, end)extracts a part of a string and returns the extracted part in a new string.substr(start, length)extracts a part of a string and returns the extracted part in a new string.replace(preval, newval)method replaces only the first match. If you want to replace all matches, use a regular expression with the /g flag set.String.toLowerCase()A string is converted to lower case.String.toUpperCase()A string is converted to upper case.String1.concat(String2)joins two or more strings.String.trim()method removes whitespace from both sides of a string.String.trimStart()method removes whitespace from start side of a string.String.trimEnd()method removes whitespace from end side of a string.String.charAt(2)method returns the character at a specified index (position) in a string.String.charCodeAt(2)method returns the unicode of the character at a specified index in a string.text[0]text string property access method.split("")method convert string in array.
Examples:
"JavaScript".length; // 10
"JavaScript"[2]; // 'v'
"JavaScript".charAt(2); // 'v'
"JavaScript".charCodeAt(2); // 118
"JavaScript".indexOf("S"); // 4
"JavaScript".toLowerCase(); // 'javascript'
"JavaScript".toUpperCase(); // 'JAVASCRIPT'
"JavaScript".slice(2, 5); // 'vas'
"JavaScript".substring(2, 5); // 'vas'
"JavaScript".substr(2, 2); // 'va'
"JavaScript".concat(" Dev"); // 'JavaScript Dev'
"JavaScript Dev".split(" "); // ['JavaScript', 'Dev']
"JavaScript Dev".includes("Dev"); // true
"Java Dev".replace("Dev", "JS"); // 'Java JS'
"Java Dev".replaceAll("Dev", "JS"); // 'Java JS'
"JavaScript Dev".trim(); // 'JavaScript Dev'
" JavaScript Dev ".trimStart(); // 'JavaScript Dev '
" JavaScript Dev ".trimEnd(); // ' JavaScript Dev'
"Dev".padStart(10, "*"); // '*******Dev'
"Dev".padEnd(10, "*"); // 'Dev*******'
"JavaScript Dev".startsWith("Java"); // true
"JavaScript Dev".endsWith("Dev"); // true
"JavaScript Dev".repeat(3); // 'JavaScript DevJavaScript DevJavaScript Dev'
"JavaScript Dev".indexOf("JavaScript"); // 0
"JavaScript Dev".lastIndexOf("Dev"); // 11
"JavaScript Dev".search("Dev"); // 11
"JavaScript Dev".includes("Dev"); // true
Do you know about memory leaks?
Ans: Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.
- Unsubscribed Observables:
this.subscription.unsubscribe(); - Remove Event Listeners:
window.removeEventListener('resize', this.handleResize); - Clear SetInterval / SetTimeout:
clearInterval(this.intervalFn);
What is the difference between setTimeout, setInterval, and debounce time and What if we put 0 millisecond in setInterval?
Ans:
Ex.
The
Ex.
setTimeout() method executes a function, after waiting a specified number of milliseconds.Ex.
window.setTimeout(function, milliseconds);The
setInterval() method repeats a given function at every given time-interval.Ex.
window.setInterval(function, milliseconds);
What is Cookie and what's the max length of cookie?
Ans: Cookies let you store user information in web pages.
Cookies are data, stored in small text files, on your computer.
JavaScript can create, read, and delete cookies with the
A cookie is an amount of information that persists between a server-side and a client-side.
Maximum length of Cookie is 4KB.
Cookies are data, stored in small text files, on your computer.
JavaScript can create, read, and delete cookies with the
document.cookie property.A cookie is an amount of information that persists between a server-side and a client-side.
Maximum length of Cookie is 4KB.
What is lexical Scope in JS?
Ans: A lexical scope in JavaScript means that a variable defined outside a function can be accessible inside another function defined after the variable declaration. But the opposite is not true; the variables defined inside a function will not be accessible outside that function.
Closure in JS?
Ans: A closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
A closure in JavaScript is when a function "remembers" the variables from its lexical scope, even after the outer function has finished executing.
A closure in JavaScript is when a function "remembers" the variables from its lexical scope, even after the outer function has finished executing.
function outerFn(){
let outerData = 'Lexical Data';
function innerFn(){
console.log(outerData);
}
return innerFn;
}
let closureCall = outerFn()
closureCall()
Function currying in JS?
Ans: We simply wrap function inside a function, which means we are going to return a function from another function to obtain this kind of translation. The parent function takes the first provided argument and returns the function that takes the next argument and this keeps on repeating till the number of arguments ends.
Hopefully, the function that receives the last argument returns the expected result.
Hopefully, the function that receives the last argument returns the expected result.
function sendEmail(to) {
return function (sub) {
return function (body) {
return `Sending Email to ${to} with subject ${sub} : ${body}`;
}
}
}
console.log(sendEmail('abc@gmail.com')('Subject here')('Body text'))
Reference: Function Currying Video
What Are call, apply, and bind?
Ans:
* Call: Calls a function with a given
* Call: Calls a function with a given
this value and individual arguments. It invokes the function immediately.function greet(greeting) {
console.log(`${greeting}, I'm ${this.name}`);
}
const person = { name: 'Alice' };
greet.call(person, 'Hello'); // Output: Hello, I'm Alice
* Apply: Same as call(), but arguments are passed as an array. It invokes the function immediately.greet.apply(person, ['Hi']); // Output: Hi, I'm Alice
* Bind: Returns a new function with this bound to the given object. It does not call the function immediately.const greetPerson = greet.bind(person);
greetPerson('Hey'); // Output: Hey, I'm Alice
Event loop in JS?
Ans: Event Loop is the mechanism in JavaScript that Handles asynchronous operations.
Priority Order:
The Event Loop Process:
Priority Order:
- Synchronous code runs first
- Microtasks (from queueMicrotask, Promise.then, etc.) run next, before any macrotasks.
- Macrotasks (like Timers, I/O, setTimeout etc.) are run after all current microtasks are done
The Event Loop Process:
- Call Stack: The call stack is a data structure that keeps track of function calls. Executes your code line by line.
- Microtask Queue: Stores promise callbacks (.then, catch) — has higher priority than the callback queue.
- Web APIs: These APIs handle async operations and send callbacks to appropriate queues.
- Macrotask Queue/Callback Queue: Stores callback functions (like from Timers, I/O, setTimeout) that are ready to run.
- Event Loop: Checks if the call stack is empty, then moves tasks from the queues.
What is the difference between microtasks and macrotasks?
Ans: The event loop always gives higher priority to the microtask queue, and will process all the callbacks in the microtask queue before moving on to the macrotask queue.
The microtask queue contains the callbacks of operations that are considered more urgent or important, such as promises and mutation observers APIs.
The macrotask queue contains the callbacks of operations that are less urgent such as timers, I/O events, and user interface events.
The microtask queue contains the callbacks of operations that are considered more urgent or important, such as promises and mutation observers APIs.
The macrotask queue contains the callbacks of operations that are less urgent such as timers, I/O events, and user interface events.
Event Bubbling vs. Event Capturing?
Ans: Event bubbling and capturing are two phases in how events propagate through the Document Object Model (DOM).
a) Event Bubbling: An event propagates from the target element upwards to its parent elements.
a) Event Bubbling: An event propagates from the target element upwards to its parent elements.
document.getElementById("outer").addEventListener("click", () => {
console.log("Outer DIV (bubbling)");
});
b) Event Capturing: An event propagates from the root element (document) downwards to the target element.document.getElementById("outer").addEventListener("click", () => {
console.log("Outer DIV (capturing)");
}, true);
* Stopping Propagation: stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.document.getElementById("middle").addEventListener("click", (event) => {
console.log("Middle DIV clicked");
event.stopPropagation(); // 🛑 stops bubbling/capturing
});
How can you make an interface readonly?
Ans:
1. Mark specific properties as readonly:
1. Mark specific properties as readonly:
interface User {
readonly id: number;
}
2. Make all properties readonly using Readonly<T> utility type:interface User {
id: number;
}
const userData: Readonly<User> = { id: 1};
3. Make entire array or object deeply readonly (for nested objects):const names: ReadonlyArray<string> = ['Alice', 'Bob'];
How can we make a property read-only via a method?
Ans:
interface User {
id: number;
}
// Dynamic method which we can apply on any key
type MakeReadonly<T, K extends keyof T> = Omit<T, K> & Readonly<Pick<T, K>>;
// Calling to make readonly
type ReadonlyId = MakeReadonly<User, 'id'>;
const userData: ReadonlyId = {id: 1}; // Use case
emp.id = 2; // ❌ Error
OOP in JS?
Ans: Object-oriented programming is about modeling a system as a collection of objects, where each object represents some particular aspect of the system. Objects contain both functions (or methods) and data. OOP was made available with ES6 in 2015.
Objects and classes in JS?
Ans:
Object: An object is a collection of key–value pairs (properties and methods) used to represent real-world entities like a person, product, or car.
Class: A class is a blueprint for creating multiple similar objects with shared structure and behavior.
Object: An object is a collection of key–value pairs (properties and methods) used to represent real-world entities like a person, product, or car.
Class: A class is a blueprint for creating multiple similar objects with shared structure and behavior.
class Person {
constructor() {...}
myMethod() {...}
}
const obj = new Person();
// Here obj is object and Person is class.
What is a Prototype in JavaScript?
Ans: In JavaScript, every object has a hidden internal link to another object called its prototype.
This prototype object can contain shared properties and methods that all instances can access.
We can set the prototype using
This prototype object can contain shared properties and methods that all instances can access.
We can set the prototype using
__proto__
Special keywords of OOP in JS?
Ans:
- new keyword create a new object using class.
- constructor is a special method inside a JavaScript class that gets called automatically when a new object is created from that class.
- this keyword refers to the object that is executing the current function.
- extends keyword using to inherit another class data.
- super keyword using to call the constructor of it's parent class to access parent's properties and method
What are the concepts of 4 pillars in OOP?
Ans:
- Abstraction: Hide complex logic, presenting essential information.
- Encapsulation: Group related data(properties) and methods typically an object or a class. It promotes data hiding, where the internal state of an object is not directly accessible from outside, and access is controlled through methods.
- Inheritance: Inheritance allows one class to inherit the properties and methods of another class, promoting code reusability.
class Parent { parentMethod() {...} } class Child extends Parent{ childMethod() { super.parentMethod(); } } - Polymorphism: Polymorphism means "many forms" — the ability for different classes to define methods with the same name but different behaviors.
What is Method Overriding and Method Overloading?
Ans:
Method Overriding: Method overriding is when a subclass provides a new implementation of a method that is already defined in its parent class.
Method Overloading: Method overloading means defining multiple methods with the same name but different parameters.
Note: Method overloading not supported by JS
Method Overriding: Method overriding is when a subclass provides a new implementation of a method that is already defined in its parent class.
Method Overloading: Method overloading means defining multiple methods with the same name but different parameters.
Note: Method overloading not supported by JS
Getter and Setter in JS?
Ans: Answer pending...
DOM Manipulation Methods
Ans:
* Accessing Elements:
* Accessing Elements:
document.getElementById("id"); // Find element by ID
document.getElementsByClassName("class"); // Find elements by class
document.getElementsByTagName("tag"); // Find elements by tag name
document.querySelector("selector"); // Find first element matching selector
document.querySelectorAll("selector"); // Find all elements matching selector
* Creating / Appending Elements:document.createElement("name"); // Create element node
document.createTextNode("text"); // Create text node
elem.appendChild(child); // Append child to element
elem.removeChild(child); // Remove child from element
elem.replaceChild(newChild, oldChild); // Replace child with new child
* Modifying Elements:elem.innerHTML = "<h2>outerHTML</h2>"; // Set inner HTML
elem.innerText = "inner text"; // Set plain text
elem.textContent = "text content"; // Set text content
elem.style.color = "blue"; // Set inline style
elem.outerHTML = "<p>Learn with <strong>Athreos</strong></p>"; // Replace entire element
JavaScript Tricky Questions & Outputs
Q1:
Result:
Reason: number + string = string
Q2:
Q3:
Q4:
Q5:
Q6:
Result:
Q7:
Q8:
Result:
Q9:
Q10:
Q11:
console.log(1 + '2' + 3);Result:
"123"Reason: number + string = string
Q2:
{1:1} == {1:1} // False[1,2,3] == '1,2,3' // TrueQ3:
console.log("a");
queueMicrotask(() => {
console.log("b");
queueMicrotask(() => {
console.log("c");
});
});
setTimeout(() => console.log("d"), 0);
Promise.resolve().then(() => console.log("e"));
console.log("f");
Result: a f b e c dQ4:
console.log(+true); // 1
console.log(+false); // 0
console.log(true+'1'); // "true1"
console.log(true+1); // 2
console.log(false-'2'); // -2
console.log(false-2); // -2
Q5:
let x = 10;
x(); // trying to call a number
Result: TypeError: x is not a functionQ6:
console.log(typeof NaN)Result:
"number" // NaN means "Not a Number" but is actually of type 'number'Q7:
const person = {
name: "Alex"
};
person = {}; // trying to reassign
Result: TypeErrorQ8:
console.log(typeof null);Result:
"object" // JS bugQ9:
let a = [1, 2, 3];
a[10] = 99;
console.log(a.length);
Result: 11 // setting a value at index 10 makes the length 11, rest will be undefinedQ10:
const obj = {};
obj.name = "Mahesh";
console.log(obj.name);
Result: "Mahesh"Q11:
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
console.log(foo());
Result: [Function: inner] // Returns the inner function, not the value
Create Flat Array?
Ans:
Method 1: Using flat() method:
const nestedArray = [1, [2, [3, [4, 5]]]];
const fullyFlatArray = nestedArray.flat(Infinity);
Method 2: Using recursive function:
function flattenArray(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const flat = flattenArray(arr[i]);
for (let j = 0; j < flat.length; j++) {
result.push(flat[j]);
}
} else {
result.push(arr[i]);
}
}
return result;
}
const nestedArray = [1, [2, [3, [4, 5]]]];
const flatArray = flattenArray(nestedArray);
console.log(flatArray);
Find 2nd largest number?
Ans:
Method 1: Using sort:
let arrayData = [1,8,5,3,4,9,2,7,6]
let array = arrayData.sort((a, b) => {return a-b;})
console.log(array[array.length-2]);
Method 2: Using filter:
let arrayData = [1,8,5,3,4,9,2,7,6]
let maxNum = Math.max(...arrayData)
let newArray = arrayData.filter((x) => x != maxNum)
let newlargest = Math.max(...newArray)
console.log(newlargest)
Sorting the array?
Ans:
Method 1: Using sort() method:
let arrayData = [1,8,5,3,4,9,2,7,6]
let array = arrayData.sort((a, b) => {return a-b;})
Method 2: Bubble Sort:
for (let i = 0; i < arrayData.length - 1; i++) {
for (let j = 0; j < arrayData.length - 1 - i; j++) {
if (arrayData[j] > arrayData[j + 1]) {
const temp = arrayData[j];
arrayData[j] = arrayData[j + 1];
arrayData[j + 1] = temp;
}
}
}
Method 3: Selection Sort:
for(let i = 0; i < arrData.length-1; i++){
for(let j = i+1; j < arrData.length; j++){
if(arrData[i] > arrData[j]){
let temp = arrData[i];
arrData[i] = arrData[j];
arrData[j] = temp
}
}
}
Get Unique number from array?
Ans:
Method 1: Using Set:
let arrayData = [1,2,5,3,4,2,1,5,3,4,1,2]
let array = [...new Set(arrayData)]
console.log(array)
Method 2: Using includes():
let arrayData = [1, 2, 5, 3, 4, 2, 1, 5, 3, 4, 1, 2];
let uniqueArray = [];
for (let i = 0; i < arrayData.length; i++) {
if (!uniqueArray.includes(arrayData[i])) {
uniqueArray.push(arrayData[i]);
}
}
console.log(uniqueArray);
Method 3: Using nested loops:
let arrayData = [1, 2, 5, 3, 4, 2, 1, 5, 3, 4, 1, 2];
let uniqueArray = [];
for (let i = 0; i < array.length; i++) {
let isUnique = true;
for (let j = 0; j < uniqueArray.length; j++) {
if (array[i] === uniqueArray[j]) {
isUnique = false;
break;
}
}
if (isUnique) {
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray);
How to create plain array (Flat Array) of nested loop?
Ans:
Method 1: Using spread operator:
const nestedArray = [1, 2, [3, 4, [5,6]], 7, 8, 9];
let newdata = [1,2, ...[3,4, ...[5,6],7,8,9]]
console.log(newdata)
Method 2: Using flat():
const nestedArray = [1, 2, [3, 4, [5,6]], 7, 8, 9];
let newdata = nestedArray.flat(Infinity)
console.log(newdata)
Method 3: Using recursive function:
const nestedArray = [1, 2, [3, 4, [5,6]], 7, 8, 9];
console.log(flatArray(nestedArray))
function flatArray(arr){
const flattened = [];
arr.forEach(item => {
if (Array.isArray(item)) {
flattened.push(...flatArray(item));
} else {
flattened.push(item);
}
});
return flattened;
}
Reverse array?
Ans:
let arrayData = [1, 2, 5, 3];
let reverseArray = [];
for (let i = arrayData.length-1; i >= 0; i--) {
reverseArray.push(arrayData[i])
}
console.log(reverseArray);
Find the matching records?
Ans: Given:
Expected Output:
words = ["bella","label","roller"]Expected Output:
["e","l","l"]words = ["bella","label","roller"]
temp2=[]
matchResult = words[0].split('')
for(let i = 0; i < words.length; i++){
temp2 = words[i].split('')
var tempData = []
for(let j = 0; j < temp2.length; j++){
var tempmem = matchResult.filter(x => x == temp2[j])[0];
if(tempmem){
tempData.push(tempmem)
}
}
matchResult = tempData
console.log(tempData)
}
Resolve following data operations?
Given Data:
const data = [
{ name: 'Alice', country: 'USA', mobile: '123', salary: 5000 },
{ name: 'Bob', country: 'India', mobile: '456', salary: 3000 },
]
a) Sort by Salary (Ascending):
function output(data){
const newData = [...data].sort((a,b) => a.salary - b.salary)
return newData;
}
b) Group by Unique Country:
// Method 1: Using reduce
function output(data){
let newData = {}
newData = data.reduce((acc, item) => {
acc[item.country] = acc[item.country] || [];
acc[item.country].push(item);
return acc
}, {})
return newData;
}
// Method 2: Using for loop
function output(data){
let newData = {}
for(let i = 0; i < data.length; i++){
let country = data[i].country;
if(!newData[country]){
newData[country] = [];
}
newData[data[i].country].push(data[i])
}
return newData;
}
c) Get First Character of Names and Their Occurrence:
// Method 1: Using reduce
function output(data){
let newData = {}
newData = data.reduce((acc, item) => {
acc[item.name[0].toLowerCase()] = (acc[item.name[0].toLowerCase()] || 0) + 1;
return acc
}, {})
return newData;
}
// Method 2: Using for loop
function output(data){
var result = {};
for (var i = 0; i < data.length; i++) {
var firstChar = data[i].name.charAt(0).toLowerCase();
if (!result[firstChar]) {
result[firstChar] = 0;
}
result[firstChar]++;
}
return result;
}
Get factorial of a number?
Ans: A factorial is a function that multiplies a number by every number below it till 1.
Method 1: Recursive:
Method 1: Recursive:
function factorialRecursive(n) {
if (n < 0) return undefined;
if (n === 0 || n === 1) return 1;
return n * factorialRecursive(n - 1);
}
Method 2: Iterative:
function factorialIterative(n) {
if (n < 0) return undefined;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
Prime Number Check?
Ans: A prime number is a whole number greater than 1 that is only divisible by 1 and itself.
function runTasks(n) {
let isPrime = true;
if (n <= 1) {
isPrime = false;
} else {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
isPrime = false;
break;
}
}
}
return isPrime;
}
console.log(runTasks(7))
Check if a number is a palindrome?
Ans: A palindrome number is a number that remains the same when its digits are reversed.
function isPalindrome(num) {
const str = num.toString();
return str === str.split('').reverse().join('');
}
String character count?
Ans: Given:
stringData="aabbbccddea" and Expected: "3a3b2c2d1e"let str = "aabbbccddea";
let obj = {};
let output = "";
for(let i=0; i < str.length; i++) {
if(obj.hasOwnProperty(str[i])){
obj[str[i]] = obj[str[i]] + 1;
} else{
obj[str[i]] = 1;
}
}
for(let key in obj) {
output = output + obj[key] + key;
}
console.log("output => ", output);
Function context and 'this' keyword?
Q1:
Q2:
function abc(){
var a1='def';
this.name = 'abc'
}
a = new abc();
console.log(a.a1); // undefined (a1 is not a property of the instance)
console.log(a.name); // "abc"
Q2:
function something() {
this.hello = "hello";
console.log(this.hello, this.who);
}
var who = "global",
foobar,
bazbam,
obj1 = { who: "obj1", something },
obj2 = { who: "obj2", something };
something(); // "hello undefined" (this refers to global, this.who is undefined)
console.log(hello); // "hello" (created on global object)
obj1.something(); // "hello obj1"
console.log(obj1.hello) // "hello"
obj2.something(); // "hello obj2"
console.log(obj2.hello); // "hello"