0% found this document useful (0 votes)
39 views16 pages

Js Questions

The document provides an overview of JavaScript data types, including primitive and non-primitive types, and explains concepts such as pure and impure functions, hoisting, and callback functions. It also covers advanced topics like currying, destructuring, promises, and the differences between various array methods. Additionally, it discusses Babel and JSX, highlighting their roles in modern JavaScript development.

Uploaded by

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

Js Questions

The document provides an overview of JavaScript data types, including primitive and non-primitive types, and explains concepts such as pure and impure functions, hoisting, and callback functions. It also covers advanced topics like currying, destructuring, promises, and the differences between various array methods. Additionally, it discusses Babel and JSX, highlighting their roles in modern JavaScript development.

Uploaded by

rootworld1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) What are data types js support?

 a) primitive Data types->


These are stored by values Stored directly in stack and these are immutable.

Type Example Description

All numbers (integers and floats


Number 42, 3.14, -0,NaN
double precision 64 bit)

String "hello", 'world' Text values

Boolean true, false Logical values

Undefined let x; A declared variable with no value

Null let x = null; Intentional absence of value

Unique and immutable identifiers


Symbol Symbol("id")
(ES6)

BigInt 12345678901234567890n For large integers beyond 2^53 - 1

b) Non Primitive data types->


These are stored by reference stored in heap section and these are mutable,

Type Example Description

Object { name: "Nikhil", age: 21 } Key-value pairs of data

Array [1, 2, 3] Ordered list of items

Function function greet() {} Callable objects

Date new Date() Special object for date/time

RegExp /abc/ Regular expressions

Map/Set new Map(), new Set() Key-value/unique value stores

2) What are pure functions and impure functions in js?


 A pure function is a function that for given same input returns always same output. Means
have no side effects. It does not modify external state (variables, DOM, files, databases,
etc.).

function add(a, b) {
return a + b;
}

console.log(add(2, 3)); // 5
console.log(add(2, 3)); // 5 (same input → same output)

pure functions are easy to test , debug, and easy to parallelize and memorize.
An impure function is a function that may return different outputs for the same input, OR
has side effects such as:
o Modifying a global variable
o Changing the DOM
o Logging to the console
o Writing to a file or database
o Fetching data (API call)

let count = 0;

function increment() {
count++; // modifies external state
return count;
}

console.log(increment()); //1
console.log(increment()); // 2

3) const arr=[,,,]
console.log(arr.length)
 Each comma represents a gap between items in array like [2,3,4] — so:
Here no element is present , just commas, so three empty slot is there (not undifned values)
Array length = number of gaps + 1, unless you omit the last item.
So here 3 is the right answer.

4) What will be output of-> console.log(1+1+’1’)?


 step-by-step evaluation (left-to-right, due to associativity of +):
1 + 1 → both numbers → normal addition → result: 2 (number)
2 + '1' → number + string → string concatenation → result: '21' (string)

5) console.log(1-‘1’)
 - or * never does string concatenation, it forces numeric conversion on both operands
1 (number) - '1' (string) → '1' gets converted to number → 1 - 1
Result: 0 (number)

6) What is hoisting?
 Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top
of their scope (either global or function scope) during the compilation phase.
🟡 Example with var:

console.log(a); // undefined (not error!)


var a = 5;

What actually happens behind the scenes:->


var a;
console.log(a); // undefined
a = 5;
So, the declaration var a is hoisted, but not the assignment = 5.
🟡 let and const are also hoisted, but:
They are hoisted to the top of their block.

BUT they are not initialized until the line where they're declared.

Accessing them before initialization causes a ReferenceError (called the Temporal Dead
Zone).
console.log(b); // ❌ ReferenceError
let b = 10;

🟡 Function declarations are fully hoisted:

greet(); // ✅ Works fine

function greet() {
console.log("Hello");
}

But be careful with function expressions as function expression or


arrow functions are not hoisted:

greet(); // ❌ TypeError: greet is not a function

var greet = function() {


console.log("Hi");
};
Why? Because var greet is hoisted as undefined, so at the time of greet(),
it's not a function yet.

7) How to delete all element from array in very fast way?


 let arr=[1,2,3]
console.log(arr) //prints [1,2,3]
arr.length=0;
console.log(arr) //prints []

This does not just hide the values — it truncates the array.

8) let name=”Nikhil”
function fn(){
console.log(name);
let name=”Hello”
}
fn()
 Here give reference error, as in name has declared as let so it has hoisting
property for this the definition is move to the top of the scope, means from
where function start, so it shadow the outside the name variable, finally as
let variable can’t be accessed before initialization , that’s why it give
reference error.
9) abc();
var abc = () => {
console.log(1);
}
abc();
function abc() {
console.log(2);
}
abc();
 If a function declaration and a var declaration share the same name, the
function binding “wins” initially. The later var declaration line itself does
nothing (it sees the name already exists), but any later assignment to that var
name in the execution phase can overwrite the function reference.

After hoisting code look like,

function abc(){
console.log(2)
}
var abc; //does nothing new (name already exists) and does NOT overwrite the function
at this stage.
abc(); //here abc as function invocation so it prints 2;
abc=()=>{
console.log(1);
}
abc() //now as abc is reassigned with arrow function so it prints 1.
abc() //similarly here also 1 is printed.

10) What is Callback function?


 Function that is passed into higher order function.

11) What are closures?


 A closure is formed when an inner function accesses variables from an outer function, even
after the outer function has returned.
Can be used for data hiding.

12) What is web api? b/w setInterval and setTimeOut which one is registered in web api?
 A Web API is a set of built-in features provided by the browser (or environment like
Node.js) that allows JavaScript to interact with things outside the JS engine, like:
Timers,Dom manipulation, network req(fetch, XMLHttpRequest) , Storage (localStorage,
sessionStorage), Geolocation, camera, notifications etc.

Both setTimeout and setInterval are registered in the Web API environment (like browser
or Node.js). But:
setTimeout is registered once, and once it fires, it’s cleared automatically.
setInterval remains registered until I clear it by clearInterval() or the program exits.
🔥 So, setInterval remains in the Web API until explicitly cleared or the process ends, while
setTimeout is removed after one execution.

13) What callback function map method take?


 array.map(function(currentValue, index, array) {
// return new value
})

Here index and array is optional, and array is the original array which is processed and index
is the position of the currentValue in original array.

14) Difference b/w map and forEach method?


 map() transforms each element & returns a new array,
foreach() executes a function on each item but returns undefined

15) What is the use of find() method?


 This method take callback as argument and check the callback condition on each element on
the array, and returns the first element if there, else return undefined.

const nums = [5, 12, 8, 130, 44];


const found = nums.find(num => num > 10);
console.log(found); // 12 (not 130!)

16) Console.log(NaN===NaN) output?


 NaN stands for "Not a Number"
According to the IEEE 754 floating point standard, NaN is not equal to anything, including
itself.

so the answer is false.

NaN is a special numeric value that indicates a failed number operation, like:
let x = 0 / 0; // NaN
let y = parseInt("abc"); // NaN

17) what will be output?


let x={}, y={name:'Satish'},z={name:'Pratik'}
x[y]={name: 'Salman'}
x[z]={name:'ShahRukh'}
console.log(x[y])
 In JavaScript, object keys can only be strings or symbols.
When you use an object as a key, JavaScript converts it to a string using .toString().
y.toString(); // "[object Object]"
z.toString(); // "[object Object]"

so,
x[y] → x["[object Object]"]
x[z] → x["[object Object]"] ← overwrites the previous value!
so the output will be {name:'ShahRukh'}

18) console.log(1>2<3)
 Output -> true,
as according to associativity first left side operator is evaluated, so 1>2 is false,
and in javascript false is represented by 0,
so 0<3 that is true.

19) What is function currying?


 Currying is a technique of transforming a function with multiple arguments into a series of
functions, each taking one argument at a time.

Examples 1->
function greet(greeting) {
return function(name) {
return `${greeting}, ${name}!`;
};
}

const sayHello = greet("Hello"); // returns a new function


console.log(sayHello("Nikhil")); // "Hello, Nikhil!"
console.log(sayHello("Aman")); // "Hello, Aman!"

Examples 2->
const multiply = a => b => c => a * b * c;
console.log(multiply(2)(3)(4)); // 24

this function currying helps to create specialized functions from general ones and pre fill
arguments.

20) Give an example of infinte currying?


 Currying is when a function takes multiple arguments one by one instead of all at once.
Infinite currying extends this idea, where the function keeps accepting arguments
indefinitely until we explicitly stop it (e.g., by calling it without arguments).

Example->
function add(a) {
return function (b) {
if (b !== undefined) {
return add(a + b); // Keep chaining
}
return a; // When no argument is passed, return result
};
}

console.log(add(1)(2)(3)(4)()); // 10

How This Works?


add(1) → returns function(b).
add(1)(2) → a=1, b=2, calls add(3).
add(1)(2)(3) → a=3, b=3, calls add(6).
When we call with no argument (), the function returns the accumulated value.

21) function sub(){


}
console.log(sub(3,2));
console.log(sub(3)(2));
You have to right sub function such a way that both console.log give 1 value as subtraction
happens?
 function sub(a,b){
if(b){
return a-b;
}else{
return function(c){
return a-c;
}
}
}

22) What is destructuring?


 Destructuring is a syntax that lets you unpack values from arrays or extract properties from
objects into distinct variables.

An exciting example of swapping two numbers->

let a=4,b=6;
[b,a]=[a,b] //here right side is an array [a,b] =>[4,6] , which is destructured in b,a variable.
console.log(a) //it is 6
console.log(b) //it is 4

23) What is rest parameter?


 The rest parameter (...) allows a function to accept any number of arguments as an array.
function myFunc(...args) {
console.log(args); // an array of all arguments passed
}

24) const arr=[1,2,3]


[a]=arr;
console.log(a)
 here output is 1, as during destructuring from first element is assigned to left side, so first 1
is assigned.

25) What is Babel?


 Babel is a JavaScript compiler that allows you to write modern JavaScript (ES6 and beyond)
and transpile it into backward-compatible JavaScript that works in older browsers or
environments.
Modern JavaScript (ES6+) includes features like:
Arrow functions (=>)
let and const
Template literals (Hello ${name})
Classes, modules
Optional chaining (obj?.prop)
Nullish coalescing (??)
JSX (in React)
Older browsers like Internet Explorer do not understand these. Babel helps by converting
your code into a format those browsers can execute.

26) What is jsx?


 JSX stands for Javascript xml. Instead of using React.createElement(...), JSX lets you write
HTML-like code in your JavaScript files
return (
<div>
<h1>Hello</h1>
<p>World</p>
</div>
);
Here for property insertion in component we have to use className (as class is keyword for
js)

27) What is promise? And what are the states of promises?


 A Promise is a built-in JavaScript object that represents the eventual result (or failure) of an
asynchronous operation.

A JavaScript Promise can exist in one of three distinct states:


Pending:
This is the initial state of a Promise. The asynchronous operation it represents has not yet
completed, meaning it has neither succeeded nor failed.
Fulfilled
(also known as Resolved): This state indicates that the asynchronous operation completed
successfully. The Promise now holds a resulting value.
Rejected:
This state signifies that the asynchronous operation failed. The Promise now holds a reason
or error object indicating why the operation failed.

28) What is callback hell? How promise helps to remove it?


 Callback Hell happens when you have nested callbacks that become hard to read, maintain,
and debug.
Example of callback hell->
getUser((user) => {
getPosts(user.id, (posts) => {
getComments(posts[0].id, (comments) => {
console.log("First post's first comment:", comments[0]);
});
});
});
As one can see, each function nests inside another — this pyramid of doom becomes
unreadable and error-prone.

With Promises, you can chain asynchronous tasks linearly — flattening the structure.
getUser()
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log("First comment:", comments[0]))
.catch(err => console.error("Error:", err));

29) What is lexical scope in javascript?


 Lexical Scope means that a variable’s accessibility is determined by its physical location in
the source code — i.e., where it's written (its "lexical" location).

30) What are template literals?


 Template literals are a modern way to create strings in JavaScript, introduced in ES6.
They make string construction easier, cleaner, and more powerful — especially when
combining variables and expressions.
Template literals use backticks ( ` ) instead of quotes (" or ').

By this one can->

i)String interpolation:- `The price of ${product} is ₹${price}`

ii)Multi line strings

iii) Expression and function call inside template literals :- `Sum: ${a + b}`

31) Difference between slice and splice method on array?


 Slice method returns a copy of array with element inside the bound passed in parameter.
Splice modifies original array delete elements inside the bound passed in parameter and add
elements passed as parameter returns an array with the deleted element.

array.slice->
const fruits = ["apple", "banana", "cherry", "date"];
const result = fruits.slice(1, 3);
console.log(result); // ["banana", "cherry"]
console.log(fruits); // ["apple", "banana", "cherry", "date"] — original intact

array.splice->
const fruits = ["apple", "banana", "cherry", "date"];
const removed = fruits.splice(1, 2, "kiwi", "mango"); //here 1 is start, 2 is delete count, all
remainings are just addable to new array
console.log(removed); // ["banana", "cherry"]
console.log(fruits); // ["apple", "kiwi", "mango", "date"]

32) What is event loop?


 The event loop is the mechanism in JavaScript that coordinates the execution of
synchronous and asynchronous code.

Event loop order->


Execute all synchronous code (in call stack)
Run all microtasks (like .then() of Promises)
Run one macrotask (like setTimeout)
Repeat

33) Why promises get higher priority than setTimeOut or setInterval?


 Because promises (and microtasks) are designed to handle immediate next-step logic that
needs to happen right after the current operation, before the browser goes on to next big
tasks like repainting, timers, or event handling.
So they are given higher priority in the event loop cycle.

34) What is code splitting?


 Code splitting is a performance optimization technique where you break your JavaScript
bundle into smaller chunks — so the browser only loads what's needed, when it's needed.

By default, tools like Webpack or Vite bundle your entire app into one large file (bundle.js).
As your app grows, this bundle becomes heavy and slow to load.
✅ Code splitting helps:
 Reduce initial load time
 Improve performance
 Load routes or components only when needed

35) What is difference between ‘==’ and ‘===’ in js?


 The == operator performs loose equality comparison with type coercion. This means
JavaScript automatically converts one or both operands to the same type before comparing
their values (in case of non-primitive data types not values just references).

'5' == 5 // true (string '5' converted to number 5)


0 == false // true (false converted to 0)
null == undefined // true (special rule)
[] == '' // true (both become empty string)

The === operator performs strict equality comparison without type coercion. It checks both
the value (in case of non-primitive data types not values just references) and the data type,
requiring them to be exactly the same.
All the above examples are false in case of === operator.

[]==[] or []===[] in case of both ans is false as here these are non-primitive data type so they
are compared by reference. And they are different objects.
Similary, [1]==[1] or [1]===[1]

36) console.log(() => {} !== () => {})


 Every function declaration creates a new object, even if the code is the same.
So that’s why it is true.

37) function abc(a,b,c){}


function xyz(a,b=0,c){}
function mno(a=0,b,c){}
console.log(abc.length)
console.log(xyz.length)
console.log(mno.length)
 The Function.length property in JavaScript returns the number of parameters expected by a
function and key rule is just count how many parameters are there before first default
parameter.
so that’s why 3,1,0 are the outputs respectively.

38) What is difference between fetch and axios?


Feature fetch() (Built-in) axios (External Library)

External library (npm install


✅ Availability Built-in browser API
axios)

📦 File size No extra size Adds to your bundle size

✍️Syntax Verbose (manual JSON


Cleaner, simpler syntax
simplicity parsing, error checks)

🧠 Auto JSON ✅ Automatically parses


❌ You must use .json()
parse response to JSON

⚠️Error Doesn't throw on HTTP ✅ Throws errors on HTTP


handling errors (like 404) status codes

fetch('https://api.example.com/user')
.then(response => {
if (!response.ok) throw new Error("HTTP error " + response.status); //manual check
return response.json(); //manual conversion of response to json
})
.then(data => console.log(data))
.catch(error => console.error(error));

import axios from 'axios';

axios.get('https://api.example.com/user')
.then(response => {
console.log(response.data); // no need for `.json()` and also throwing http errors.
})
.catch(error => {
console.error(error);
})

39) How request cancellation done in axios and fetch?


 Request cancellation is important when you want to abort unnecessary network requests —
for example, when a user types in a search box, and you only want the latest request to
complete while canceling the previous ones.

Axios has built-in support for cancellation using AbortController (newer versions) or the
deprecated CancelToken (older versions).
import axios from "axios";

const controller = new AbortController();

axios
.get("https://api.example.com/data", { signal: controller.signal })
.then((response) => console.log(response))
.catch((error) => {
if (axios.isCancel(error)) {
console.log("Request canceled", error.message);
} else {
console.error(error);
}
});

// Cancel the request


controller.abort();

The fetch API uses the AbortController interface for cancellation.


const controller = new AbortController();
const signal = controller.signal;

fetch("https://api.example.com/data", { signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => {
if (err.name === "AbortError") {
console.log("Fetch aborted");
} else {
console.error(err);
}
});

// Cancel the request


controller.abort();

40) What is web workers?


 Web Workers are a feature in the browser that allow you to run JavaScript code in the
background, on a separate thread from the main UI thread.
🚀 Why Use Web Workers?
JavaScript is single-threaded, so long-running tasks (like:
heavy computation,
data parsing,
image processing,
real-time data updates)
can block the UI and make the page unresponsive.
Web Workers let you offload these tasks to a background thread, keeping the UI smooth
and responsive.

main.js:
const worker = new Worker('worker.js');

worker.postMessage('start');

worker.onmessage = function(event) {
console.log('Result from worker:', event.data);
};

worker.js:
onmessage = function(event) {
if (event.data === 'start') {
// Heavy computation
let sum = 0;
for (let i = 0; i < 1e9; i++) sum += i;
postMessage(sum); // Send result back to main thread
}
};

Limitations->
i) Web worker can’t access dom.
ii) Heavy memory: Each worker has its own context
iii) Same-origin policy applies

41) Give some cases where arrow functions can’t be used?


 Below are the cases where we can’t use arrow fucntions->

1) Object Methods (when you need this):-


Arrow functions do not have their own this.
They inherit this from the surrounding lexical scope, which can break method behavior.
Example->
const person = {
name: "Nikhil",
greet: () => {
console.log(`Hello, ${this.name}`); // ❌ `this` is undefined or window
}
};
person.greet(); // Hello, undefined

2) Using arguments Object:-


Arrow functions don’t have arguments, so you can’t access passed arguments
dynamically.
Example->
const add = () => {
console.log(arguments); // ❌ ReferenceError
};
add(1, 2, 3);

3) Constructor Functions:-
Arrow functions cannot be used with new because they lack [[Construct]].
Example->
const User = (name) => {
this.name = name;
};
const u = new User("Nikhil"); // ❌ TypeError: User is not a constructor

42) How to add javascript gloabally to react js so one can need to import any module?
 Assign property to window, and access anywhere in the component.

window.myGlobalFunc = () => console.log("I'm global");

Now in any component just use it.

The reason you can assign a property like window.myGlobalFunc is because JavaScript
objects are dynamic and follow the prototype chain. The window object is essentially the
global object in browsers, and adding a property to it makes it globally accessible.

43) What is optional chaining?


 Optional chaining (?.) is a feature in JavaScript (introduced in ES2020) that allows you to
safely access deeply nested object properties without having to manually check if each
reference in the chain is null or undefined.

Two different method printing user.profile.name handling null or undefined values also->

i) console.log(user && user.profile && user.profile.name); //with out optional chaining .


ii) console.log(user?.profile?.name); //with optional chaining.

44) Difference b/w installing process by npm and by cdn?


 Through npm I have to download the packages to local node_modules folder and add a
reference to package.json file, and When I import axios from "axios", bundlers like
Webpack/Vite include Axios in my final build bundle.

But using cdn(content delivery network) , I don’t need to download anything locally, I just
include a <script> tag pointing to a hosted version:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
The browser fetches Axios directly from the CDN server (like jsDelivr, unpkg, or cdnjs).
It is great for quick testing or small html project.

45) How many type of export is there? What is difference b/w them?
 Two export->
1) default export:
Used when you want to export a single main value from a module.
You can import with any name
Only one default export is allowed per file
2) Named export:
You must use the exact name during import
You can have multiple named exports
You can rename while importing using as

46) What is tilda(~) and caret(^) operator?


 "axios": "^1.2.3"
Here caret operator is used which means: install any version >= 1.2.3 but < 2.0.0.
It allows minor and patch updates, but not major updates.
For example, it could update to 1.3.0 or 1.2.5, but not 2.0.0 because that’s a breaking
change.

"axios": "~1.2.3"
Here tilda operator is used which means: install any version >= 1.2.3 but < 1.3.0.
It only allows patch updates (last digit), but not minor updates.
For example, it could update to 1.2.4 or 1.2.9, but not 1.3.0.

"axios": "1.2.3"
Here no operator is used. It means: install exactly version 1.2.3 — no updates allowed
automatically.

47) Diff b/w localStorage and sessionStorage?


 Both are part of webStorage api and used to store key-value data in browser.

Feature localStorage sessionStorage

Persists only during the


Persistence Persists until manually cleared
session/tab

✅ Cleared when tab/window


Expiration ❌ No expiration (stored forever)
is closed

Storage
~5-10 MB (varies by browser) ~5 MB
limit

Shared across tabs/windows of Isolated to the specific


Scope
same origin tab/window

API Same (setItem, getItem, Same (setItem, getItem,


Feature localStorage sessionStorage

removeItem) removeItem)

48) Difference b/w debouncing and throttling?


 Debouncing waits until activity stops and then runs once.
It is used in search box, auto save draft, resize events.
How it works:
Every time the event is triggered, it resets a timer.
Only when the event stops firing for a set time, the function is run.

Throttling runs the function at regular intervals, regardless of how many times the event
fires.
It is used Scroll events, Mouse move or drag events
How it works:
Once the function runs, it won’t run again until the set time passes, even if the
event keeps firing.
Example->
Below even if the user scrolls wildly, the function runs only once every 500ms.
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}

const handleScroll = throttle(() => {


console.log("Scroll event");
}, 500);

You might also like