├── 100Questions └── 100_JS_Que ├── Akshay Saini Notes ├── Akshay Saini - Notes- Cheatsheet.pdf ├── Akshay Saini - Notes- Handwritten.pdf └── Akshay Saini - Notes.pdf ├── Interview-questions-answers ├── Interview_Preparation └── js codes.docx /100Questions/100_JS_Que: -------------------------------------------------------------------------------- 1 | https://plainenglish.io/blog/50-javascript-output-questions 2 | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 3 | // Question: What is typeof [] 4 | // Answer: Object. Actually Array is derived from Object. If you want to check array use Array.isArray(arr) 5 | 6 | // Question: What is typeof arguments 7 | // Answer: Object. arguments are array like but not array. it has length, can access by index but can't push pop, etc. 8 | 9 | // Question: What is the value of typeof null 10 | // Answer: "object" 11 | 12 | // Question: What is console.log(true+false) 13 | // Answer: 1 here true -->> 1 & false -->> 0 then 1 + 0 -->> 1 14 | 15 | // Question: What is 2+true 16 | // Answer: 3. The plus operator between a number and a boolean or two boolean will convert boolean to number. Hence, true converts to 1 and you get result of 2+1 17 | 18 | // Question: What is "2"+true 19 | // Answer: 2true here string concatination happer "2"+"true" -->> 2true 20 | 21 | // Question: What is the value of -'34'+10 22 | // Answer: -24. minus(-) in front of a string is an unary operator that will convert the string to a number and will make it negative. Hence, -'34' becomes, -34 and then plus (+) will perform simple addition as both the operands are number. 23 | 24 | // Question: What is the value of +'dude' 25 | // Answer: NaN. The plus (+) operator in front of a string is an unary operator that will try to convert the string to number. Here, JavaScript will fail to convert the "dude" to a number and will produce NaN. 26 | 27 | // Question: If you have var y = 1, x = y = typeof x; What is the value of x? 28 | // Answer: "undefined" 29 | 30 | // Question: for var a = (2, 3, 5); what is the value of a? 31 | // Answer: 5. The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand. ref: MDN 32 | 33 | // Question: for var a = (1, 5 - 1) * 2 what is the value of a? 34 | // Answer: 8 35 | 36 | // Question: What is the value of !'bang' 37 | // Answer: false. ! is NOT. 38 | 39 | // Question: What is the value of parseFloat('12.3.4') 40 | // Answer: 12.3 41 | 42 | // Question: What is the value of Math.max([2,3,4,5]); 43 | // Answer: NaN 44 | 45 | // Question: typeof(NaN) 46 | // Anwser:"number" 47 | 48 | // Question:null == undefined 49 | // Answer: true 50 | 51 | // Question: If var a = 2, b =3 what would be value of a && b 52 | // Answer: 3 53 | 54 | // Question: What is -5%2 55 | // Answer:-1. the result of remainder always get the symbol of first operand 56 | ====================================================================================================================================================================== 57 | let a = []; 58 | let b = []; 59 | console.log(a==b); //false 60 | console.log(a===b); //false 61 | //Explaination : Here we are comparing memory location, not an array. Memory location of 2 arrays are not same. 62 | -------------------------- 63 | let a = []; 64 | let b = a; 65 | console.log(a==b); //true 66 | console.log(a===b); //true 67 | //Explaination : Here we are assigning a to b, where memory location is now same. 68 | --------------------------- 69 | let a = [1]; 70 | let b = [1]; 71 | console.log(a[0]==b[0]); //true 72 | console.log(a[0]===b[0]); //true 73 | //Explaination : Here we are comparing elements inside an array, not a memory location. We specify the index so that's why element get compared. 74 | ----------------------------- 75 | let z= [1,2,3] 76 | let a ={name: "priya"} 77 | console.log(...z); // 1 2 3 78 | //Explaination : ...z means destructing happened i.e, all the elements are come out from an array/object. 79 | ------------------------------ 80 | console.log(typeof NaN); //number 81 | //Explaination : If we divide "priya"/2 then it will give NaN. 82 | -------------------------------- 83 | let data = 10 - -10; 84 | console.log(data); //20 85 | //Explaination : Minus minus will become plus so 10+10=20 86 | --------------------------------- 87 | const set = new Set([1,1,2,2,3,4,5]) 88 | console.log(set) //{1,2,3,4,5} 89 | //Explaination : It will remove duplicate values. 90 | --------------------------------- 91 | let data ={name: "priya"} 92 | console.log(delete data.name); //true 93 | console.log(data)//{} 94 | //Explaination : delete will return either true or false. 95 | ----------------------------------- 96 | let data ={name: "priya"} 97 | console.log(delete data); //false 98 | //Explaination : We can delete the object property only. We can't able to delete the object(i.e, data). 99 | ------------------------------------ 100 | const data = ["piya", "priya", "supriya"]; 101 | const [y] = data; 102 | console.log(y); //"priya" 103 | //Explaination : We are doing destructuring here. y is representing the first index only 104 | ------------------------------------- 105 | const data = ["piya", "priya", "supriya"]; 106 | const [y,z] = data; 107 | console.log(y,z); //"priya", "priya" 108 | //Explaination : We are doing destructuring here. y is representing the first index only and z representing the second index. 109 | -------------------------------------- 110 | const data = ["piya", "priya", "supriya"]; 111 | const [,m] = data; // way to access any specific element here at second position 112 | console.log(m); //"priya" 113 | //Explaination : To access any element without taking previous values, we can do just write comma. 114 | -------------------------------------- 115 | const data ={name:"priya"} 116 | const {name} = data; //how to get the name property without . dot operator 117 | console.log(name);//priya 118 | //Explaination : Here we did object destructuring.It's not store in continuos memory location but array store in continuoes memory location so that's why we used comma in an array. 119 | -------------------------------------- 120 | let data ={name:"priya"} 121 | let data1={city:"ABC"} 122 | data = {...data, ...data1} //merge 2 objects 123 | console.log(data); // {name:"priya", age:"ABC"} 124 | //Explaination : using spread operator we use to merge the 2 objects. Three dots will pop out the property from an object and assign inside curly brackets. 125 | ----------------------------------------- 126 | let data ={name:"priya"} 127 | let data1={city:"ABC"} 128 | data = {data, ...data1} //merge 2 objects 129 | console.log(data); // { "data" : {name:"priya"}, "city": "ABC"} 130 | //Explaination :Three dots will pop out the property from an object and assign inside curly brackets. If we didn't do destructing or spread operator then key will be object name(i.e, data) and assign the value as whole object into it. 131 | ------------------------------------------ 132 | let data ={name:"priya"} 133 | let data1={city:"ABC", name: "supriya"} 134 | data = {...data, ...data1} //merge 2 objects 135 | console.log(data); // { name:"supriya", "city": "ABC"} 136 | //Explaination : If we have same keys while merging then the position of the property will remain same but the value get updated with new value. Because in an objects Keys hould be unique. 137 | ------------------------------------------- 138 | const name = "priya" 139 | console.log(name()); //Error: name is not a function 140 | //Explaination : Function we are calling but it's not present so it will an error. 141 | -------------------------------------------- 142 | const result = false || {} || 20 || null; 143 | console.log(result); //20 144 | //Explaination : OR operator will find first positive value. Null is a falsy value by default. {} is a positive value. It didn't reach till 20 and null. 145 | -------------------------------------------- 146 | const result = null || false || ''; 147 | console.log(result); //'' 148 | //Explaination : OR operator will find first positive value. It will print '' because any of the true value didn't found so it will pick last value always. 149 | ------------------------------------------- 150 | const result = [] || 0 || true; 151 | console.log(result); //[] 152 | //Explaination : OR operator will find first positive value. It will print [] because empty array/object is a positive. 153 | ------------------------------------------------- 154 | console.log(Promise.resolve(5)); //Promise {: 5} 155 | //Explaination : While doing resolve(), itself here a promise. If we pass number/string etc then it will print fulfilled. 156 | ------------------------------------------------ 157 | console.log("smile" === "smile"); //true 158 | //Explaination : Each emojy contain unicode where we are compairing unicode not the emojy so it's true 159 | ------------------------------------------------- 160 | JSON.parse ? 161 | Parse JSON object to a JavaScript value // converting data into js object 162 | ------------------------------------------------- 163 | let name = "priya"; 164 | function getName(){ 165 | console.log(name); //Uncaught ReferenceError: Cannot access 'name' before initialization 166 | let name = "supriya"; 167 | } 168 | getName(); 169 | //Explaination : Hoisting used here. If we use VAR the can use variable before declare. But in LET we can't do that. LET/CONST need declaration first then can use it. 170 | -------------------------------------------------- 171 | let name = "priya"; 172 | function getName(){ 173 | console.log(name); //Uncaught ReferenceError: Cannot access 'name' before initialization 174 | let name = "supriya"; 175 | } 176 | getName(); 177 | ------------------------------------------------------------------------------ 178 | let name = "priya"; 179 | function getName(){ 180 | let name; 181 | console.log(name); //undefined 182 | name = "supriya"; 183 | } 184 | getName(); 185 | ------------------------------------------------------------------------------ 186 | let name = "priya"; 187 | function getName(){ 188 | let name = "supriya"; 189 | console.log(name); //supriya 190 | } 191 | getName(); 192 | ------------------------------------------------------------------------------ 193 | let name = "priya"; 194 | function getName(){ 195 | console.log(name); //priya 196 | } 197 | getName(); 198 | //Explaination : Let is a block scope.Because of closures we can able to access name which is outside of a function with LET. 199 | -------------------------------------------------- 200 | console.log((x => x)('I love')) //"I love" 201 | console.log(`${(x => x)('I love')} to program`) //"I love to program" 202 | //Explaination : Template Literal used here. We use here arrow function which is returning a string 203 | ---------------------------------------------------- 204 | function sumValues(x,y,z){ 205 | return x+y+z; 206 | } 207 | sumValues(...[2,3,4]) //how to call a function so that output will be 9 208 | //Explaination : we can't do like this sumValues(2,3,4). 209 | ---------------------------------------------------- 210 | const name = "priya is a girl."; 211 | console.log(typeof name); //string 212 | console.log(!typeof name); //false //"priya is a good girl" is a string means thruthy value. Nagation of thruthy is falsy value. 213 | console.log(!typeof name === 'object'); //false 214 | console.log(!typeof name === 'string'); //false 215 | console.log(!typeof name === false); //true 216 | //Explaination : We are using negation mark(!) which will return either true or false only. 217 | ---------------------------------------------------- 218 | const name = "priya"; 219 | const age ="10000"; 220 | console.log(isNaN(name)); //true 221 | console.log(isNaN(age)); //false 222 | //Explaination : If it's not a number then return True. If it's a number then return false. 223 | ----------------------------------------------------- 224 | let person = {name: "priya"}; 225 | Object.seal(person); //post seal, how can you modify the person object 226 | person.age ="1000"; 227 | person.name ="supriya"; 228 | console.log(person); //{name : "supriya"} 229 | //Explaination : Onceyou use Seal we can't able to add the more keys with values into it.But you can modigy the existing key. 230 | ------------------------------------------------------- 231 | let data = [2,9,0,10]; 232 | data.shift();//remove first element 233 | console.log(data); //[9,0,10] 234 | data.pop(); //remove last element 235 | console.log(data);//[9,0] 236 | //Explaination : shift and pop use to remove the elements from first and last index. 237 | -------------------------------------------------------- 238 | //check the value is even or odd 239 | let a =10; 240 | console.log(a%2===0 ? true : false); //true 241 | //Explaination : Need to divide by 2 and then checking if reminder is zero/one. 242 | ---------------------------------------------------------- 243 | let data ={ name : "priya"}; 244 | delete data.name; 245 | console.log(data); //{} 246 | //Explaination : delete always work with object properties not a object itself. 247 | --------------------------------------------------------- 248 | let data ="true"; 249 | //convert data into boolean false value 250 | console.log(!data); //false 251 | console.log(typeof !data); //boolean 252 | //Explaination : ! will make boolean value(or opposite value). 253 | --------------------------------------------------------- 254 | let data ="true"; 255 | //convert data into boolean true value 256 | console.log(!!data); //true 257 | console.log(typeof !!data); //boolean 258 | //Explaination : ! will make boolean value(or opposite value). 259 | --------------------------------------------------------- 260 | Diff between Map and foreach: Map will return new thing but Foreach didn't return anything. 261 | --------------------------------------------------------- 262 | let data = ["piya", "priya", "supriya"]; 263 | delete data[1]; 264 | console.log(data); //["piya",,"supriya"] //["piya",empty,"supriya"] 265 | console.log(data.length); //3 266 | //Explaination : Whenever element deleted from an object it will create a empty space. Array length will always reain same. 267 | ------------------------------------------------------------- 268 | //merge 2 arrays 269 | const a =[1,2,3]; 270 | const b =[4,5,6]; 271 | const c =[...a, ...b] 272 | console.log(c); //[1,2,3,4,5,6] 273 | //Explaination : using spread operator 274 | ---------------------------------------------------------------- 275 | const a =[1,2,3]; 276 | const b =[3,4,5,6]; 277 | const c =[...a, ...b] 278 | console.log(c); //[1,2,3,3,4,5,6] 279 | //Explaination : using spread operator still we can merge and both values will be present in arrays. But in an object, it will take the lates value and assigned to the 1st position of that key. 280 | ------------------------------------------------------------------- 281 | let c = 3**3; 282 | console.log(c); //27 283 | console.log(3*3); //9 284 | //Explaination : 3 square 3 means 3*3*3 285 | --------------------------------------------------------------------- 286 | let a=2; 287 | setTimeout(()=>{ 288 | console.log(a); //100 289 | },0) 290 | a=100; 291 | //Explaination : Here we are using zero time interval. setTimeout is async function so it will execute at last. Firstly all the sync code will get execute. so that's why 100 is assigned to a. 292 | ------------------------------------------------------------------------ 293 | let a =2; 294 | let A =30; 295 | console.log(A); //30 296 | //Explaination : a and A both are diff variables. 297 | ------------------------------------------------------------------------ 298 | let A10="hello"; 299 | let 10A ="hi"; 300 | console.log(A10); //hello 301 | //console.log(10A); //error 302 | //Explaination : Variable can't start with a number. 303 | ------------------------------------------------------------------------ 304 | let a="hello"; 305 | let b =`hello`; 306 | console.log(a === b); //true 307 | console.log(a == b); //true 308 | //Explaination : Doble code and backticks both are same. 309 | -------------------------------------------------------------------------- 310 | let a =1; 311 | let c =2; 312 | console.log(--c === a); //true 313 | //Explaination : --c will be 1 so thats why true. 314 | -------------------------------------------------------------------------- 315 | let a =1; 316 | let b =1; 317 | let c =2; 318 | console.log(a === b === -c); //false 319 | //Explaination : a===b gives True. true === -c(number) gives false. 320 | --------------------------------------------------------------------------- 321 | console.log(3*3); //9 322 | console.log(3**3); //27 323 | //console.log(3***3); //error 324 | //Explaination : *** doesn't exist in js. 325 | ---------------------------------------------------------------------------- 326 | console.log(a); //undefined 327 | var a; 328 | //Explaination : We can use VAR variable before its declaration. We didn't assign any value but still by default "undefined" will be store in it.undefined means declared but value didn't initialised. 329 | ----------------------------------------------------------------------------- 330 | console.log(a); //not defined 331 | //Explaination : Not defined means variable didn't even declared.Also value is not assogned. 332 | ----------------------------------------------------------------------------- 333 | console.log([[[]]]); //[[[]]] 334 | //Explaination : It will print the nested array. We will get 3 nested array and each one have 1 element but at the last array will be empty. 335 | ------------------------------------------------------------------------------ 336 | How to find Operating system name? 337 | navigator.plateform we can use it. //win32 338 | ------------------------------------------------------------------------------- 339 | let for = 100; //Error 340 | //Explaination : For is a reserved keyword. 341 | ------------------------------------------------------------------------------- 342 | function fruit(){ 343 | console.log(name); //undefined 344 | console.log(price); //Error 345 | var name = "priya"; 346 | let price = 1000; 347 | } 348 | fruit() 349 | //Explaination : Hoisting concept used here. Error because in LET declaration first then only we can use it. but in var we can use brfore its declaration. 350 | ------------------------------------------------------------------------------- 351 | for(var i=0; i<3; i++){ //i=0 //1 //2 //3 352 | setTimeout(()=>console.log(i),1) // 3,3,3 353 | } 354 | //Explaination : Var is a global variable. Firstly Sync code get executed then async code will start to execute. so i value incremented from 0 to 3 when pointer reaches to setTimeout so it will print 3 thrice time. 355 | --------------------------------------------------- 356 | for(let i=0; i<3; i++){ //i=0 //1 //2 //3 357 | setTimeout(()=>console.log(i),1) //0 //1 //2 358 | } 359 | //Explaination : LET is a block scope. so it will print 0,1,2. Its having own islocated scope. 360 | ---------------------------------------------------- 361 | console.log(+true); //1 362 | console.log(typeof +true); //number 363 | //Explaination : if we write + in front of anything then it will convert into a number. 364 | ---------------------------------------------------- 365 | console.log(!"priya"); //false 366 | console.log(typeof ("priya")); //string 367 | //Explaination : ! will give either true/false.! means false and !! means true. 368 | ---------------------------------------------------- 369 | let data = "size"; 370 | const bird = {size : "small"} 371 | console.log(bird[data]); //small 372 | console.log(bird["size"]); //small 373 | console.log(bird.size); //small 374 | console.log(bird.data); //undefined 375 | //Explaination : If we wants to access variable with object then use [] notation(. notation will not work). 376 | ------------------------------------------------------ 377 | let c = {name : "priya"}; 378 | let d; 379 | d=c; 380 | c.name = "supriya"; 381 | console.log(d.name); //supriya 382 | //Explaination : Using assignment operator we are accessing the same memory allocation. 383 | ------------------------------------------------------- 384 | var x; 385 | var x=10; 386 | console.log(x); //10 387 | //Explaination : Can be declare multiple times. 388 | --------------------------------------------------------- 389 | var x; 390 | let x=10; 391 | console.log(x); //Error 392 | //Explaination : Can't be declare multiple times with LET. 393 | ---------------------------------------------------------- 394 | let a = 3; 395 | let b = new Number(3); 396 | console.log(a == b); //true 397 | console.log(a === b); //false 398 | console.log(typeof b); //object 399 | //Explaination : === will give false because a will give number but b will give an object. 400 | ------------------------------------------------------- 401 | let name; 402 | nmae ={}; //wrong variable name i wrote 403 | console.log(name); //undefined 404 | //Explaination : by default it wil be undefined if we declare first. 405 | --------------------------------------------------------- 406 | function first(){ 407 | console.log("Woof!!"); //Woof!! 408 | } 409 | first.name = "apple"; 410 | first(); 411 | //Explaination : To add the property with a function then it will not create a impact. 412 | ---------------------------------------------------------- 413 | function sum(a,b){ 414 | return a+b; 415 | } 416 | console.log(sum(1, "2")); //12 417 | //Explaination : 2 is passed as a string so it will get concat. num+string = string 418 | ------------------------------------------------------------ 419 | let num = 0; 420 | console.log(num++); //0 421 | console.log(++num); //2 422 | console.log(num); //2 423 | //Explaination : ++ will increase the value by 1. preincrement and postincrement used here. 424 | -------------------------------------------------------------- 425 | function getAge(...args){ //[1000] 426 | console.log(typeof args); //object 427 | } 428 | getAge(1000); 429 | //Explaination : typeof args means typeof an array means typeof [] is object. 430 | -------------------------------------------------------------- 431 | function getAge(){ 432 | age = 1000; 433 | console.log(age); //1000 434 | } 435 | getAge(); 436 | //Explaination : if we didn't declare with Var/Let/const then by default it will become as a Var. 437 | ------------------------------------------------------------------ 438 | function getAge(){ 439 | 'use strict' 440 | age = 1000; 441 | console.log(age); //error 442 | } 443 | getAge(); 444 | //Explaination : Use strict wil give a error because it forces to use a proper way of the variable declaration. 445 | ---------------------------------------------------------------------- 446 | const sum = eval('10*10+5'); 447 | console.log(sum); //105 448 | //Explaination : It will perform the numerical operation 449 | ---------------------------------------------------------------------------- 450 | const obj = {1:"a", 2:"b"} 451 | console.log(obj.hasOwnProperty("1")); //true 452 | console.log(obj.hasOwnProperty(1)); //true 453 | //Explaination : "1" and 1 treat as same. 454 | ---------------------------------------------------------------------------- 455 | const obj = {a:"one", b: "two", a:"three"} 456 | console.log(obj); // {a:"three", b: "two"} 457 | //Explaination : Key position will be same but tha value get updated with new value in object. 458 | ---------------------------------------------------------------------------- 459 | for(let i=1; i<5; i++){ 460 | if(i==3) continue; 461 | console.log(i); //1,2,4 462 | } 463 | //Explaination : If i =3 then it will not execute the code for 3, but can execute for i=4. 464 | ------------------------------------------------------------------------------ 465 | const foo = () => console.log("first"); 466 | const bar = () => setTimeout(()=> console.log("second")); 467 | const baz = () => console.log("third"); 468 | bar(); 469 | foo(); 470 | baz(); 471 | //Explaination : first,third, second. Because asyn operation work post all the syn operation get complete. 472 | ---------------------------------------------------------------------------- 473 |
474 |
475 | 478 |
479 |
480 | //Explaination : button, second div, first div. Even bubbling happened here. 481 | --------------------------------------------------------------------------- 482 | const person = {name:'priya'}; 483 | function sayHi(age){ 484 | return `${this.name} is ${age}`; 485 | } 486 | console.log(sayHi.call(person,21)); //"priya is 21" 487 | console.log(sayHi.bind(person,21)); //it will return a function. //function sayHi(age){ return `${this.name} is ${age}`;} 488 | console.log(sayHi.bind(person,21)()); //"priya is 21" 489 | //Explaination : Bind will always return a function so require to invoke the function. 490 | ------------------------------------------------------------------------------ 491 | function sayHi(){ 492 | return (()=>0)(); 493 | } 494 | console.log(typeof sayHi()); //number 495 | //Explaination : sayHi will return anonymous arrow function/IIFE, where it will return 0. type of 0 is number. 496 | ---------------------------------------------------------------------------- 497 | function sayHi(){ 498 | return ()=>0; 499 | } 500 | console.log(typeof sayHi()); //function 501 | console.log(typeof sayHi()()); //function 502 | //Explaination : sayHi will return anonymous arrow function/IIFE, where we didn't invole the arroe function so it will return function. 503 | ----------------------------------------------------------------------------- 504 | console.log(typeof typeof 1); //string 505 | //Explaination : typeof 1 is a number and typeof number is a string. 506 | ----------------------------------------------------------------------------- 507 | const numbers = [1,2,3]; 508 | numbers[6]=11; 509 | console.log(numbers); //[1,2,3,,,,11] 510 | //Explaination : Array store elements in a continuous memory location. It will give empty in between an array. 511 | ------------------------------------------------------------------------------- 512 | const numbers = [1,2,3]; 513 | numbers[9]=numbers; 514 | console.log(numbers); //[1,2,3,,,,.......] 515 | //Explaination: It will print infinite loop. 516 | ------------------------------------------------------------------------------- 517 | console.log(!!null); //false 518 | console.log(!!""); //false 519 | console.log(!!1); //true 520 | //Explaination: !null give true and !!null give false. !1 give false and then !!1 give true. 521 | ------------------------------------------------------------------------------- 522 | console.log(setInterval(()=>console.log('Hi'), 1000)); 523 | console.log(setInterval(()=>console.log('Hi'), 1000)); 524 | console.log(setInterval(()=>console.log('Hi'), 1000)); 525 | //Explaination: setInterval will give uniques id to stop. It will give like 1,2,3. so it will print 1,2,3,Hi,Hi, Hi, Hi, Hi, .....so on. 526 | ------------------------------------------------------------------------------ 527 | console.log(setTimeout(()=>console.log('Hi'), 1000)); 528 | console.log(setTimeout(()=>console.log('Hi'), 1000)); 529 | console.log(setTimeout(()=>console.log('Hi'), 1000)); 530 | //Explaination : it will print 1,2,3,Hi,Hi, Hi. 531 | ------------------------------------------------------------------------------- 532 | console.log([..."priya"]); //["p","r","i","y","a"] 533 | //Explaination: It will convert into an array. 534 | ------------------------------------------------------------------------------- 535 | const firstPromise = new Promise((res, rej)=>{ 536 | setTimeout(res, 500, 'one'); 537 | }) 538 | const secondPromise = new Promise((res, rej)=>{ 539 | setTimeout(res, 100, 'second'); 540 | }) 541 | Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); 542 | //Explaination: Race will return only first matching result so it will print 100. For 500 it will take time to execute so it will not get print. 543 | ----------------------------------------------------------------------------------- 544 | let person = {name: "priya"}; 545 | const numbers = [person]; 546 | person = null; 547 | console.log(numbers, person); // [{name : "priya"}] //null 548 | //Explaination: We try to empty the objecti,e person, but still an array i.e, numbers conatin value so it will not create an impact while assigning null to person. 549 | ---------------------------------------------------------------------------------- 550 | const person = {name: "priya", age: 1000}; 551 | for(const item in person){ 552 | console.log(item); //name, age 553 | } 554 | //Explaination: For in loop give a keys only. 555 | -------------------------------------------------------------------------------------- 556 | let data = 3+4+'5'; 557 | console.log(data); //"75" 558 | console.log(typeof data); //string 559 | //Explaination: It will add as a string. 560 | ------------------------------------------------------------------------------------------ 561 | console.log(typeof 3+4+'5'); //"number45" 562 | //Explaination: operation went from left to right side. 563 | ---------------------------------------------------------------------------------------- 564 | console.log(typeof (3+4+'5')); //"75" //string 565 | console.log(typeof (3+4+ +'5'));//number 566 | //Explaination: To find out the typeof when the all the operation get complete thrn have to enclose in paranethisis. If we add + plus sign to any string it will convert to a number. 567 | ---------------------------------------------------------------------------------------- 568 | let data = [1,2,3].map( num =>{ 569 | if (typeof num === 'number') return; 570 | return num*2; 571 | }) 572 | console.log(data); //[undefined,undefined,undefined] 573 | //Explaination: If jusr return then it will print undefined. 574 | ---------------------------------------------------------------------------------------- 575 | function getInfo(member){ 576 | member.name = "priya"; 577 | } 578 | const person = {name : "supriya"} 579 | getInfo(person); 580 | console.log(person); //{"name":"priya"} 581 | //Explaination: If we pass an object as argument it will have call by refrence, means having same memory location. 582 | ---------------------------------------------------------------------------------------- 583 | function Car(){ 584 | this.make = "tata"; 585 | return {make: "kia"}; 586 | } 587 | const myCar = new Car(); 588 | console.log(myCar.make); //kia 589 | //Explaination: return will overrite the property.If we didn't return then it will print tata. 590 | ---------------------------------------------------------------------------------------- 591 | (()=>{ 592 | let x = (y = 10); 593 | })() 594 | console.log(typeof x, y); //"undefined" //10 595 | //Explaination: x is a block scope, and we are trying to console x outside of x so that's why undefined. 596 | ----------------------------------------------------------------------------------------- 597 | (()=>{ 598 | let x = y = 10; 599 | })() 600 | console.log(typeof y); //number 601 | //Explaination: x is a block scope, and y is a var because y is not declared so by default it will be var. 602 | ---------------------------------------------------------------------------------------- 603 | (()=>{ 604 | let x = 10; 605 | })(); 606 | (()=>{ 607 | let x = 10; 608 | })(); 609 | console.log(typeof x); //undefined 610 | //Explaination: x is a block scope. 611 | --------------------------------------------------------------------------------------- 612 | (()=>{ 613 | let x = y = 10; 614 | })(); 615 | (()=>{ 616 | let x = y = 20; 617 | })(); 618 | console.log(y); //20 619 | //Explaination: y is a var scope so it will overrite from 10 to 20 620 | ----------------------------------------------------------------------------------------- 621 | let x =100; 622 | (()=>{ 623 | var x = 10; 624 | })(); 625 | console.log(x); //100 626 | //Explaination: x=10 contain inside a block because we already declare with 100 outside so it will print 100. 627 | ------------------------------------------------------------------------------------------- 628 | const func = (function(a){ 629 | delete a; 630 | return a; 631 | } )(5) 632 | console.log(func); 633 | 634 | output: 5 635 | //delete keyword only use with object properties. here a is a variable so it will not work the variable. //delete user.age 636 | ------------------------------------------------------------------------------------------ 637 | Dynamic property of object : 638 | const property = "firstName"; 639 | const name = "Priya"; 640 | 641 | const user = { 642 | property : name //{"property" : "Priya"} 643 | } 644 | console.log(user); 645 | 646 | const user1 = { 647 | [property] : name //dynamic property required [] //{"firstName" : "Priya"} 648 | } 649 | console.log(user1); 650 | ------------------------------------------------------------------------------------------ 651 | const user ={ 652 | name : "priya", 653 | age : 100 654 | } 655 | 656 | //iterate through keys 657 | for(let item in user){ 658 | console.log(item) //name age 659 | } 660 | //iterate through values 661 | for(let item in user){ 662 | console.log(user[item]) //priya 100 663 | } 664 | ------------------------------------------------------------------------------------------ 665 | const user ={ 666 | name : "priya", 667 | age : 100 668 | } 669 | 670 | //double the age as 200 //iterate through keys 671 | for(let item in user){ 672 | if(typeof user[item] === "number"){ 673 | user[item]*=2 674 | } 675 | } 676 | 677 | console.log(user) 678 | ------------------------------------------------------------------------------------------ 679 | const a = {} 680 | const b = {key : "b"} 681 | const c = {key : "c"} 682 | 683 | a[b] = 123; 684 | a[c] = 456; 685 | console.log(a[b]); //456 686 | 687 | //console.log(a) //{"[object Object]" : 456} 688 | //here object is not converted into a string so printing key as object Object. 689 | //so for both it will be 690 | //a["[object Object]"] = 123; 691 | //a["[object Object]"] = 456; 692 | //it get override by 456. 693 | ------------------------------------------------------------------------------------------ 694 | const user = { 695 | name :"priya", 696 | age : 100 697 | } 698 | //convert into a string 699 | const str = JSON.stringify(user) 700 | console.log(str)//{'name':'priya','age':100}" 701 | 702 | //convert string onto an object 703 | console.log(JSON.parse(str)) //{ name : "priya, "age":100} 704 | 705 | 706 | ***************** 707 | Real Usecases : Storing in local storage. We can't store the object as a value so require to convert into a string. 708 | const user = { 709 | name :"priya", 710 | age : 100 711 | } 712 | console.log(JSON.stringify(user)) //convert into a string 713 | console.log(JSON.parse(JSON.stringify(user))) //convert into an object 714 | 715 | localStorage.setItem("testAsKey", JSON.stringify(user)) {"name":"priya","age":100} 716 | localStorage.setItem("testAsKey", user) //[object Object] beacuse we are forcefully trying to convert in a string 717 | 718 | JSON.parse(localStorage.getItem("testAsKey")) //will get as a object 719 | ------------------------------------------------------------------------------------------ 720 | const user = { 721 | name :"priya", 722 | age : 100 723 | } 724 | console.log(JSON.stringify(user,["name"])) //"{'name':'priya'}" 725 | 726 | //wheen we pass as a array then it will convernt only those properties and ignore rest of the proerties 727 | ------------------------------------------------------------------------------------------ 728 | const shape = { 729 | radius : 10, 730 | diameter(){ 731 | return this.radius*2; //this pointing to shape 732 | } 733 | parimeter : () => 2*Math.PI*this.radius; //this pointing to window where it's not exist 734 | } 735 | console.log(shape.diameter()) //20 736 | //console.log(shape.parimeter()) //Nan 737 | ------------------------------------------------------------------------------------------- 738 | let user = { 739 | name : "Priya", 740 | age : 100 741 | } 742 | 743 | const name = "Supriya"; 744 | //const {name} = user; //Identifier 'name' has already been declared 745 | const {name : myName} = user; 746 | 747 | console.log(myName) //Priya 748 | ------------------------------------------------------------------------------------------- 749 | let user = { 750 | age : 100, 751 | fullName : { 752 | first : "Priya", 753 | last : "Bagde" 754 | } 755 | } 756 | 757 | const {fullName : {first}} = user; 758 | console.log(first); //"Priya" 759 | //Destructuring at deep nested 760 | ------------------------------------------------------------------------------------------- 761 | let c = {greeting : "Hey!"} 762 | let d; 763 | 764 | d=c; 765 | c.greeting = "Hello" 766 | console.log(d.greeting); //Hello 767 | //We are passing the refrence not the propertues of an object so when we changge the roperty of any object it will reflect in both objects 768 | ------------------------------------------------------------------------------------------- 769 | let person = {name : "priya"} 770 | const members = [person] 771 | person = null 772 | console.log(members);// [{"name":"priya"}] 773 | 774 | let person = {name : "priya"} 775 | const members = [person] 776 | person.name = null 777 | console.log(members);// [{"name":null}] 778 | //because we are modifying the property of object 779 | ------------------------------------------------------------------------------------------- 780 | Ways to make deep copy: 781 | 1. object.assign 782 | 2. {...obj} 783 | 3. JSON.parse(JSON.stringyfy(obj)) 784 | ------------------------------------------------------------------------------------------- 785 | console.log(1); 786 | 787 | function print(name){ 788 | setTimeout(()=>{ 789 | return `${name}` 790 | },1000) 791 | } 792 | let value = print("Priya"); 793 | console.log(value) 794 | 795 | console.log(2); 796 | Reason : It run the code quickly and it will not wait for setTimeout so value will be undefined 797 | --------------------------------------------------- 798 | Above code can be fix by callback: 799 | console.log(1); 800 | function print(name, cb){ 801 | setTimeout(()=>{ 802 | cb(`${name}`) 803 | },1000) 804 | } 805 | print("Priya", (value)=>{ 806 | console.log(value) 807 | }); 808 | console.log(2); 809 | ------------------------------------------------------------------------------------------- 810 | let promises = new Promise((resolve, reject)=>{ 811 | setTimeout(()=>{ 812 | let state = true; 813 | if(state){ 814 | resolve("Resolved Promises!!..."); 815 | }else{ 816 | reject("Rejected Promises!!..."); 817 | } 818 | }, 1000) 819 | }) 820 | promises.then((res)=>console.log(res)) 821 | .catch((err)=>console.log(err)) 822 | //resoled!!.... 823 | ------------------------------------------------------------------------------------------- 824 | console.log(1); 825 | 826 | const data = new Promise((resolve, reject)=>{ 827 | console.log(2); 828 | resolve(3); 829 | }) 830 | 831 | data.then((res)=>{ 832 | console.log(res) 833 | }) 834 | 835 | console.log(4); //1 2 4 3 836 | ------------------------------------------------------------------------------------------- 837 | console.log(1); 838 | 839 | const data = new Promise((resolve, reject)=>{ 840 | console.log(2); 841 | //resolve(3); 842 | }) 843 | 844 | data.then((res)=>{ 845 | console.log(res) 846 | }) 847 | 848 | console.log(4); //1 2 4 849 | If we are not returning anything it will not print anything . 850 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 851 | let a = "true"; 852 | setTimeout(()=>{ 853 | a=false; 854 | }, 2000) 855 | 856 | while(a){ 857 | console.log("1") 858 | } 859 | 860 | Reason: 1, 1, 1,...... 861 | Explanation: Event loop will add setTimeout callback in Macrotask queue and will push it to call stack for execution only when the main thread finishes executing. 862 | 863 | Here, since 'a' is true and isn't being set to false anywhere in main thread, the while loop will run infinitely, and setTimeout callback will never get a chance to run. 864 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 865 | function run(value, time){ 866 | return new Promise((resolve)=>{ 867 | setTimeout(()=>{ 868 | resolve(value) 869 | }, time) 870 | }) 871 | } 872 | async function task(){ 873 | let a = await run(1, 1000); //1value //1 sec 874 | let b = run(2, 2000); //2value //2 sec 875 | let c = run(3, 1000); //3value //execute before b so will not take extra time 876 | console.log(a + await b+ await c); 877 | } 878 | task() 879 | 880 | 6 'in 3Sec' 881 | 882 | Explanation: In line 10, a setTimeout() timer of 1 sec will be triggered and due to 'await', it will wait for the timer to expire, and after 1 sec, value of a is 1. 883 | 884 | Then since there is no 'await' in line 11 and 12, the 2 timers of 2 sec and 1 sec will be triggered simultaneously. Then in line 14, since b hasn't been resolved, due to await, it will wait for another 2 sec, and since the 2 timers started simultaneously, the other 1 sec timer would already have expired. 885 | 886 | So, after another 2 sec, value of b will be 2, and then immediately after that, value of c will be 3. 887 | 888 | 👉 Output : 1 + 2 + 3 = 6 889 | 👉 Total time: 1 (line 10) + 2 (await b, in line 14) + 0 (await c, in line 14) = 3 sec 890 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 891 | const fetchData = function(){ 892 | return new Promise((res, reject)=>{ 893 | reject("Error!!") 894 | }) 895 | } 896 | 897 | fetchData() 898 | .then(null, (err)=>{ 899 | console.log("First"); 900 | console.log(err); 901 | }) 902 | .catch(()=>{ 903 | console.log("Second"); 904 | console.log(err) 905 | }) 906 | 907 | Explaination : "First" "Error!!" 908 | reject("Error!!") gives string value so it will go to THEN block rather than CATCH block. 909 | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 910 | displayName(); 911 | var displayName = function(){ 912 | console.log("Priya") 913 | } 914 | function displayName(){ 915 | console.log("dolly") 916 | } 917 | displayName(); 918 | 919 | //Explaination : dolly priya 920 | 921 | Normal function will get execute before, because of function Hoisting concept, then function expression wil get execute. 922 | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 923 | const inc = async(x) => { 924 | x = x + await 1; //2 925 | return x; 926 | } 927 | 928 | const increment = async(x) =>{ 929 | x = x+1; //2+1 930 | return x; //3 931 | } 932 | inc(1) 933 | .then((x)=>{ //2 934 | increment(x) //2 935 | .then((x)=>console.log(x)) //3 936 | }) 937 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 938 | const p1 = Promise.resolve("First"); 939 | const p2 = Promise.reject("Second"); 940 | const p3 = Promise.resolve("Third"); 941 | const runPromise = async() =>{ 942 | try{ 943 | const res = await Promise.all([p1,p2,p3]); 944 | console.log(res); 945 | } 946 | catch(err){ 947 | console.log(err) 948 | } 949 | } 950 | runPromise(); 951 | 952 | //output : Second 953 | 954 | Promise.all() returns array of resolved promises values and if either any of the promise is rejected, then it directly returns the rejected promise value through catch block. 955 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 956 | console.log("start"); 957 | 958 | async function getData(){ 959 | console.log("priya"); 960 | return "Dolly"; 961 | } 962 | 963 | getData() 964 | .then((res)=> console.log(res)); 965 | 966 | console.log("end"); 967 | //start priya end Dolly 968 | //all the console will print first then aync and setTimeout 969 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 970 | const promise = () => Promise.resolve("Success"); 971 | function first(){ 972 | promise().then((res)=> console.log(res)); //async 973 | console.log("First"); //sync 974 | } 975 | async function second(){ 976 | const res = await promise(); 977 | console.log(res); //async 978 | console.log("Second"); //sync 979 | } 980 | first(); 981 | second(); 982 | 983 | // First Sucess success second 984 | // sync(console) run hen async(promise) 985 | //await pause the line of execution 986 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 987 | const person1 = { 988 | name : "Priya" 989 | } 990 | const person2 = { 991 | name : "Dolly" 992 | } 993 | const person = Object.assign(person1, person2); 994 | 995 | console.log(person); //{"name" : "Dolly"} 996 | console.log(person.name); //Dolly 997 | console.log(person1.name); //Dolly 998 | console.log(person2.name); //Dolly 999 | 1000 | //Having same key name so, the value is override and it will be "Dolly" 1001 | 1002 | Explanation : As Object.assign() method will add all the key values of person2 to person1 and return the reference of person1 to person and if same key are there they'll be overwritten. 1003 | Basically person1 and person are referring to same object. 1004 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1005 | const calc=(a)=>{ 1006 | return (b)=>{ 1007 | if(b) return calc(a+b); 1008 | return a; 1009 | } 1010 | } 1011 | console.log(calc(1)(2)(3)(4)()) //10 currying 1012 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1013 | const fetchData = function(){ 1014 | return new Promise((res)=> res("One")); 1015 | } 1016 | let isLoading = true; 1017 | fetchData() 1018 | .then((result)=>{ 1019 | console.log(result); 1020 | }) 1021 | .finally(()=>{ 1022 | console.log("Two"); 1023 | isLoading = false; 1024 | }) 1025 | console.log(isLoading) 1026 | 1027 | //true one two 1028 | //console value run first 1029 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1030 | 1031 | const person = { 1032 | name : "Priya", 1033 | displayName(){ 1034 | console.log(this.name) //pointing to the person object 1035 | } 1036 | } 1037 | 1038 | const jayesh = Object.create(person) 1039 | person.displayName(); //Priya 1040 | console.log(jayesh); //{} 1041 | jayesh.displayName(); //Priya 1042 | I believe Object.create() creates a new object from the existing object, and both have the same memory addresses. 1043 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1044 | let p = new Promise((resolve, reject)=>{ 1045 | reject(Error("Failed!!")) 1046 | }) 1047 | 1048 | p.catch((error)=>{ 1049 | console.log(error); //{} 1050 | console.log(error.message); //failed 1051 | }).then((result)=>{ 1052 | console.log(result) //undefined //doesn't return anything 1053 | }) 1054 | 1055 | //Failed!! undefined 1056 | Explanation: In line 2, we are rejecting the promise 'p' with the argument as Error("Fails!"), which is an 'Error' object with property 'message' set to 'Fails!'. So, in line 5, the error callback passed to catch() method of promise 'p' receives the above passed Error object as the 'error' parameter, and so 'error.message' (Fails!) is printed. 1057 | 1058 | Now, as this catch handler is not returning any value so, the chained 'then' handler will be called with undefined as parameter. 1059 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1060 | 1061 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1062 | 1063 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1064 | 1065 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1066 | 1067 | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1068 | /* 💡"JavaScript-with-JC" - Guess the Output? */ 1069 | 1070 | // 👉 MCQ-1 1071 | function MCQ1() { 1072 | const person = { 1073 | name: "Jayesh", 1074 | displayName1: function () { 1075 | console.log("name1", this.name); 1076 | }, 1077 | displayName2: () => { 1078 | console.log("name2", this.name); 1079 | }, 1080 | }; 1081 | person.displayName1(); 1082 | person.displayName2(); 1083 | 1084 | // 👍A) name1 Jayesh , name2 Jayesh 1085 | // 💡B) name1 Jayesh , name2 undefined 1086 | // 💖C) name1 Jayesh , name2 1087 | // 😀D) name1 , name2 Jayesh 1088 | 1089 | /* 1090 | In window browser answer is C) name1 Jayesh , name2 because arrow function inherits "this" from its outer function where "this" is window. 1091 | and window has by default property name that is used for setting or returning the name of a window and in above case window.name is empty string. 1092 | 1093 | In other compilers answer is B) name1 Jayesh , name2 undefined because arrow function inherits "this" from its outer function where "this" refers to global object. 1094 | */ 1095 | } 1096 | // MCQ1(); 1097 | 1098 | // 👉 MCQ-2 1099 | function MCQ2() { 1100 | let name = "Jayesh"; 1101 | function printName() { 1102 | if (name === "Jayesh") { 1103 | let name = "JC"; 1104 | console.log(name); 1105 | } 1106 | console.log(name); 1107 | } 1108 | printName(); 1109 | 1110 | // 👍A) Jayesh 💡B) Jayesh, JC 1111 | // 💖C) JC, JC 😀D) JC, Jayesh 1112 | 1113 | /* Answer is D) JC, Jayesh because let variables are block scope, name inside if condition will shadow outer name*/ 1114 | } 1115 | // MCQ2(); 1116 | 1117 | // 👉 MCQ-3 1118 | function MCQ3() { 1119 | var player = "Virat"; 1120 | function displayPlayer() { 1121 | if (player === "Virat") { 1122 | var player = "VK"; 1123 | console.log(player); 1124 | } 1125 | console.log(player); 1126 | } 1127 | displayPlayer(); 1128 | 1129 | // 👍A) VK, Virat 💡B) VK, VK 1130 | // 💖C) undefined 😀D) VK, undefined 1131 | 1132 | /* 1133 | Answer is C) undefined because var variables are functional scope, When displayPlayer fn starts executing, Execution context of 1134 | displayPlayer will be created in callstack and at the memory creation phase var variable player is initialized as undefined. 1135 | hence if condition will become false and It will print only undefined. 1136 | */ 1137 | } 1138 | // MCQ3(); 1139 | 1140 | // 👉 MCQ-4 1141 | function MCQ4() { 1142 | const person = { 1143 | name: "Jayesh", 1144 | age: 24, 1145 | }; 1146 | 1147 | const getAge = person.age; 1148 | delete person.age; 1149 | 1150 | console.log(person); 1151 | console.log(getAge); 1152 | 1153 | // 👍A) { name: 'Jayesh', age: 24 }, null 1154 | // 💡B) { name: 'Jayesh' }, 24 1155 | // 💖C) { name: 'Jayesh' }, undefined 1156 | // 😀D) { name: 'Jayesh', age: 24 }, 24 1157 | 1158 | /* 1159 | Answer is B) { name: 'Jayesh' }, 24 because delete keyword deletes property of an object and we are setting getAge as pass by value. 1160 | */ 1161 | } 1162 | // MCQ4(); 1163 | 1164 | // 👉 MCQ-5 1165 | function MCQ5() { 1166 | // No Strict Mode 1167 | name = "Jayesh"; // window.name ( property of window object ) 1168 | console.log(delete name); 1169 | 1170 | const displayName = (function (name) { 1171 | console.log(delete name); // Local variable of function 1172 | return name; 1173 | })("JC"); 1174 | 1175 | console.log(displayName); 1176 | 1177 | // 👍A) true, false, JC 1178 | // 💡B) true, true, undefined 1179 | // 💖C) false, false, JC 1180 | // 😀D) false, true, undefined 1181 | 1182 | /* 1183 | Answer is A) true, false, JC because delete keyword deletes only property of an object. 1184 | delete keyword can not delete local variables ( declared with var, let, and const ) and functions. 1185 | delete keyword can delete global variables as they are property of window object. 1186 | */ 1187 | } 1188 | // MCQ5(); 1189 | 1190 | // 👉 MCQ-6 1191 | function MCQ6() { 1192 | const arr = []; 1193 | 1194 | for (var i = 0; i < 5; i++) { 1195 | arr[i] = function () { 1196 | return i; 1197 | }; 1198 | } 1199 | 1200 | console.log(arr[0]()); 1201 | console.log(arr[4]()); 1202 | 1203 | // 👍A) 0, 4 💡B) 4, 4 1204 | // 💖C) 5, 5 😀D) TypeError 1205 | 1206 | /* 1207 | Answer is C) 5, 5 because variables declared with var keyword are function-scoped or globally-scoped but not blocked scoped. 1208 | Inner function will form the closure and points to the updated value of i that is 5. 1209 | In the case of Let variable, as they are blocked scoped so inner function will hold different values of i from 0 to 4. 1210 | */ 1211 | 1212 | /* 👇 In the case of Let variable */ 1213 | const arrBlock = []; 1214 | 1215 | for (let i = 0; i < 5; i++) { 1216 | arrBlock[i] = function () { 1217 | return i; 1218 | }; 1219 | } 1220 | 1221 | console.log(arrBlock[0]()); // 0 1222 | console.log(arrBlock[4]()); // 4 1223 | } 1224 | // MCQ6(); 1225 | 1226 | // 👉 MCQ-7 1227 | function MCQ7() { 1228 | let person = { name: "Jayesh" }; 1229 | const personArray = [person]; 1230 | person = null; 1231 | console.log(personArray); 1232 | 1233 | personArray = []; 1234 | console.log(personArray); 1235 | 1236 | // 👍A) [ { name: "Jayesh" } ], [] 1237 | // 💡B) [ { name: "Jayesh" } ] , TyperError 1238 | // 💖C) [ null ], TypeError 1239 | // 😀D) [ {} ], [] 1240 | 1241 | /* 1242 | Answer is B) [ { name: "Jayesh" } ] , TyperError because person = null will only disconnect the person variable from value { name: "Jayesh"} which is stored in memory, personArray[0] will still point to same value { name: "Jayesh"}. 1243 | and personArray = [] at this line TyperError as const variable can't be redeclared and throws Uncaught TypeError: Assignment to constant variable. 1244 | */ 1245 | } 1246 | // MCQ7(); 1247 | 1248 | // 👉 MCQ-8 1249 | function MCQ8() { 1250 | const value = { number: 10 }; 1251 | 1252 | const addition = (x = { ...value }) => { 1253 | console.log((x.number += 5)); 1254 | }; 1255 | 1256 | addition(); 1257 | addition(); 1258 | addition(value); 1259 | addition(value); 1260 | 1261 | // 👍A) 15, 20, 25, 30 💡B) 15, 15, 20, 25 1262 | // 💖C) 15, 15, 15, 15 😀D) 15, 15, 15, 20 1263 | 1264 | /* 1265 | Answer is D) 15, 15, 15, 20 because when we call addition function 3rd time with passing value object as an argument, then x will take value as pass by reference and will update number property of original object ( value in this case ) to 15. 1266 | Hence, while calling addition function 4th time will console 15 + 5 => 20. 1267 | */ 1268 | } 1269 | // MCQ8(); 1270 | 1271 | // 👉 MCQ-9 1272 | function MCQ9() { 1273 | function makePerson() { 1274 | return { 1275 | userName: "Jayesh", 1276 | ref: this, 1277 | }; 1278 | } 1279 | 1280 | const person = makePerson(); 1281 | console.log(person.ref.userName); 1282 | 1283 | // 👍A) Jayesh 💡B) "" 1284 | // 💖C) undefined 😀D) TypeError 1285 | 1286 | /* 1287 | Answer is C) undefined because "this" keyword in makePerson function will refer to the window object, 1288 | person.ref.userName is same as Window.userName and no property named with userName is present in window object, Hence It will console undefined. 1289 | */ 1290 | 1291 | // 👇 We can get "Jayesh" as an output by doing small change in above question :- 1292 | function makePerson2() { 1293 | return { 1294 | userName: "Jayesh", 1295 | // 👇 Here, We have assigned a function to ref property of an object, and function's "this" will point to the returned object. 1296 | ref: function () { 1297 | return this; 1298 | }, 1299 | }; 1300 | } 1301 | 1302 | const person2 = makePerson2(); 1303 | console.log(person2.ref().userName); // Jayesh 1304 | } 1305 | // MCQ9(); 1306 | 1307 | // 👉 MCQ-10 1308 | function MCQ10() { 1309 | const user = { 1310 | userName: "Jayesh", 1311 | displayName: function () { 1312 | console.log(this.userName); 1313 | }, 1314 | }; 1315 | 1316 | setTimeout(user.displayName, 1000); 1317 | 1318 | // 👍A) Jayesh 💡B) undefined 1319 | // 💖C) "" 😀D) TypeError 1320 | 1321 | /* 1322 | Answer is B) undefined because setTimeout is using user.displayName as a callback function rather than object method. 1323 | callback function's "this" will refer to the window object and It will console undefined as there is no property such as userName in the window object. 1324 | */ 1325 | 1326 | // 👇 We can get "Jayesh" as an output by wrapping the user.displayName() inside a function :- 1327 | 1328 | setTimeout(function () { 1329 | user.displayName(); // Here, displayName is called by user object ( object method ). Hence, "this" will refer to user object. 1330 | }, 1000); 1331 | } 1332 | // MCQ10(); 1333 | 1334 | // 👉 MCQ-11 1335 | function MCQ11() { 1336 | const series = { name: "JavaScript-with-JC" }; 1337 | 1338 | function getSatus(postNumber) { 1339 | return `${this.name} 🌟 ${postNumber}`; 1340 | } 1341 | 1342 | console.log(getSatus.call(series, 50)); 1343 | console.log(getSatus.bind(series, 50)); 1344 | 1345 | // 👍A) JavaScript-with-JC 🌟 50, undefined 1346 | // 💡B) JavaScript-with-JC 🌟 50, JavaScript-with-JC 🌟 50 1347 | // 💖C) JavaScript-with-JC 🌟 50, [Function: bound getSatus] 1348 | // 😀D) JavaScript-with-JC 🌟 50, TypeError 1349 | 1350 | /* 1351 | Answer is C) JavaScript-with-JC 🌟 50, [Function: bound getSatus] because call, apply and bind methods are used for function borrowing in JavaScript. 1352 | The call method immediately invokes the borrowed function where as bind method does not invoke the borrowed function immediately, bind method returns a copy of borrowed function 1353 | that can be called later on with or without passing new arguments to it. 1354 | */ 1355 | 1356 | // 👇 We can get 'JavaScript-with-JC 🌟 50, JavaScript-with-JC 🌟 50' as an output by calling borrowed function of bind method :- 1357 | 1358 | console.log(getSatus.call(series, 50)); // JavaScript-with-JC 🌟 50 1359 | console.log(getSatus.bind(series, 50)()); // JavaScript-with-JC 🌟 50 1360 | } 1361 | // MCQ11(); 1362 | 1363 | // 👉 MCQ-12 1364 | function MCQ12() { 1365 | var name = "Jayesh"; 1366 | 1367 | function displayName() { 1368 | console.log(this.name); 1369 | } 1370 | 1371 | const person = { 1372 | name: "JC", 1373 | method(fn) { 1374 | fn(); 1375 | }, 1376 | }; 1377 | 1378 | person.method(displayName); 1379 | 1380 | // 👍A) JC 💡B) Jayesh 1381 | // 💖C) undefined 😀D) TypeError 1382 | 1383 | /* 1384 | Answer is B) Jayesh because displayName function is passed to person object method as a callback function. 1385 | "this" keyword in displayName function will refer to window object and window object has a property "name" with value "Jayesh". Hence, It will console Jayesh as an output. 1386 | */ 1387 | 1388 | // 👇 We can get JC as an output by attaching call method with fn() inside person method :- 1389 | 1390 | const person2 = { 1391 | name: "JC", 1392 | method(fn) { 1393 | fn.call(this); // borrowing function and passing "this" of person2 object. 1394 | }, 1395 | }; 1396 | 1397 | person2.method(displayName); // JC 1398 | } 1399 | // MCQ12(); 1400 | 1401 | // 👉 MCQ-13 1402 | function MCQ13() { 1403 | var length = 4; 1404 | 1405 | function callback() { 1406 | console.log(this.length); 1407 | } 1408 | 1409 | const object = { 1410 | length: 5, 1411 | method: function () { 1412 | arguments[0](); 1413 | }, 1414 | }; 1415 | 1416 | object.method(callback, 2, 3); 1417 | 1418 | // 👍A) 2 💡B) 3 1419 | // 💖C) 4 😀D) 5 1420 | 1421 | /* 1422 | Answer is B) 3 because arguments keyword is an array of arguments passed to the function. 1423 | Here while calling object.method(), we are passing three arguments callback fn(), 2 and 3. 1424 | If we try to console arguments it will look like this 👇 1425 | 1426 | Arguments(3) [ƒ, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ] 1427 | 0: ƒ callback() 1428 | 1: 2 1429 | 2: 3 1430 | callee: ƒ () 1431 | length: 3 1432 | Symbol(Symbol.iterator): ƒ values() 1433 | [[Prototype]]: Object 1434 | 1435 | As we can clearly see, arguments is having length property that is equal to number of arguments passed to function. 1436 | So, arguments[0] is nothing but the first argument passed to function that is callback function in this case. 1437 | As we know, Everything in JavaScript is an object ( arguments is also an object which has length property with value 3 ) 1438 | arguments[0]() function's "this" will refer to arguments object. Hence, It will console 3 as an output. 1439 | */ 1440 | } 1441 | // MCQ13(); 1442 | 1443 | // 👉 MCQ-14 1444 | function MCQ14() { 1445 | var name = "Jayesh"; 1446 | 1447 | function displayName() { 1448 | console.log(this.name); 1449 | } 1450 | 1451 | const person = { 1452 | name: "JC", 1453 | method: displayName.bind(this), 1454 | }; 1455 | 1456 | person.method(); 1457 | 1458 | // 👍A) Jayesh 💡B) JC 1459 | // 💖C) undefined 😀D) TypeError 1460 | 1461 | /* 1462 | Answer is A) Jayesh because "this" inside the definition for person object does not refer to person object. 1463 | "this" will refer to the window object here, and binding displayName function with passing window's this 1464 | as a context will return a copy of bound function that is stored in method property of person object. 1465 | So, While calling person.method() will console Jayesh as an output. 1466 | */ 1467 | 1468 | // 👇 We can get JC as an output by wrapping displayName.bind(this) inside a function because "this" inside the normal function of an object refers to the object :- 1469 | 1470 | const person2 = { 1471 | name: "JC", 1472 | method: function () { 1473 | return displayName.bind(this); // Here, "this" refers to the person2 object 1474 | }, 1475 | }; 1476 | 1477 | person2.method()(); // JC 1478 | } 1479 | // MCQ14(); 1480 | 1481 | // 👉 MCQ-15 1482 | function MCQ15() { 1483 | function show() { 1484 | console.log(this.name); 1485 | } 1486 | 1487 | const person1 = { name: "Jc" }; 1488 | const person2 = { name: "Jayesh" }; 1489 | 1490 | show = show.bind(person1).bind(person2); 1491 | show(); 1492 | 1493 | // 👍A) Jayesh 💡B) undefined 1494 | // 💖C) JC 😀D) TypeError 1495 | 1496 | /* 1497 | Answer is C) JC because a function which is bound with bind keyword can not be re-bound with other new context, bind chaining does not exist. 1498 | once the function is bound to a particular object, It will always be bound to that object no matter how many times it's further bounded. 1499 | */ 1500 | } 1501 | // MCQ15(); 1502 | 1503 | // 👉 MCQ-16 1504 | function MCQ16() { 1505 | let person1 = { 1506 | name: { firstName: "Jayesh" }, 1507 | age: 24, 1508 | }; 1509 | let person2 = { ...person1 }; 1510 | 1511 | person2.name.firstName = "Virat"; 1512 | person2.age = 33; 1513 | 1514 | console.log(person1.name.firstName); 1515 | console.log(person1.age); 1516 | 1517 | // 👍A) Jayesh, 33 💡B) Jayesh, 24 1518 | // 💖C) Virat, 33 😀D) Virat, 24 1519 | 1520 | /* 1521 | Answer is D) Virat, 24 because The spread operator makes deep copies of data if the data is not nested. 1522 | When we have nested data in an array or object the spread operator will create a deep copy of the top most data 1523 | and a shallow copy of the nested data. 1524 | person1 and person2 is pointing to different memory address but person1.name and person2.name is pointing to the same memory address 1525 | 1526 | We Can do Deep copy of nested objects by using:- 1527 | 1) const copyObj = JSON.parse(JSON.stringify(originalObj)) 1528 | 2) const copyObj = structuredClone(originalObj); 1529 | */ 1530 | } 1531 | // MCQ16(); 1532 | 1533 | // 👉 MCQ-17 1534 | function MCQ17() { 1535 | for (var i = 0; i < 5; i++) { 1536 | setTimeout( 1537 | (i) => { 1538 | console.log(i); 1539 | }, 1540 | 1000, 1541 | i 1542 | ); 1543 | } 1544 | 1545 | // 👍A) 0 1 2 3 4 💡B) 5 5 5 5 5 1546 | // 💖C) 4 4 4 4 4 😀D) 0 1 2 3 4 5 1547 | 1548 | /* 1549 | Answer is A) 0 1 2 3 4 because as we are passing i ( 0 to 4 ) value as an argument to setTimeout callback function 1550 | therefore this will console different values of i from 0 to 4. 1551 | 1552 | if there was no argument passed to setTimeout callback function then the output would be 5 5 5 5 5 because variables declared 1553 | with var keyword are function-scoped or globally-scoped but not blocked scoped. Inner function i would point to the updated value of i that is 5. 1554 | */ 1555 | } 1556 | // MCQ17(); 1557 | 1558 | // 👉 MCQ-18 1559 | function MCQ18() { 1560 | console.log(1); 1561 | 1562 | async function fetchData() { 1563 | console.log(2); 1564 | let result = await Promise.resolve(3); 1565 | console.log(result); 1566 | } 1567 | 1568 | fetchData(); 1569 | console.log(4); 1570 | 1571 | // 👍A) 1 2 3 4 💡B) 1 4 2 3 1572 | // 💖C) 1 2 4 3 😀D) 1 3 4 2 1573 | 1574 | /* 1575 | Answer is C) 1 2 4 3 beacause promise is used to handle the asynchronous result of an operation and 1576 | callback functions attached to the promises are stored into microtask queue. 1577 | So, first synchronous code will be executed i.e 1,2,4 and once callstack is empty, event loop pushes the microtask queue's task into callstack 1578 | callstack will start executing the task and It will console 3 at last. 1579 | */ 1580 | } 1581 | // MCQ18(); 1582 | 1583 | // 👉 MCQ-19 1584 | function MCQ19() { 1585 | console.log("start"); 1586 | 1587 | const promise = new Promise((resolve) => { 1588 | console.log(1); 1589 | resolve(2); 1590 | console.log(3); 1591 | }); 1592 | 1593 | promise.then((result) => { 1594 | console.log(result); 1595 | }); 1596 | 1597 | console.log("end"); 1598 | 1599 | // 👍A) start end 1 3 2 💡B) start 1 3 end 2 1600 | // 💖C) start end 1 2 3 😀D) start 1 end 2 3 1601 | 1602 | /* 1603 | Answer is B) start 1 3 end 2 beacause The function we pass into the Promise constructor runs synchronously, 1604 | but anything that depends on its resolution ( resolve or reject ) will be called asynchronously. 1605 | Even if the promise resolves immediately, any handlers ( callback attached to promise then and catch ) will execute asynchronously. 1606 | 1607 | const promise = new Promise((resolve) => { 1608 | console.log(1); // runs synchronously 1609 | resolve(2); // called asynchronously by then callback 1610 | console.log(3); // runs synchronously 1611 | }); 1612 | */ 1613 | } 1614 | // MCQ19(); 1615 | 1616 | // 👉 MCQ-20 1617 | function MCQ20() { 1618 | console.log("First"); 1619 | 1620 | const promise = new Promise((resolve) => { 1621 | console.log("Second"); 1622 | }); 1623 | 1624 | promise.then((result) => { 1625 | console.log(result); 1626 | }); 1627 | 1628 | console.log("Third"); 1629 | 1630 | // 👍A) First Second undefined Third 💡B) First Third Second 1631 | // 💖C) First Second Third undefined 😀D) First Second Third 1632 | 1633 | /* 1634 | Answer is D) First Second Third because as there is no resolve in Promise constructor, So it will not go inside of .then block. 1635 | */ 1636 | } 1637 | // MCQ20(); 1638 | 1639 | // 👉 MCQ-21 1640 | function MCQ21() { 1641 | const fetchData = function () { 1642 | return new Promise((resolve, reject) => { 1643 | reject(); 1644 | }); 1645 | }; 1646 | 1647 | fetchData() 1648 | .then(() => { 1649 | console.log("Success 1"); 1650 | }) 1651 | .catch(() => { 1652 | console.log("Error 1"); 1653 | }) 1654 | .then(() => { 1655 | console.log("Success 2"); 1656 | }); 1657 | 1658 | // 👍A) Error 1 TypeError 💡B) Error 1 1659 | // 💖C) Error 1 Success 2 😀D) undefined 1660 | 1661 | /* 1662 | Answer is C) Error 1 Success 2 because in promise chaining .then method below .catch method will be called if in .catch method we are not 1663 | returning rejected promise ( by default implicitly returns a promise that is handled by it's below .then method ) 1664 | */ 1665 | } 1666 | // MCQ21(); 1667 | 1668 | // 👉 MCQ-22 1669 | function MCQ22() { 1670 | function foo() { 1671 | let a = (b = 0); 1672 | a++; 1673 | return a; 1674 | } 1675 | foo(); 1676 | console.log(typeof a); 1677 | console.log(typeof b); 1678 | 1679 | // 👍A) undefined number 💡B) ReferenceError number 1680 | // 💖C) undefined undefined 😀D) number number 1681 | 1682 | /* 1683 | Answer is A) undefined number because variable a is declared with let it is blocked scope and will be "not defined" outside function foo(). 1684 | The typeof operator returns "undefined" even for “undeclared” (or “not defined”) variables. 1685 | Notice that there was no error thrown when we executed typeof a, even though a is an undeclared variable. 1686 | This is a special safety guard in the behavior of typeof. 1687 | and variable b is a just global scope variable hence it will be available outside function foo() also. 1688 | */ 1689 | } 1690 | // MCQ22(); 1691 | 1692 | // 👉 MCQ-23 1693 | function MCQ23() { 1694 | console.log("start"); 1695 | 1696 | setTimeout(() => { 1697 | console.log("first"); 1698 | }, 0); 1699 | 1700 | Promise.resolve("second").then((res) => console.log(res)); 1701 | 1702 | console.log("end"); 1703 | 1704 | // 👍A) start end first second 💡B) start first second end 1705 | // 💖C) start end second first 😀D) start first end second 1706 | 1707 | /* 1708 | Answer is C) start end second first because callback function attached to Promises added into microtask queue 1709 | whereas callback function of setTimeout added into callback ( macroTask ) queue. 1710 | microTask queue has more priority than callback ( macroTask ) queue. 1711 | */ 1712 | } 1713 | // MCQ23(); 1714 | 1715 | // 👉 MCQ-24 1716 | function MCQ24() { 1717 | const person1 = { 1718 | name: "Jayesh", 1719 | age: 24, 1720 | }; 1721 | 1722 | const person2 = person1; 1723 | person2.name = "Virat"; 1724 | 1725 | console.log(person1.name); 1726 | console.log(person2.name); 1727 | 1728 | // 👍A) Jayesh Virat 💡B) Virat Virat 1729 | // 💖C) Virat Jayesh 😀D) Jayesh Jayesh 1730 | 1731 | /* 1732 | Answer is B) Virat Virat because objects are passed as a reference, person1 and person2 will hold the same memory address 1733 | and altering any property of person2 will modify property of person1 as well. 1734 | */ 1735 | } 1736 | // MCQ24(); 1737 | -------------------------------------------------------------------------------- /Akshay Saini Notes/Akshay Saini - Notes- Cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priya42bagde/JavaScriptCodingInterviewQuestions/44926a553dbe7c387e33caf01c8399487ca8c71a/Akshay Saini Notes/Akshay Saini - Notes- Cheatsheet.pdf -------------------------------------------------------------------------------- /Akshay Saini Notes/Akshay Saini - Notes- Handwritten.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priya42bagde/JavaScriptCodingInterviewQuestions/44926a553dbe7c387e33caf01c8399487ca8c71a/Akshay Saini Notes/Akshay Saini - Notes- Handwritten.pdf -------------------------------------------------------------------------------- /Akshay Saini Notes/Akshay Saini - Notes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/priya42bagde/JavaScriptCodingInterviewQuestions/44926a553dbe7c387e33caf01c8399487ca8c71a/Akshay Saini Notes/Akshay Saini - Notes.pdf -------------------------------------------------------------------------------- /Interview-questions-answers: -------------------------------------------------------------------------------- 1 | 1. Question: Write a function that reverses a given string. 2 | function reverseString(str) { 3 | return str.split('').reverse().join(''); 4 | } 5 | console.log(reverseString('Hello')); 6 | // Output: 'olleH' 7 | ----------------------------------------------------------------- 8 | 2.Question: Write a function that finds the longest word in a sentence. 9 | function findLongestWord(sentence) { 10 | const words = sentence.split(' '); 11 | let longestWord = ''; 12 | for (let i = 0; i < words.length; i++) { 13 | if (words[i].length > longestWord.length) { 14 | longestWord = words[i]; 15 | } 16 | } 17 | return longestWord; 18 | } 19 | console.log(findLongestWord('The quick brown fox jumps over the lazy dog')); 20 | // Output: 'quick' 21 | ----------------------------------------------------------------- 22 | 3.Question: Write a function that removes duplicates from an array. 23 | function removeDuplicates(arr) { 24 | return [...new Set(arr)]; 25 | } 26 | console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); 27 | // Output: [1, 2, 3, 4, 5] 28 | ----------------------------------------------------------------- 29 | 4. Question: Given an array containing numbers from 1 to N, with one number missing, find the missing number. 30 | function findMissingNumber(arr) { 31 | const n = arr.length + 1;(added 1 because that number is missing) 32 | const Expectedsum = (n * (n + 1)) / 2; 33 | const ActualarrSum = arr.reduce((acc, curr) => acc + curr, 0); 34 | return Expectedsum - ActualarrSum; 35 | } 36 | console.log(findMissingNumber([1, 2, 3, 5])); 37 | // Output: 4 38 | ----------------------------------------------------------------- 39 | 5. Question: Write a function that checks if a given string is a palindrome. 40 | function isPalindrome(str) { 41 | const reversedStr = str.split('').reverse().join(''); 42 | return str === reversedStr; 43 | } 44 | console.log(isPalindrome('level')); 45 | // Output: true 46 | ----------------------------------------------------------------- 47 | 6. Question: What will be the output of the following code? 48 | for (var i = 1; i <= 5; i++) { 49 | setTimeout(function() { 50 | console.log(i); 51 | }, 1000); 52 | } 53 | Answer: The output will be five instances of the number 6. 54 | ----------------------------------------------------------------- 55 | 7.Question: What will be the output of the following code? 56 | for (var i = 1; i < 5; i++) { 57 | setTimeout(function() { 58 | console.log(i); 59 | }, 1000); 60 | } 61 | Answer: The output will be five instances of the number 5. 62 | ----------------------------------------------------------------- 63 | 8. How to empty an array in javascript? 64 | 1. array=[] 65 | 2. array.length=0 66 | 3. array.splice(0, arr.length) 67 | 4. while(array.length){ 68 | array.pop() 69 | } 70 | ----------------------------------------------------------------- 71 | 9. How would you check if a number is a integer or decimal? 72 | number % 1 === 0 //true 73 | ----------------------------------------------------------------- 74 | 10. Write a "mul"function which will properly when invoked as below syntax. 75 | console.log(mul(2)(3)(4)); // output :: 24 76 | console.log(mul(4)(3)(4))/// output :: 48 77 | function mul(a){ 78 | return function (b){ 79 | return function (c){ 80 | return a*b*c 81 | } 82 | } 83 | } 84 | Here mul function accept the first argument and return anonymous 85 | function which take the second parameter and return anonymous function 86 | which take the third parameter and return multiplication of arguments 87 | which is being passed in successive 88 | ----------------------------------------------------------------- 89 | 11. Class Component in Reactjs: 90 | 1. We can initiatise the state inside a constructor function. 91 | 2. Super() method or function is used to execute the parent class constructor. 92 | 3. The constructor is called during the component creation and before mounting. 93 | 4. The constructor is also used to bind the event handlers. 94 | 5. this.state scope is not in any of the block, it's inside class component. 95 | Link: https://www.youtube.com/watch?v=JiO0dXP3YLA&list=PLsuIm95J7Lco58PVaz6c1ssCwHy8GaxHa&index=3 96 | ----------------------------------------------------------------- 97 | 12. Why is it require to have a callback function at onClick in Reactjs, such as, onClick={()=>this.increment()} 98 | 1. If we call like onClick={this.increment()}, then it will not wait for any user's action like click. As soon as page refresh it also get render.Then it will be a infinite loop. 99 | 2. In lexical scopping we need to use the arrow function(callback function) at OnClick, otherwise it will give an error that setState() is undefined. 100 | 3. There are 2 ways to create a arrow function while onClick. 101 | 3.a onClick={()=> handleClick()} OR 102 | 3.b increment = () => {} 103 | 4. If we don't want to use the callaback(Arrow function then we can use conventional way i.e, with .bind() inside the constructor. 104 | 5. setState is a asyn so immediately not getting a updated value. 105 | 6. second parameneter of the setState contain the updated value, which we can take with arrow function, i.e called a callback function. 106 | ----------------------------------------------------------------- 107 | 13. Functional Component in Reactjs: 108 | 1. In Functional Component, state introduced by Hooks. 109 | 2. Hooks are used to state and the life cycle methods in a functional component. 110 | 3. In functional component, we have multiple states, but in class component we have single state in which the one object contain multiple values. 111 | ----------------------------------------------------------------- 112 | 14. What is state and Props ? 113 | 1. State is an object where you store the property that belongs to the component. 114 | 2. Props are the properties which are passed to the components externally. 115 | 3. "Props" contains all the props value so we can directly destructure at the function firts line like 116 | const MyComponent = ({name, age}) =>{} 117 | or 118 | const MyComponent = (props) =>{ 119 | const {name, age} = props; 120 | } 121 | 4. In class based component, we can access like {this.props.name}. 122 | 5. To access the props in class based component then we need to pass the props at constructor() and super() method. 123 | 6. Stae is inside the component, while props are outside the component. 124 | 7. With Props, we are making the components reusable. 125 | 8. State controls the component internally, while props do externally. 126 | 9. State can be change inside the component, but props can't change/modified at inside the component. 127 | ----------------------------------------------------------------- 128 | 15. What's getSnapshotBeforeUpdate()? 129 | This method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated. 130 | ----------------------------------------------------------------- 131 | 16. Can we use setstate in componentWillUnmount()? 132 | 1. No, because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again. 133 | ----------------------------------------------------------------- 134 | 17. What's Error Boundaries. 135 | 1. If we have an error at one part then it should not break the whole app. 136 | 2. It's a React Component that catches JS errors anywhere in their child component tree, 137 | log those errors and display a fallback UI instead of the component tree that crashed. 138 | 3. It do not catch an error for: 139 | - Event handlers 140 | - Asyn Code(setTimeout) 141 | - SSR 142 | - Error thrown in the error bounary itself(rather than it's children) 143 | 4. Two methods: 144 | - getDerivedStateFromError 145 | - ComponentDidCatch 146 | 5. Will receive exceptions in the development mode only, not an prod. 147 | ---------------------------------------------------------------- 148 | 18. 4 ways of styling: 149 | - Inline styling 150 | - External styling 151 | - Style component 152 | - Module styling- This will help when we have a same class name for more than 2 classes then it will not allow to override the class properties to all the classes. 153 | ---------------------------------------------------------------- 154 | 19. 155 | - Package.json : Its a json file which contains project dependencies means those packages are required, where we are maintaing the versions. This is used by the npm(package manager) and it 156 | will get details of dependencies and its version. 157 | - npm : It manage the packages and its dependencies. These dependencies are storing at node_module folder. 158 | - example==> 159 | "version": "carotsymbo2.1.0" means it will allow to download everything before 3.1.0(major dependencies) 160 | "version": "~2.1.0" means it will allow to download everything before 2.2.0(minor dependencies) 161 | - package.lock.json- actual project deendencies with its version in it. 162 | - index.html- It has the root element of the project. Adiv that render our application. 163 | - index.js- It access the root element and render the whole app. 164 | ---------------------------------------------------------------- 165 | 20. What's createRoot? 166 | - It create a root to Display the React Components inside a browser DOM node. 167 | - ReactDOM: Its a package to manage efficiently html. It provide many methods to manage the DOM. 168 | - Babel: It transpile or compiel the code into js code. 169 | - Module Bundler: We need an application which make the bundle the reactjs code, so that we will get production reay build, code minified, create a hierarchy. Like Webpack or parcel, 170 | - JSX- ease for write a reactjs code 171 | - dependencies vs dev dependencies: Which are require to run an application at runtime vs when it require at Devlopment 172 | - what's bundle.js ?- This whill be production bundle. 173 | - Scripts: Used to run an application 174 | - npx vs npm ?: To execute the process vs to install the dependencies 175 | - "serve" used in development 176 | - react is library, not framewoek why ? 177 | ---------------------------------------------------------------- 178 | 21. What's react-router dom ? 179 | - React is SPA. how ?- We ahve a single page where we are changing the content only. 180 | - React router don is used for the navigation between urls. 181 | - Link vs NavLink 182 | - Nested and Dynamic Route? 183 | ---------------------------------------------------------------- 184 | 22. HOC ? 185 | - Usage: 186 | 1. Code Sharing 187 | 2. State management 188 | 3. Caching or Memoization 189 | 4. Styling 190 | 5. Conditional rendering 191 | - React time example: 192 | 1. React.memo 193 | 2. withRouter 194 | 3. Connect() 195 | - Drawbacks: 196 | 1. Prop Colliasion 197 | - We can fix with Render Props or using Custom Hooks. 198 | 2. We can wrap with muktiple HOC so difficult to debug it 199 | ---------------------------------------------------------------- 200 | 23. Memoisation: 201 | - It means caching. 202 | - using closure, we can implement it. 203 | - React.memo- its a HOC, wrapper component. If we are passing the same props again then it won't calculate it, rerender the previous result. It's used in functional component. 204 | - In class componenet, we have shouldCoponentUpdate() and Pure component for this. 205 | - useMemo- Its hook, it will call inside a componenet and check whether have we calculated/store the value. When it rerender again, with the same arguments are same or not, if same then won't recalculate it. 206 | --------------------------------------------------------------- 207 | 24. useCallback: 208 | - When we have 2 objects/arrays, we are comparing by memory reference, not by the values. 209 | - Don't use useCallback: when we are not passing through the data. 210 | --------------------------------------------------------------- 211 | 25 Interviewer: What're the React 18 new features? https://react.dev/blog/2022/03/29/react-v18#new-suspense-features 212 | 213 | These examples would definitely boost your explanation during interview. : 214 | 215 | 1. Automatic Batching: Automatic batching is like waiting until you have a bunch of tasks to do before doing them all at once, instead of doing each task immediately as it comes up. 216 | Example: 𝑰𝒎𝒂𝒈𝒊𝒏𝒆 𝒚𝒐𝒖'𝒓𝒆 𝒃𝒂𝒌𝒊𝒏𝒈 𝒄𝒐𝒐𝒌𝒊𝒆𝒔 𝒊𝒏 𝒚𝒐𝒖𝒓 𝒌𝒊𝒕𝒄𝒉𝒆𝒏. 𝑰𝒏𝒔𝒕𝒆𝒂𝒅 𝒐𝒇 𝒕𝒖𝒓𝒏𝒊𝒏𝒈 𝒐𝒏 𝒕𝒉𝒆 𝒐𝒗𝒆𝒏 𝒆𝒗𝒆𝒓𝒚 𝒕𝒊𝒎𝒆 𝒚𝒐𝒖 𝒇𝒊𝒏𝒊𝒔𝒉 𝒑𝒓𝒆𝒑𝒂𝒓𝒊𝒏𝒈 𝒐𝒏𝒆 𝒄𝒐𝒐𝒌𝒊𝒆, 𝒚𝒐𝒖 𝒘𝒂𝒊𝒕 𝒖𝒏𝒕𝒊𝒍 𝒚𝒐𝒖'𝒗𝒆 𝒑𝒓𝒆𝒑𝒂𝒓𝒆𝒅 𝒂 𝒘𝒉𝒐𝒍𝒆 𝒃𝒂𝒕𝒄𝒉 𝒐𝒇 𝒄𝒐𝒐𝒌𝒊𝒆 𝒅𝒐𝒖𝒈𝒉. 𝑻𝒉𝒆𝒏, 𝒚𝒐𝒖 𝒕𝒖𝒓𝒏 𝒐𝒏 𝒕𝒉𝒆 𝒐𝒗𝒆𝒏 𝒂𝒏𝒅 𝒃𝒂𝒌𝒆 𝒂𝒍𝒍 𝒕𝒉𝒆 𝒄𝒐𝒐𝒌𝒊𝒆𝒔 𝒂𝒕 𝒐𝒏𝒄𝒆. 217 | 218 | 2. Concurrent rendering: It is like being an efficient cook in your kitchen. When React renders a component tree, it may have multiple tasks to perform, such as updating the UI, handling user interactions, and fetching data from an API. With concurrent rendering, React can work on these tasks concurrently, switching between them as needed to make progress on all fronts. 219 | Example: 𝑰𝒎𝒂𝒈𝒊𝒏𝒆 𝒚𝒐𝒖'𝒓𝒆 𝒄𝒐𝒐𝒌𝒊𝒏𝒈 𝒅𝒊𝒏𝒏𝒆𝒓 𝒊𝒏 𝒚𝒐𝒖𝒓 𝒌𝒊𝒕𝒄𝒉𝒆𝒏. 𝒀𝒐𝒖 𝒉𝒂𝒗𝒆 𝒎𝒖𝒍𝒕𝒊𝒑𝒍𝒆 𝒅𝒊𝒔𝒉𝒆𝒔 𝒕𝒐 𝒑𝒓𝒆𝒑𝒂𝒓𝒆, 𝒃𝒖𝒕 𝒚𝒐𝒖 𝒄𝒂𝒏 𝒐𝒏𝒍𝒚 𝒖𝒔𝒆 𝒐𝒏𝒆 𝒃𝒖𝒓𝒏𝒆𝒓 𝒂𝒕 𝒂 𝒕𝒊𝒎𝒆. 𝑯𝒐𝒘𝒆𝒗𝒆𝒓, 𝒚𝒐𝒖'𝒓𝒆 𝒂𝒏 𝒆𝒇𝒇𝒊𝒄𝒊𝒆𝒏𝒕 𝒄𝒐𝒐𝒌, 𝒔𝒐 𝒚𝒐𝒖 𝒔𝒕𝒂𝒓𝒕 𝒃𝒐𝒊𝒍𝒊𝒏𝒈 𝒘𝒂𝒕𝒆𝒓 𝒇𝒐𝒓 𝒑𝒂𝒔𝒕𝒂 𝒘𝒉𝒊𝒍𝒆 𝒄𝒉𝒐𝒑𝒑𝒊𝒏𝒈 𝒗𝒆𝒈𝒆𝒕𝒂𝒃𝒍𝒆𝒔 𝒇𝒐𝒓 𝒔𝒂𝒍𝒂𝒅. 𝒀𝒐𝒖 𝒔𝒘𝒊𝒕𝒄𝒉 𝒃𝒆𝒕𝒘𝒆𝒆𝒏 𝒕𝒂𝒔𝒌𝒔 𝒂𝒔 𝒏𝒆𝒆𝒅𝒆𝒅, 𝒎𝒂𝒌𝒊𝒏𝒈 𝒑𝒓𝒐𝒈𝒓𝒆𝒔𝒔 𝒐𝒏 𝒎𝒖𝒍𝒕𝒊𝒑𝒍𝒆 𝒅𝒊𝒔𝒉𝒆𝒔 𝒄𝒐𝒏𝒄𝒖𝒓𝒓𝒆𝒏𝒕𝒍𝒚, 𝒆𝒗𝒆𝒏 𝒕𝒉𝒐𝒖𝒈𝒉 𝒚𝒐𝒖'𝒓𝒆 𝒐𝒏𝒍𝒚 𝒂𝒄𝒕𝒊𝒗𝒆𝒍𝒚 𝒘𝒐𝒓𝒌𝒊𝒏𝒈 𝒐𝒏 𝒐𝒏𝒆 𝒕𝒂𝒔𝒌 𝒂𝒕 𝒂 𝒕𝒊𝒎𝒆. 220 | 221 | 3. Transition: The transition feature in React allows you to animate changes in the UI when certain conditions are met, such as when a component mounts or updates. It provides a smooth and visually appealing way to transition between different states of your application. 222 | Example: 𝑰𝒎𝒂𝒈𝒊𝒏𝒆 𝒚𝒐𝒖 𝒉𝒂𝒗𝒆 𝒂 𝒄𝒐𝒎𝒑𝒐𝒏𝒆𝒏𝒕 𝒕𝒉𝒂𝒕 𝒅𝒊𝒔𝒑𝒍𝒂𝒚𝒔 𝒂 𝒎𝒐𝒅𝒂𝒍 𝒅𝒊𝒂𝒍𝒐𝒈. 𝑾𝒉𝒆𝒏 𝒕𝒉𝒆 𝒎𝒐𝒅𝒂𝒍 𝒊𝒔 𝒐𝒑𝒆𝒏𝒆𝒅 𝒐𝒓 𝒄𝒍𝒐𝒔𝒆𝒅, 𝒚𝒐𝒖 𝒘𝒂𝒏𝒕 𝒊𝒕 𝒕𝒐 𝒔𝒎𝒐𝒐𝒕𝒉𝒍𝒚 𝒇𝒂𝒅𝒆 𝒊𝒏 𝒐𝒓 𝒐𝒖𝒕, 𝒓𝒂𝒕𝒉𝒆𝒓 𝒕𝒉𝒂𝒏 𝒂𝒃𝒓𝒖𝒑𝒕𝒍𝒚 𝒂𝒑𝒑𝒆𝒂𝒓𝒊𝒏𝒈 𝒐𝒓 𝒅𝒊𝒔𝒂𝒑𝒑𝒆𝒂𝒓𝒊𝒏𝒈. 223 | 224 | 4. Suspense: Imagine you're building a webpage, and part of it relies on fetching some data from an API before it can be shown to the user. Now, traditionally, in React, handling this kind of asynchronous data loading has been a bit clunky. You might have used loading spinners or conditional rendering to manage the waiting time. But with Suspense, React gives us a more elegant solution. It's like telling React, "Hey, hold up for a sec while I fetch this data." Suspense allows components to suspend rendering while waiting for some asynchronous operation, like data fetching or code splitting, to complete. 225 | Example: Let's say you have a social media feed in your app, and each post includes comments from other users. Instead of waiting for all the comments to load before showing the post, you can use Suspense. This means the post will render right away, and Suspense will take care of loading the comments in the background. 226 | --------------------------------------------------------------- 227 | 26. 𝐈𝐦𝐦𝐮𝐭𝐚𝐛𝐥𝐞 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭: const vs Object.freeze() Explained! 228 | 229 | Here is my answer... 230 | 231 | ☀ const: When declare a variable with const, the variable cannot be reassigned to a new value after its initial assignment. 232 | It applies to bindings(variables). 233 | It create an immutable binding. 234 | It can't assign a new value to the binding. 235 | 236 | Example: 237 | You put a diamond ring in the safe deposit box (the diamond ring represents an object with properties). Even though you can't replace the diamond with another item (because the box is locked with a const key), you can still polish or clean the diamond to improve its appearance (changing the properties of the object). 238 | 239 | ☀ Object.freeze(): Object.freeze() making the object properties immutable. Once an object is frozen using Object.freeze(), you can't add, delete, or modify its properties. 240 | It works on object values. 241 | It create an immutable object. 242 | It can't change its properties. 243 | 244 | Example: 245 | You put a diamond ring in the safe deposit box and lock it with a special lock that prevents any changes. Now, not only can you not replace the diamond or change its appearance, but you also can't add a necklace to the box or take the diamond out to wear it. 246 | ----------------------------------------------------------------- 247 | Can we commit 🏹 .env file at GitHub ? 248 | 249 | The .env files in a React project are environment files that provide a way to store configuration settings and variables that should not be committed to the source code. These files are used to set environment variables for your application at build time. 250 | 251 | The .env file is a file that contains key-value pairs. The key-value pairs defined in the .env file can be accessed in your React application by prefixing the key with REACT_APP_. For example, if you have a variable called API_URL in your .env file, you can access it in your React application as process.env.REACT_APP_API_URL. 252 | 253 | Note: React only exposes variables prefixed with REACT_APP_ to the JavaScript code. This is a security measure to prevent accidentally exposing sensitive information such as API keys. 254 | 255 | Here's an example of what a .env file could look like: 256 | REACT_APP_API_URL=https://api.example.com 257 | REACT_APP_API_KEY=myapikey 258 | In your React component or script, you would access these values like so: 259 | const apiUrl = process.env.REACT_APP_API_URL; 260 | const apiKey = process.env.REACT_APP_API_KEY; 261 | 262 | Remember, the .env file should not be used to store sensitive information like secrets or passwords, as these files are generally included in the version control system and can be accessed by anyone with access to the repository. 263 | -------------------------------------------------------------------------------- /Interview_Preparation: -------------------------------------------------------------------------------- 1 | HTML, CSS, JS, React 2 | 3 | 🔹 1. HTML Structure & Syntax 4 | 1. What is HTML? 5 | A: HTML (HyperText Markup Language) is used for creating structure and content of a web pages and applications like headings, paragraphs, links, images, and more. 6 | 2. What is the purpose of ? 7 | A: The declaration specifies the version of HTML used in a document and helps browsers render the page according to the correct standards. It should be the first element in an HTML file to ensure proper parsing and compatibility. It doesn't have the closing tag. 8 | 3. What’s the difference between block-level and inline elements? 9 | A: Block-Level Elements: 10 | Start on a new line. 11 | Span the full width available. 12 | Can contain other block-level and inline elements. 13 | Example:
,

,

,