JavaScript Interview Guide
JavaScript Interview Guide
Important :
In interviews, mostly interviewers will focus on 5 areas.
So, we can just assign anything to the variable and it works fine.
let a; a = 0; console.log(a) //
0 a = "Hello" console.log(a)
// "Hello"
Str ing
number
boolean
null
undefined
Bigint
symbol
Non-Primitive datatypes:
Object
Ar ray
Date
In javascript, variables and functions can be used before declaring it. The
javascript compiler moves all the declarations of variables and functions on
top. so there will not be any error. This is called hoisting.
👉 Interview Tip: Mention buzz word temporal dead zone in above answer so that
interviewer will ask What is temporal dead zone. 😉
Ref: https://stackabuse.com/hoisting-in-javascript/
6. What are the differences let, var and const ? (Most asked)
Variables declared with var are function scoped.( available through out the
function where its declared ) or global scoped( if defined outside the
function ).
Reassignment:
Hoisting:
let and const - gets hoisted to the top of the scope but does not get
assigned any value.(temporal dead zone)
Destructuring assignment
Default parameters
Template literals
Promises
Classes
Modules
Arrow function does not have their own this. Instead, they inherit this from the
surrounding code at the time the function is defined.
Arrow functions cannot be used as constructors. Using them with the 𝙣𝙚𝙬
keyword to create instances throws a TypeError.
👉 Note: Arrow functions + this combination questions will be asked here. Please
explore on this combinations.
Concatenating arrays.
function createExample(arg1,arg2){
console.log(arg1,arg2);
}
createExample(…a)
👉 Interview Tip: Practice the above examples mentioned and showcase them in
interviews to make interviewer think that you are a practical person. 😉
function Example(...args){
console.log(args)
}
Example(1,2,3,4);
const user = {
"age": 10,
"name": "Saikrishna"
}
Map is the collection of key value pairs Set is a collection of unique values
Map is two dimensional Set is one dimensional
Eg: Eg:
Ref: https://javascript.info/map-set
Modules can be imported and exported using import and export statements.
function changeNum(value) {
value = 20;
console.log(value); // Output: 20
}
changeNum(num);
console.log(num); // Output: 10
function addToArr(value) {
value.push(4);
console.log(value); // Output: [1, 2, 3, 4]
}
map method will return a new array with the transformed values. forEach
method does not return a new array.
map method can be used with other array methods like filter method. whereas
forEach method cannot be used with other array methods as it does not return
any array.
for-in:
for-of:
https://stackoverflow.com/questions/29285897/difference-between-for-in-and-
for-of-statements?answertab=scoredesc#tab-top
It will return the first element of array that passes specified condition.
function findMethod(){
let arr = [{id:1,name:"sai"},{id:2,name:"krishna"}];
let data = arr.find(x=> x.id==2)
console.log(data)
}
findMethod()
Output:
{id:2,name:"krishna"}
findIndex:
It will return the index of first element of an array that passes the specified
condition.
function findMethod(){
let arr = [{id:1,name:"sai"},{id:2,name:"krishna"}];
let data = arr.findIndex(x=> x.id==2)
console.log(data)
}
findMethod()
Pure functions are the functions which will return same output for same
arguments passed to the function.
This will not have any side effects.
Impure Functions:
Impure functions are the functions which will return inconsistent output for
same arguments passed to the function.
This will have side effects.
Ref: https://www.scaler.com/topics/pure-function-in-javascript/
Call method will invokes the function immediately with the given this value and
allow us to pass the arguments one by one with comma separator.
Apply method will invokes the function immediately with given this value and
allow us to pass the arguments as an array.
Bind method will return a new function with the given this value and
arguments which can be invoked later.
Brief examples:
The only difference between call and apply is that syntax of how we pass the
arguments.
bind This gives us a copy which can be invoked or executed later rather than
directly invoking it whereever we are writing this line of code.
Object literal :
let userDetails = {
name: "Saikrishna",
city: "Hyderabad"
}
Object constructor :
Object.Create() :
let animal = {
name: "Animal name"
}
Object.assign() :
This is used when we want to include properties from multiple other objects
into new object we are creating.
let lesson = {
lessonName: "Data structures"
};
let teacher= {
teacher: "Saikrishna"
};
Object.keys(data) // ["name","lang"]
Object.values(data) // ["Sai","english"]
Object.entries(data) // [["name","Sai"],["lang","English"]]
Will make the object immutable ( prevents the addition of new propeties
and prevents modification of existing properties)
let data = {
a : 10
};
Object.freeze(data);
data.a= 20;
data.c = 30;
console.log(data)
output: {
a: 10
}
Object.Seal():
let data = {
a : 10
};
Object.seal(data);
data.a = 20; data.c =
30;
console.log(data)
Output:
data: {
a: 20
}
data.forEach((item,i)=>{
console.log(item,i)
Array.prototype.forEach((callback)=>{
for(let i=0;i<=this.length-1;i++){
callback(this[i],i)
}
})
Array.prototype.map=((callback)=>{
let temp = [];
for(let i=0;i<=this.length-1;i++){
temp.push(callback(this[i]))
}
return temp;
})
console.log(output)
ref: https://dev.to/umerjaved178/polyfills-for-foreach-map-filter-reduce-in-
javascr ipt-1h13
function Student(){
this.name = "Saikrishna",
this.exp= "8"
}
Student.prototype.company = "Hexagon"
console.log(std1);
console.log(std2)
They are defined by using function* and it contains one or more yield
expressions.
The main method of generator is next(). when called, it runs the execution until
the nearest yield.
It returns an object which contains 2 properties. i.e., done and value.
https://javascript.info/generators
functions which are executed immediately once they are mounted to the stack
is called iife.
They does not require any explicit call to invoke the function.
https://www.geeksforgeeks.org/immediately-invoked-function-expressions-
iife-in-javascript/
https://www.tutorialsteacher.com/javascript/immediately-invoked-function-
expression-iife
(function(){
console.log("2222")
})()
https://dev.to/lydiahallie/cs-visualized-cors-5b8h
Typescript is the superset of javascript and has all the object oriented
features.
Javascript is a dynamically typed language whereas typescript is a statically
typed language.
Typescript is better suited for large scale applications where as javascript is
suited for small scale applications.
Typescript points out the compilation errors at the time of development.
Because of this, getting runtime errors is less likely.
Typescript supports interfaces whereas javascript does not.
Authorization:
Its the process of verifying what they have access to. What files and data
user has access to.
👉 Interview Tip: For this question, learn jwt token mechanism and tell that you
have implemented this in your project. This helps a lot.This kills atleast 34 min of
interview time 😉
https://www.youtube.com/watch?v=7Q17ubqLfaM
Undefined:
means the variable has been declared but not assigned any value yet.
console.log(newArr) // [2,3]
Splice:
console.log(arr); // [1,2,8,9,6,10]
console.log(newArr); // [3,4,5,0]
setTimeOut(function(){
console.log("Prints Hello after 2 seconds")
👉 Interview Tip: Most asked in output based and problem solving so learn
syntax more. Practice some examples.
setInterval(function(){
console.log("Prints Hello after every 2 seconds");
},2000);
👉 Interview Tip: Most asked in output based and problem solving so learn
syntax more. Practice some examples.
promise.then((response)=>{
console.log("success",response)
}).catch((err)=>{
console.log("failed",err)
})
Will wait for all of the promises to resolve or any one of the promise
reject.
Promise.allSettled:
Will wait for all the promises to settle (either fulfilled or rejected).
Will return if any one of the promise fulfills or rejects when all the
promises are rejected.
Promise.race:
https://medium.com/@log2jeet24/javascript-different-types-of-promise-
object-methods-to-handle-the-asynchronous-call-fc93d1506574
👉 Interview Tip: practice some examples on this concepts. This is a practical
question. You can expect some scenario based questions from interviewer on
this concept so prepare well from above link
Each and every function in javascript has access to its outer lexical
environment means access to the variables and functions present in the
environments of its parents
Usecases:
setTimeOut
function Print(){
console.log("Print method");
}
function Hello(Print){
console.log("Hello method");
Hello(Print);
Output:
Hello method
Print method
Advantages:
callback functions
Abstraction
Code reusability
Encapsulation
Ref: https://developer.mozilla.org/en-
US/docs/Web/API/Web_Storage_API#concepts_and_usage
SessionStorage:
All the scenarios are covered here so 100% sure nothing more than this will
be asked. 😊😊
𝟏. 𝐈 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 𝐚 𝐥𝐨𝐜𝐚𝐥𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐚𝐧𝐝 𝐜𝐥𝐨𝐬𝐞𝐝 𝐭𝐡𝐞 𝐛𝐫𝐨𝐰𝐬𝐞𝐫 𝐚𝐧𝐝 𝐫𝐞𝐩𝐨𝐞𝐧𝐞𝐝 𝐢𝐭. 𝐖𝐢𝐥𝐥 𝐥𝐨𝐜𝐚𝐥 𝐬𝐭𝐨𝐫𝐚𝐠𝐞
𝐝𝐚𝐭𝐚 𝐩𝐞𝐫𝐬𝐢𝐬𝐭𝐬 ?
Yes local storage data persists even when i close and reopen the browser
𝟐. 𝐈 𝐰𝐚𝐧𝐭 𝐭𝐨 𝐚𝐜𝐜𝐞𝐬𝐬 𝐋𝐨𝐜𝐚𝐥 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐢𝐧 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐭𝐚𝐛 𝐨𝐟 𝐬𝐚𝐦𝐞 𝐛𝐫𝐨𝐰𝐬𝐞𝐫 𝐢𝐬 𝐢𝐭 𝐩𝐨𝐬𝐬𝐢𝐛𝐥𝐞 ?
I can access local storage data even for different windows with same url.
𝟔. 𝐖𝐡𝐞𝐧 𝐥𝐨𝐜𝐚𝐥 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐫𝐞𝐦𝐨𝐯𝐞𝐝 ?
30
𝟏𝟎. 𝐈 𝐰𝐢𝐥𝐥 𝐭𝐫𝐲 𝐭𝐨 𝐬𝐭𝐨𝐫𝐞 𝐥𝐞𝐭𝐬 𝐬𝐚𝐲 𝐚𝐧 𝐢𝐦𝐚𝐠𝐞 𝐨𝐟 𝐬𝐢𝐳𝐞 𝐦𝐨𝐫𝐞 𝐭𝐡𝐚𝐧 𝟓𝐦𝐛 𝐢𝐧 𝐥𝐨𝐜𝐚𝐥𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐭𝐡𝐞𝐧
𝐰𝐡𝐚𝐭 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 ?
Yes localstorage data still persists even if i shutdown my laptop and reopen
the browser
All the scenarios are covered here so 100% sure nothing more than this will
be asked. 😊😊
𝟏 .𝐈 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 𝐚 𝐬𝐞𝐬𝐬𝐢𝐨𝐧𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐚𝐧𝐝 𝐜𝐥𝐨𝐬𝐞𝐝 𝐭𝐡𝐞 𝐛𝐫𝐨𝐰𝐬𝐞𝐫 𝐚𝐧𝐝 𝐫𝐞𝐩𝐨𝐞𝐧𝐞𝐝 𝐢𝐭 𝐚𝐧𝐝 𝐫𝐞𝐬𝐭𝐨𝐫𝐞𝐝 𝐭𝐚𝐛 .
𝐖𝐢𝐥𝐥 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐩𝐞𝐫𝐬𝐢𝐬𝐭𝐬 ?
No session storage data does not persists on browser close & reopen.
𝟏 .𝐈 𝐜𝐫𝐞𝐚𝐭𝐞𝐝 𝐚 𝐬𝐞𝐬𝐬𝐢𝐨𝐧𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐚𝐧𝐝 𝐜𝐥𝐨𝐬𝐞𝐝 𝐭𝐡𝐞 𝐛𝐫𝐨𝐰𝐬𝐞𝐫 𝐚𝐧𝐝 𝐫𝐞𝐩𝐨𝐞𝐧𝐞𝐝 𝐢𝐭 𝐚𝐧𝐝 𝐫𝐞𝐬𝐭𝐨𝐫𝐞𝐝 𝐭𝐚𝐛 .
𝐖𝐢𝐥𝐥 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐩𝐞𝐫𝐬𝐢𝐬𝐭𝐬 ?
No session storage data does not persists on browser close & reopen.
𝟐. 𝐂𝐚𝐧 𝐢 𝐚𝐜𝐜𝐞𝐬𝐬 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐢𝐧 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐭𝐚𝐛 𝐨𝐟 𝐬𝐚𝐦𝐞 𝐛𝐫𝐨𝐰𝐬𝐞𝐫 ?
No we cannot access session storage data of one tab in another tab.
𝟑. 𝐈 𝐫𝐞𝐥𝐨𝐚𝐝𝐞𝐝 𝐭𝐡𝐞 𝐩𝐚𝐠𝐞 𝐚𝐟𝐭𝐞𝐫 𝐜𝐫𝐞𝐚𝐭𝐢𝐧𝐠 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞. 𝐖𝐢𝐥𝐥 𝐢𝐭 𝐩𝐞𝐫𝐬𝐢𝐬𝐭𝐬 ?
Yes session storage data persists on page reload.
𝟒. 𝐈𝐟 𝐢 𝐨𝐩𝐞𝐧 𝐦𝐮𝐥𝐭𝐢𝐩𝐥𝐞 𝐭𝐚𝐛𝐬 𝐰𝐢𝐭𝐡 𝐬𝐚𝐦𝐞 𝐮𝐫𝐥 𝐡𝐨𝐰 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐛𝐞𝐡𝐚𝐯𝐞𝐬 ?
We cannot access session storage data in multiple tabs even if its same url
𝟓. 𝐈𝐟 𝐢 𝐨𝐩𝐞𝐧 𝐦𝐮𝐥𝐭𝐢𝐩𝐥𝐞 𝐰𝐢𝐧𝐝𝐨𝐰𝐬 𝐰𝐢𝐭𝐡 𝐬𝐚𝐦𝐞 𝐮𝐫𝐥 𝐡𝐨𝐰 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐛𝐞𝐡𝐚𝐯𝐞𝐬 ?
We cannot access session storage data in multiple windows even if its same
url
31
𝟔. 𝐖𝐡𝐞𝐧 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐝𝐚𝐭𝐚 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐫𝐞𝐦𝐨𝐯𝐞𝐝 ?
once tab closes or session ends session storage data will be removed.
𝟕. 𝐈𝐬 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐨𝐫 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 ?
Session storage is synchronous. If i perform operations on session storage, It
blocks the execution of other javascript code until the current operation is
completed.
𝟖. 𝐈 𝐰𝐚𝐧𝐭 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐨𝐩𝐞𝐫𝐚𝐭𝐢𝐨𝐧𝐬 𝐚𝐧𝐝 𝐥𝐚𝐫𝐠𝐞 𝐝𝐚𝐭𝐚 𝐬𝐞𝐭𝐬 𝐭𝐨 𝐛𝐞 𝐬𝐭𝐨𝐫𝐞𝐝 𝐭𝐡𝐞𝐧 𝐰𝐡𝐚𝐭 𝐲𝐨𝐮 𝐰𝐢𝐥𝐥
𝐬𝐮𝐠𝐠𝐞𝐬𝐭 ? 👉 Remember this question )
I can go with Indexeddb where asynchronous operations are supported and
we can work with large data sets.
𝟗. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐭𝐡𝐞 𝐦𝐚𝐱 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐥𝐢𝐦𝐢𝐭 𝐨𝐟 𝐬𝐞𝐬𝐬𝐢𝐨𝐧 𝐬𝐭𝐨𝐫𝐚𝐠𝐞 ?
We can store max of 5mb.
𝟏𝟎. 𝐈 𝐰𝐢𝐥𝐥 𝐭𝐫𝐲 𝐭𝐨 𝐬𝐭𝐨𝐫𝐞 𝐥𝐞𝐭𝐬 𝐬𝐚𝐲 𝐚𝐧 𝐢𝐦𝐚𝐠𝐞 𝐨𝐟 𝐬𝐢𝐳𝐞 𝐦𝐨𝐫𝐞 𝐭𝐡𝐚𝐧 𝟓𝐦𝐛 𝐢𝐧 𝐥𝐨𝐜𝐚𝐥𝐬𝐭𝐨𝐫𝐚𝐠𝐞 𝐭𝐡𝐞𝐧
𝐰𝐡𝐚𝐭 𝐡𝐚𝐩𝐩𝐞𝐧𝐬 ?
It will throw QuotaExceededException if it exceeds the limit.
Cookies are stored as key value pairs and hold 4kb of data.
When user logins to the application, server uses the set-cookie http
header in the response to set a cookie with a unique session identifier.
Next time when user makes the api requests, cookie will be sent in the http
header by using which server will identify who the user is.
Eg:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 120000
UTC; path=/";
Ref: https://www.w3schools.com/js/js_cookies.asp
32
47. Interview questions on this keyword.
👉 Interview Tip:Asked frequently so all scenarios are covered here. Learn
carefully. Thank me later 😇
𝟏. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐢𝐧 𝐣𝐚𝐯𝐚𝐬𝐜𝐫𝐢𝐩𝐭 ?
In non strict mode, when ever this keyword value is null or undefined,
javascript will replace itʼs value with global object.Due to this
substitution)
𝟒. 𝐈𝐧 𝐬𝐭𝐫𝐢𝐜𝐭 𝐦𝐨𝐝𝐞,𝐖𝐡𝐚𝐭 𝐰𝐢𝐥𝐥 𝐭𝐡𝐞 𝐯𝐚𝐥𝐮𝐞 𝐨𝐟 𝐭𝐡𝐢𝐬 𝐢𝐧𝐬𝐢𝐝𝐞 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 ?
𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐱(){
𝐜𝐨𝐧𝐬 𝐨𝐥 𝐞.𝐥 𝐨𝐠 (𝐭𝐡𝐢 𝐬 )
}
𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐱(){
𝐜𝐨𝐧𝐬 𝐨𝐥 𝐞.𝐥 𝐨𝐠 (𝐭𝐡𝐢 )𝐬
}
𝐰𝐢𝐧𝐝𝐨𝐰.𝐱()
33
𝐥𝐞𝐭 𝐨𝐛𝐣 = {
𝐱:” 𝐇𝐞𝐥𝐥𝐨 ”,
𝐲: 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧(){
𝐜𝐨𝐧𝐬𝐨𝐥𝐞 .𝐥𝐨𝐠 (𝐭𝐡𝐢𝐬.𝐱)
}
}
𝐨𝐛𝐣.𝐲()
It will print Hello. Because, When ever we are inside the method, the value
of this keyword is the object where this method is present.
𝟕 .𝐖𝐡𝐚𝐭𝐰𝐢𝐥𝐥𝐛𝐞𝐭𝐡𝐞𝐭𝐡𝐢𝐬𝐯𝐚𝐥𝐮𝐞𝐢𝐟 𝐢𝐭'𝐬 𝐥𝐨𝐠𝐠𝐞𝐝 𝐢𝐧𝐬𝐢𝐝𝐞 𝐚𝐫𝐫𝐨𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 ?
𝐥𝐞𝐭 𝐨𝐛𝐣 = {
𝐱 :”𝐇𝐞𝐥 𝐥 𝐨”,
𝐲: ()=>{
𝐜𝐨𝐧𝐬 𝐨𝐥 𝐞.𝐥 𝐨𝐠 (𝐭𝐡𝐢 𝐬 )
}
}
𝐨𝐛𝐣.𝐲()
It will print window object.Because, Arrow function does not have their own
this binding. they take the this value of their lexical environment where they
are enclosed.
𝟖 .𝐖𝐡𝐚𝐭 𝐰𝐢𝐥𝐥 𝐛𝐞 𝐭𝐡𝐢𝐬 𝐯𝐚𝐥𝐮𝐞 𝐢𝐟 𝐢 𝐮𝐬𝐞 𝐢𝐧 𝐛𝐮𝐭𝐭𝐨𝐧 𝐞𝐥𝐞𝐦𝐞𝐧𝐭
34
Interceptors allows us to modify the request or response before its sent to
the server or received from the server.
axios.interceptors.request.use((config)=>{
if(longUrls.include(url)){
config.timeout = 1000;
}
return config;
}
axios.interceptors.response.use((response)=>{
return response;
})
console.log(eval("1 + 2")); // 3
35
https://www.linkedin.com/posts/saikrishnanangunuri_javascript-
javascriptdeveloper-reactjs-activity-7211747675635900416-h9IB?
utm_source=share&utm_medium=member_desktop
Give above post example )
shallowCopy[2][0] = 100;
console.log(originalArray); // Output: [1, 2, [100, 4]]
Deep copy:
A deep copy creates a new object or array that has its own copies of
the properties of the original object.
using lodash:
let array = _.cloneDeep(originalArray)
These variables does not exist in the program and they are not
declared.
If we try to read the value of undeclared variable then we will get a
runtime error.
36
undefined:
These variables are declared in the program but are not assigned any
value.
If we try to access the value of undefined variables, It will return
undefined.
<script>
document.getElementById('div1').addEventListener(
'click', function() {
37
console.log('Div 1 clicked');
});
document.getElementById('div2').addEventListener(
'click', function() {
console.log('Div 2 clicked');
});
document.getElementById('button1').addEventListener(
'click', function(event) {
console.log('Button clicked');
// To stop the event from bubbling up
event.stopPropagation();
});
</script>
</body>
</html>
38
<body>
<div id="div1" style="padding: 50px;
border: 1px solid black;">
Div 1
<div id="div2" style="padding: 50px;
border: 1px solid red;">
Div 2
<button id="button1">Click Me</button>
</div>
</div>
<script>
document.getElementById('div1').addEventListener(
'click', function() {
console.log('Div 1 clicked');
}, true);
document.getElementById('div2').addEventListener(
'click', function() {
console.log('Div 2 clicked');
}, true);
document.getElementById('button1').addEventListener(
'click', function(event) {
console.log('Button clicked');
// To stop the event from propagating further
// event.stopPropagation();
}, true);
</script>
</body>
</html>
39
54. What are the various array methods in javascript ?
toString(): returns array as acomma separated string.
shift(): removes the first element at the beginning and shifts all the
elements to lower index.
unshift(): adds new element at beginning and moves other elements one
index further.
concat(): creates new array by concatenating existing arrays.
fill(): will fill all the elements of an array from a start index ti an end index
with a stati value.
Ref: https://www.w3schools.com/js/js_array_methods.asp
40
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
every(): will check if all the elements of the array satisfies the specified
condition. it return true if all the elements satisfies the condition, else
returns false.
function x(){
try {
null.f();
} catch (e) {
console.error(e);
// TypeError: Cannot read property 'f' of null
}
Range errors: These errors occurs when the value is not present in
allowed range.
try {
new Array(-1);
} catch (e) {
console.error(e);
// RangeError: Invalid array length
}
Eg2:
if (num < 30) throw new RangeError("Wrong number");
^
RangeError: Wrong number
try {
eval('eval("invalid code")');
} catch (e) {
URI errors: These erros occurs when wrong characters used in URI
functions
console.log(decodeURI("https://www.learndepth")) //works f
console.log(decodeURI("%sdfk")); //throws error
decodeURIComponent('%');
Advantages:
let package = {
version: "2.0",
};
let application = Object.create(package, {
name: { value: "game" },
}); // inherited from package
console.log(application);
console.log(Object.getPrototypeOf(application));
Ref: https://www.scaler.com/topics/javascript/prototype-inheritance-in-
javascript/
ref: https://apidog.com/blog/axios-vs-fetch/
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok'
+ response.statusText);
}
r e t u r n r e s p o n s e . j s o n ( ) ;
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(`There has been a problem with
your fetch operation:`, error);
});
axios:
axios.get(url)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(`There has been a problem
with your axios operation:`, error);
});
SOLID
Arrow functions will solve the common pain points of this binding in
traditional funtional expressions. Arrow functions does not have their own
this. It will take the this value from the parentʼs scope (i.e., code that
contains the arrow function). For example, look at the setTimeout function
below.
// ES5
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}.bind(this), 1000);
} };
obj.counter(); // 42
// ES6
var obj = {
let count = 0;
const intervalId = setInterval(() => {
console.log(count++);
This code will print the numbers 0 to 5 with a one-second delay between each
number. After printing 5, the clearInterval method will be called, and the
interval will stop.
// worker.js
// main.js
Example: "^1.2.3"
This means that the package manager will install any version from
1.2.3 to less than 2.0.0.
It will install newer patch versions (e.g., 1.2.4, 1.2.5) and minor
versions (e.g., 1.3.0, 1.4.0), but not major versions (e.g., 2.0.0).
Tilde (~)
The tilde (~) allows updates to the most recent patch version (x.x.1, but it
will not allow updates to the minor or major versions.
Example: "~1.2.3"
This means that the package manager will install any version from
1.2.3 to less than 1.3.0.
It will install newer patch versions (e.g., 1.2.4, 1.2.5), but not new
minor versions (e.g., 1.3.0).
// or
// Add a class
element.classList.add("newClass");
const a = 1<2<3;
const b = 1>2>3;
console.log(a,b) //true,false
Output:
true, false
const p = { k: 1, l: 2 };
const q = { k: 1, l: 2 };
let isEqual = p==q;
let isStartEqual = p=== q;
console.log(isEqual, isStartEqual)
OutPut:
isStartEqual will also be false for the same reason. The === operator
checks for strict equality, meaning it not only compares values but also
ensures that the objects being compared reference the exact same
memory location.
So, console.log(isEqual, isStartEqual) will output false false.
a) 2+2 = ?
b) "2"+"2" = ?
c) 2+2-2 = ?
d) "2"+"2"-"2" = ? (tricky remember this)
e) 4+"2"+2+4+"25"+2+2 ?
Output:
a) 2+2 = ?
console.log(2 + 2); // Output: 4
b) "2"+"2" = ?
console.log("2" + "2");
// Output: "22" (string concatenation)
c) 2+2-2 = ?
d) "2"+"2"-"2" = ?
console.log("2" + "2" - "2");
// Output: 20 (string "22" is converted
to a number, then subtracted by the number 2)
e) 4+"2"+2+4+"25"+2+2
console.log(4+"2"+2+4+"25"+2+2);
// "42242522"
let a = 'jscafe'
a[0] = 'c'
console.log(a)
Output:
“jscafeˮ
var x=10;
function foo(){
var x = 5;
foo();
console.log(x)
Output: 5 and 10
var x = 10; Declares a global variable x and initializes it with the value
10.
var x = 5; Inside the function foo, declares a local variable x and
initializes it with the value 5. This x is scoped to the function foo and is
different from the global x.
console.log(x); Logs the value of the global variable x (which is still 10) to
the console outside the foo function.
console.log("Start");
setTimeout(() => {
console.log("Timeout");
Output:
Start, End,Promise,Timeout.
function x(){
for(var i=1;i<=5;i++){
setTimeout(()=>{
console.log(i)
},i*1000)
}
x();
function x() {
function closur(x) {
// Set a timeout to log value of x after x seconds
setTimeout(() => {
console.log(x);
}, x * 1000);
};
// Loop from 1 to 5
for (var i = 1; i <= 5; i++) {
// Call the closure function with current value of i
closur(i);
}}
For each iteration of the loop, the inner function closur is called with the
current value of i.
Each call to closur(i) creates a new closure that captures the current value of
i and sets a timeout to log that value after i seconds.
1 (after 1 second) 2
(after 2 seconds) 3
(after 3 seconds) 4
(after 4 seconds) 5
(after 5 seconds)
This happens because each iteration of the loop calls closur with a different
value of i, and each setTimeout inside closur is set to log that value after i
seconds.
var z = x();
z();
var z = x(); Calls the function x and assigns the returned function d to
the variable z.
When you run this code, it will log the value of a at the time of executing d,
which is 500, because d retains access to the variable a even after x has
finished executing. This behavior is possible due to closure, which allows
inner functions to access variables from their outer scope even after the outer
function has completed execution.
getData1()
getData();
function getData1(){
console.log("getData11")
}
Output:
Explanation:
In JavaScript, function declarations are hoisted to the top of their scope, while
variable declarations using var are also hoisted but initialized with undefined.
Here's what happens in your code:
getData is declared using var, so it's also hoisted to the top but
initialized with undefined.
The arrow function assigned to getData is not hoisted because it's
assigned to a variable.
It will throw an error because getData is undefined, and you cannot call
undefined as a function.
Therefore, if you try to run the code as is, you'll encounter an error when
attempting to call getData().
If you want to avoid this error, you should either define getData before calling it
or use a function declaration instead of a variable declaration for getData.
Here's how you can do it:
function func() {
try {
console.log(1)
return
} catch (e) {
console.log(2)
} finally {
console.log(3)
}
console.log(4)
}
func()
Output: 1 & 3
Since return is encountered within the try block, the control exits the function
immediately after console.log(1). The catch block is skipped because there are
no errors, and the code in the finally block is executed regardless of whether
an error occurred or not.
So, when you run this code, it will only print 1 and 3 to the console.
Explanation:
Many of you might have thought the output to be 1,2,3,4,5,6,7. But “breakˮ
statement works only loops like for, while, do…while and not for map(),
forEach(). They are essentially functions by nature which takes a callback and
not loops.
while(a) {
console.log(' -- inside whilee -- ');
}
Solution: https://medium.com/@iamyashkhandelwal/5-output-based-
inter view-questions-in-javascr ipt-b64a707f34d2
The issue here is that the while loop runs indefinitely because there's no
opportunity for the JavaScript event loop to process the setTimeout callback
and update the value of a. So, even though a will eventually become false
after 2 seconds, the while loop will not terminate because it doesn't yield
control to allow other tasks, like the callback, to execute.
To fix this, you might consider using asynchronous programming techniques
like Promises, async/await, or handling the setTimeout callback differently.
console.log(2);
console.log(5);
This code demonstrates the event loop in JavaScript. Here's the breakdown of
what happens:
When you run this code, the order of the output might seem a bit
counterintuitive:
2
3
5
4
1
https://medium.com/@iamyashkhandelwal/5-output-based-interview-
questions-in-javascript-b64a707f34d2
console.log("D");
foo();
console.log("E")
Output:
D, A, E, B, C
function is still not fully executed, and it's waiting for the resolution of the
Promise inside it. Inside foo()
(resumed execution): console.log("B") This line logs "B" to the console since
it's a synchronous operation.
await new Promise(resolve ⇒ setTimeout(resolve, 0;
This line awaits the resolution of a Promise returned by the setTimeout
function. Although the delay is set to 0 milliseconds, the setTimeout callback
is pushed into the callback queue, allowing the synchronous code to continue.
Back to the main context: The control is still waiting for the foo() function to
complete.
Inside foo() (resumed execution): The callback from the setTimeout is picked
up from the callback queue, and the promise is resolved. This allows the
execution of the next await .
console.log("C") This line logs "C" to the console since it's a synchronous
operation. foo() function completes.
Output: 3
Finally, the function returns x. Since x was passed as 3 when calling the
function (function(x){ ... })(3), it returns 3.
Output: 3 3 3
The loop checks if i is still less than 3. Since it's now 3, the loop exits.
When the timeouts execute after their respective intervals, they access the
variable i from the outer scope. At the time of execution, i is 3 because the
loop has already finished and incremented i to 3. So, all three timeouts log
3.
Output: 3
Let me break it down for you:
let c=0;
setTimeout(() => {
clearInterval(id)
},2000)
This JavaScript code sets up an interval that increments the value of c every
200 milliseconds and logs its value to the console. After 2 seconds 2000
milliseconds), it clears the interval.
Here's what each part does:
function getName1(){
console.log(this.name);
}
Object.prototype.getName2 = () =>{
console.log(this.name)
}
let personObj = {
name:"Tony",
print:getName1
}
personObj.print();
personObj.getName2();
function getName1(){
console.log(this.name);
}
let personObj = {
name:"Tony",
print:getName1
}
personObj.print();
Object.prototype.name="Steve";
personObj.getName2();
function test() {
console.log(a);
console.log(foo()); var
a = 1; function foo() {
return 2;
}
}
test();
function job(){
return new Promise((resolve,reject)=>{
reject()
})
}
promise.then(()=>{
console.log("1111111111")
}).then(()=>{
console.log("22222222222")
}).catch(()=>{
console.log("3333333333")
}).then(()=>{
console.log("4444444444")
})
After that, a series of then and catch methods are chained to the promise:
The first then method is chained to the promise, but it is not executed
because the Promise is rejected, so the execution jumps to the catch
method.
The catch method catches the rejection of the Promise and executes its
callback, logging "3333333333".
Another then method is chained after the catch method. Despite the
previous rejection, this then method will still be executed because it's part
of the Promise chain, regardless of previous rejections or resolutions. It
logs "4444444444".
So, when you run this code, you'll see the following output:
333333333
3
44444444
44
var a = 1;
function data() {
if(!a) {
var a = 10;
}
console.log(a);
}
Explanation:
var a = 1;
function toTheMoon() {
var a;
/* var has function scope,Hence
it's declaration will be hoisted */
if(!a) {
a = 10;
}
console.log(a);
// 10 precendence will be given to local scoped variable.
}
toTheMoon();
console.log(a); // 1 refers to the `a` defined at the top.
function guessArray() {
let a = [1, 2]; let b = [1, 2];
console.log(a == b);
console.log(a === b);
guessArray();
In JavaScript, when you compare two arrays using the == or === operators,
you're comparing their references, not their contents. So, even if two arrays
have the same elements, they will not be considered equal unless they refer to
the exact same object in memory.
In your guessArray function, a and b are two separate arrays with the same
elements, but they are distinct objects in memory. Therefore, a == b and a ===
b will both return false, indicating that a and b are not the same object.
If you want to compare the contents of the arrays, you'll need to compare each
element individually.
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
Solution:
The provided code snippet demonstrates the behavior of variable hoisting and
function scope in JavaScript. Let's analyze the code step-by-step to
understand the output:
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
Breakdown
var x = 23;
(function(){
var x = 43;
// ...
})();
(function random(){
x++;
console.log(x);
var x = 21;
})();
Another function scope is created inside the first IIFE. The function
random is invoked immediately.
x++;
console.log(x);
var x = 21;
Here, variable hoisting comes into play. The declaration var x = 21; is
hoisted to the top of the function random, but not its initialization. Thus,
the code is interpreted as:
After the console.log statement, x is assigned the value 21, but this
assignment happens after the console.log and thus does not affect the
output.
Summary
When random function is executed, the following sequence occurs:
28. Can you find is there any security issue in the javascript
code?
To mitigate this security risk, you should properly sanitize or escape the data
before assigning it to innerHTML, or consider using safer alternatives like
textContent or creating DOM elements programmatically.
Here's an example of how you could sanitize the data using a library like
DOMPur ify:
return uniqueArr;
};
removeDuplicatesWay1([1, 2, 1, 3, 4, 2, 2, 1, 5, 6]);
// -------------------------- (or)---------------------------
function removeDuplicatesWay2(arr) {
/* Use the Set object to remove duplicates. This works
because Sets only store unique values */
return Array.from(new Set(arr));
// return [...new Set(arr)] => another way
}
removeDuplicates([1, 2, 1, 3, 4, 2, 2, 1, 5, 6]);
function findEvenNumbers(arr) {
const result = [];
// Example usage:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8,-8,19, 9, 10];
console.log("Even numbers:", findEvenNumbers(numbers));
console.log(checkPallindrome("madam"));
console.log(findFactorial(4));
console.log(longestWord);
};
function findMax(arr) {
if (arr.length === 0) {
return undefined;
return max;
}
// Example usage:
const numbers = [1, 6, -33, 9, 4, 8, 2];
console.log("Maximum number is:", findMax(numbers));
function isPrime(number) {
if (number <= 1) { return false; // 1 and numbers less
than 1 are not prime
return true;
// If not divisible by any number, it's prime
}
// Example usage:
console.log(isPrime(17)); // true
console.log(isPrime(19)); // false
function findSmallestWord() {
const sentence = "Find the smallest word";
const words = sentence.split(' ');
If the input array is empty or contains less than 3 numbers then return 0.
if (numTerms <= 0) {
return [];
} else if (numTerms === 1) {
return [0];
}
return sequence;
}
// Example usage:
const numTerms = 10;
const fibonacciSeries = fibonacciSequence(numTerms);
console.log(fibonacciSeries);
// Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
console.log(maxCount);
};
while(array1 || array2){
}
console.log(mergedArray)
sortedData([1,3,4,5],[2,6,8,9])
14. Create a function which will accepts two arrays arr1 and
arr2. The function should return true if every value in arr1 has
its corresponding value squared in array2. The frequency of
values must be same. (Effecient)
1,2,3,4,1,9 true
1,2,3,1,9 false
1,2,1,4,4,1 false (must be same frequency)
function isSameFrequency(arr1,arr2){
}
console.log(isSameFrequency([1,2,5],[25,4,1]))
"aaz","zza" ⟹ false
function isStringCreated(str1,str2){
if(str1.length !== str2.length) return false
let freq = {};
console.log(isStringCreated('anagram','nagaram'))
function getUniqueArr(array){
const uniqueArr = [];
const seen = {};
function findLargestElement(arr) {
let max = Number.NEGATIVE_INFINITY;
// Initialize max to smallest possible number
return max;
}
// Example usage:
const array = [
[3, 4, 58],
[709, 8, 9, [10, 11]], [111, 2]
];
console.log("Largest element:", findLargestElement(array));
function countCharacters(str) {
// Object to store character counts
const charCount = {};
const len = str.length;
// Example usage:
const result = countCharacters("helaalo");
console.log(result);
// Output: { h: 1, e: 1, l: 2, o: 1 }
function quickSort(arr) {
// Check if the array is empty or has only one element
if (arr.length <= 1) {
return arr;
}
// Example usage:
const unsortedArray = [5, 2, 9, 1, 3, 6];
const sortedArray = quickSort(unsortedArray);
console.log(sortedArray);
// Output: [1, 2, 3, 5, 6, 9]
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
// Example usage
reverseWords("ChatGPT is awesome");
//"awesome is ChatGPT"
function reverseWords(sentence) {
// Split the sentence into words
let words = [];
let wordStart = 0;
for (let i = 0; i < sentence.length; i++) {
if (sentence[i] === ' ') {
words.unshift(sentence.substring(wordStart, i));
wordStart = i + 1;
} else if (i === sentence.length - 1) {
words.unshift(sentence.substring(wordStart,i+1));
}
}
// Example usage
const sentence = "ChatGPT is awesome";
function flattenArray(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
// Reverse the result to maintain original order
}
return result;
}
24. Given an array, return an array where the each value is the
product of the next two items: E.g. [3, 4, 5] -> [20, 15,
12]
function productOfNextTwo(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
function findSecondLargest(arr) {
if (arr.length < 2) {
throw new Error(`Array must contain
at least two elements.`);
}
return secondLargest;
}
// Example usage:
const array = [10, 5, 20, 8, 12];
console.log(findSecondLargest(array)); // Output: 12
return pairs;
function encodeString(input) {
if (input.length === 0) return "";
return result;
}
1. What is React?
React is an opensource component based JavaScript library which is used
to develop interactive user interfaces.
Virtual dom
This jsx will be transpiled into javascript that interacts with the browser
when the application is built.
4. What is DOM ?
DOM means document object model. It is like a tree like structure that
represents the elements of a webpage.
Rendering Efficiency:
Virtual DOM Updates to the Virtual DOM are typically faster because
they occur in memory and are not directly reflected in the browser.
Actual DOM Manipulating the actual DOM is slower due to its
complexity and the potential for reflows and repaints.
function User() {
const [message, setMessage] = useState("Welcome React");
return (
<div>
<h1>{message}</h1>
</div>
);
}
this.state = {
message: "Welcome to React world",
};
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}}
They are used to send data from parent component to child component.
Props are immutable, so they cannot be modified directly within the child
component.
Example:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const name = "John";
return (
<div>
<h1>Parent Component</h1>
<ChildComponent name={name} />
</div>
);
}
// ChildComponent.js
import React from 'react';
function ChildComponent(props) {
return (
<div>
<h2>Child Component</h2>
<p>Hello, {props.name}!</p>
</div>
);
}
State is used to hold the data of a component whereas props are used to
send data from one component to another component.
State is mutable but props are immutable.
Prop drilling can make code difficult to read and maintain, especially in
large applications with many components. This is because props need to
be passed down through multiple levels of components, and it can be
difficult to keep track of which components are using which props.
Reduced maintainability:
Prop drilling can also make code less maintainable. This is because if a
prop needs to be changed, the change needs to be propagated through all
of the components that use it. This can be a time-consuming and error-
prone process.
Example :
smoother user
experience.
useEffect(()=>{
console.log("Called on initial mount only once")
},[])
useEffect(()=>{
console.log("Called on every dependency update")
},[props.isFeature,props.content])
This will be called whenever dependency value changes (here Eg: isFeature or
content).
useEffect(()=>{
return ()=>{
console.log(`Any cleanup activities
or unsubscribing etc here`)
}
})
mounting
updating
unmounting
Mounting:
Constructor:
getDerivedStateFromProps:
This is called right before rendering the elements into the dom.
Its a natural place to set the state object based on the initial props.
getDerivedStateFromProps(props,state){
return { favColor: props.favColor }
}
render():
It contains all the html elements and is method that actually outputs
the html to the dom.
ComponentDidMount():
Updating phase:
ShouldComponentUpdate:
This will return boolean value that specifies whether react should
continue with the rendering or not. default is true.
shouldComponentUpdate(){
return true/false
}
getSnapshotBeforeUpdate:
It will have access to the props and state before update. means
that even after the update you can check what are the values were
before update.
getSnapshotBeforeUpdate(prevProps,prevState){
console.log(prevProps,prevState)
}
ComponentDidUpdate:
Unmounting phase:
In this phase the component will be removed from the dom. here we
can do unsubscribe to some events or destroying the existing dialogs
etc.
ComponentWillUnmount:
react will use this to indentify, which elements in the list have been added,
removed or updated.
function MyComponent() {
const items = [
{ id: 1, name: "apple" },
{ id: 2, name: "banana" },
{ id: 3, name: "orange" }
];
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
Advantage:
Reference: https://react.dev/reference/react/PureComponent
Ref: https://goshacmd.com/controlled-vs-uncontrolled-inputs-react/
they are helpful when we want to update the component whith out using
state and props and prevents triggering rerender.
Common useCases:
Media control/Playback
Examples:
1. Managing input focus
function App() {
const inputRef = useRef();
return (
<div>
<input type='text' ref={inputRef} />
<button onClick={focusOnInput}>Click Me</button>
</div>
);
}
function App() {
const audioRef = useRef();
return (
<div>
Reference: https://www.memberstack.com/blog/react-refs
Example:
Using the Forward Ref Component: Use this component and pass a ref to
it.
function ParentComponent() {
const inputRef = useRef(null);
return (
<div>
<ChildComponent ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus Input
</button>
</div>
);
}
static getDerivedStateFromError(error) { /*
Update state so the next render will
show the fallback UI. */
return { hasError: true };
}
componentDidCatch(error, info) {
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
logErrorToMyService(error, info.componentStack);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.fallback;
}
return this.props.children;
}
}
Then you can wrap a part of your component tree with it:
function withStyles(Component) {
return props => {
const style = { padding: '0.2rem', margin: '1rem' }
return <Component style={style} {...props} />
}}
function App() {
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
Eg:
Fetch data
https://react.dev/learn/reusing-logic-with-custom-hooks
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
c o n s t r e s u l t = a w a i t r e s p o n s e .
s e t D a t a ( r e s u l t ) ;
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{data && (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)}
</div>
);
}
Create context
Create Provider and wrap this provider around root level component and
pass the data.
Create consumer and utilize data using useContext.
Data fetching Sharing fetched data across multiple components that need
to display this data. (for displaying search results when user makes a
search request).
UserContext.js
Step 2 We need to wrap the root level component with provider and
pass the user Information.
App component:
return (
<div>
<UserProvider value={userinfo}>
<ComponentA/>
</UserProvider>
</div>
);
};
Step 3 In componentA, We can get the data using useContext and utilize
the user Information.
=============================================================
// Enabling strict mode for entire App.
=============================================================
function App() {
return (
<>
<Header />
<StrictMode>
<main>
<Sidebar />
<Content />
</main>
</StrictMode>
<Footer />
</>
);
}
32. What are the different ways to pass data from child
component to parent component in react ?
There are 4 common ways to send data from child component to parent
component. They are.,
Callback Functions
Context API
Redux
Initial Load time: csr has slow initial load time as browser needs to
interpret the data and render the page. where as ssr has faster initial load
times as server send pre-rendered html page to the browser.
Seo: Ssr is seo friendly when compared to csr as fully rendered html
content is provided to the search engine crawlers whereas csr needs to
parse javascript heavy content.
Router: It wraps the entire application and provides the routing context for
the application. It contains 2 types of routers,
Browser router and Hash router.
Route: It contains mapping between urlpath and the component. When the
url matches, respective component will be rendered.
Link: is used to create the navigation links which user can click to navigate
to different routes.
switch: is used to render the first matching route among its children. It
ensures only one route is rendered.
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Contact() {
return <h2>Contact</h2>;
}
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">
Home
</Link>
</li>
<li>
<Link to="/about">
About
</Link>
</li>
<li>
<Link to="/contact">
Contact
<Switch>
<Route exact path="/"
component={Home}
/>
<Route path="/about"
component={About}
/>
<Route path="/contact"
component={Contact}
/>
</Switch>
</div>
</Router>
);
}
Ref : https://www.youtube.com/watch?v=wU57kvYOxT4
https://mtg-dev.tech/blog/real-world-example-to-use-uselayouteffect
When an event occurs in the child component (like a button click), call this
function with the data to be passed to the parent.
Parent Component:
function ParentComponent() {
const [dataFromChild, setDataFromChild] = useState('');
return (
<div>
<ChildComponent onData={handleDataFromChild} />
<p>Data from child: {dataFromChild}</p>
</div>
Child Component:
return (
<button onClick={sendDataToParent}>
Send Data to Parent
</button>
);
}
It will not trigger any event by itself whenever the data is updated.
Parent component:
return (
<>
<TextEditor valueRef={valueRef} />
<button onClick={() => {
console.log(valueRef.current)}
}
>Get</button>
</>
);
}
Child component:
// Initial state
const initialState = {
count: 0
};
// Reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
} };
// Component
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch( {
type: 'increment' }
)}>Increment</button> <button
onClick={() => dispatch( { type:
'decrement' }
)}>Decrement</button>
</div>
);
};
useCounter.js:
return {
counter,
increment,
decrement
}; ,
};
component.js:
import { useCounter } from './useCounter.js';
return (
<div>
<button onClick={decrement}>Decrease</button>
<div>Count: {counter}</div>
<button onClick={increment}>Increase</button>
</div>
);
};
return (
<div>
{checkboxes.map((checkbox) => (
<Checkbox
key={checkbox.id}
label={checkbox.label}
checked={checkbox.checked}
onChange={
() => handleCheckboxChange(checkbox.id)
}
/>
))}
<button
onClick={handleSelectAll}
disabled={selectAllDisabled}>
{selectAllDisabled ? 'Deselect All' : 'Select All'}
</button>
<p>Selected: {selectedCount}</p>
<ul>
{selectedCheckboxes.map((checkbox) => (
<li key={checkbox.id}>{checkbox.label}</li>
))}
</ul>
</div>
);
};
Solution:
Create App component and circle component. We will use recursion concept
to achieve this.
App.js:
return (
<div className="nested-circles-container">
<input
onChange={(e) => handleInput(e)}
placeholder="Enter number of circles"
type="number"
/>
<Circle numbCircles={num}></Circle>
</div>
);
}
App.css/Style.css:
.nested-circles-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
Circle.js:
Circle.css:
.circle-new {
border-radius: 100%;
border: 1px solid black;
display: flex;
justify-content: center;
align-items: center;
}
HOC Pattern
https://javascriptpatterns.vercel.app/patterns/react-patterns/render-props
For example, if we wanted to show listings on the landing page, we could use
a container component to fetch the data for the recent listings, and use a
https://javascriptpatterns.vercel.app/patterns/react-patterns/conpres