Search This Blog

Prototype Example

var car = function (){
  return "this is car";
}

car.prototype.prop1 = "Property 1";
car.prototype.func1 = function(){
  return "this is Function 1";
}

//var honda = new car();
var maruti = Object.create(car.prototype);
maruti.prop2 = "Property 2";

var maruti800 = Object.create(maruti);
//console.log(car());
//console.log(car.prototype);
console.log(maruti.func1());
//console.log(maruti800.func1());
//console.log(maruti800.prop2);


//console.log(maruti);
//console.log(honda.prop1);
//console.log(maruti.prop1);

maruti800.func1 = function(){
  return "this is maruti800 1";
};
console.log(maruti800.func1());

Q56-Q60

Q56. Closures are more related to prototyping or they are completely different concept in JavaScript?
Q57. How to select an element using its CSS class in JavaScript?
Q58. What is V8 engine?
Q59. What is module pattern in Javascript?'
Q60. Difference between Find and Filter in javascript?
-------------------------------------------------------------------------------------------------------------------------
Q56. Closures are more related to prototyping or they are completely different concept in JavaScript?

Answer:

You can achieve almost everything using prototype concept what we can achieve using closures. but Closures are consider to be more modern concept than prototype, Although implementing prototype are consider to be faster than closures.

Example of Prototype --
function Book(title) {
    this.title = title;
}

Book.prototype.getTitle = function () {
    return this.title;
};

var myBook = new Book('War and Peace');
alert(myBook.getTitle())

Example of Closure --
function Book(title) {
    var book = {
        title: title
    };
    book.getTitle = function () {
        return this.title;
    };
    return book;
}

var myBook = Book('War and Peace');

alert(myBook.getTitle())

https://stackoverflow.com/questions/3564238/object-oriented-javascript-with-prototypes-vs-closures
-------------------------------------------------------------------------------------------------------------------------
Q57. How to select an element using its CSS class in JavaScript?

Answer: 

There are two ways. either use queryselector method syntax or use document.getElementsByClassName method.

element = document.querySelector(selectors);
var el = document.querySelector(".myclass");

example
---HTML--
<body>
  <div class='div1'> this is div1 </div>
    <div class='div2'> this is div2 </div>

</body>


--JavaScript--
(function(){
var a = document.querySelector('.div2');
  a.style.backgroundColor = "red";
})();


--JavaScript--
(function(){
var a = document.getElementsByClassName('div2');
  a[0].style.backgroundColor = "red";

})();
-------------------------------------------------------------------------------------------------------------------------
Q58. What is V8 engine?

Answer:

V8 is the name of the JavaScript engine that powers Google Chrome. It's the thing that takes our JavaScript and executes it while browsing with Chrome.

V8 provides the runtime environment in which JavaScript executes. The DOM, and the other Web Platform APIs are provided by the browser.

The cool thing is that the JavaScript engine is independent of the browser in which it's hosted. This key feature enabled the rise of Node.js. V8 was chosen to be the engine that powered Node.js back in 2009, and as the popularity of Node.js exploded, 


https://nodejs.dev/learn/the-v8-javascript-engine

-------------------------------------------------------------------------------------------------------------------------
Q59. What is module pattern in Javascript?

Answer:
It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope.

https://www.youtube.com/watch?v=SKBmJ9P6OAk&ab_channel=AllThingsJavaScript%2CLLC

-------------------------------------------------------------------------------------------------------------------------
Q60. Difference between Find and Filter in javascript?

Answer:
The find() method returns the first value that matches from the collection. Once it matches the value in findings, it will not check the remaining values in the array collection.

The filter() method returns all the matched values in an array from the collection. It will check all values in the collection and return the matched values in an array.

Example below: 

var requests = [{  
    App: 'Apple',  
    Count: 12  
}, {  
    App: 'Amazon',  
    Count: 5  
}, {  
    App: 'Microsoft',  
    Count: 2  
},
  {
    App: 'Apple',  
    Count: 11  
}];  

var obj1 = requests.find(function(item) {  
    return item.App == "Apple" ;
});

var obj2= requests.filter(function(item) {  
    return item.App == "Apple"; 
});

console.log(obj1); // Find will return only 1 element. 
console.log(obj2); // Filter will return both element. 

output of find -->

[object Object] {
 
App: "Apple",
 
Count: 12
}

Output of Filter -->

[[object Object] {
 
App: "Apple",
 
Count: 12
}, [object Object] {
 
App: "Apple",
 
Count: 11
}]

https://www.c-sharpcorner.com/blogs/find-vs-filter-in-javascrtipt
-------------------------------------------------------------------------------------------------------------------------

Q51-Q55

Q51. How JavaScript support asynchronous behavior?
Q52. What is a difference between callbacks and promises in JavaScript?
Q53. how to create a clone of object in JavaScript?
Q54. What are undeclared and undefined variables in JavaScript?
Q55. In how many ways you can clear Arrays in JavaScript?
--------------------------------------------------------------------------------------------------------------------------
Q51. How JavaScript support asynchronous behavior?

Answer: 
It can be done through 
  • Ajax (asynchronous JavaScript and xml) calls, 
  • Callback functions,
  • Javascript ES6 promises and 
  • RXJS observables.
--------------------------------------------------------------------------------------------------------------------------
Q52. What is a difference between callbacks and promises in JavaScript?

Answer : 
  • Promises and callbacks are fundamentally same.
  • Promises are introduced in ES6
  • With promises we have much cleaner code with keyword .then() to handle returning result otherwise callback hell will seen in callback.
  • With promises we have .catch() to catch error in much cleaner way.
Callback hell is an anti pattern  which means callback function inside a callback function. It would tough to maintain and readiliby is also not good with callbacks. 

http://qnimate.com/javascript-promise-vs-callback/
--------------------------------------------------------------------------------------------------------------------------
Q53. how to create a clone of object in JavaScript?

Answer  53: 

Deep copy is also known as Cloning. 
There are two ways to copy objects in JavaScript. Both  ways to make a copy by value of objects as by default objects copy by reference. 
one is to make shallow copy and other is to make a deep copy.

Simple deep copy can be made by way JSON.parse(JSON.stringify(objA)).

--------------------------------------------------------------------------------------------------------------------------
Q54. What are undeclared and undefined variables in JavaScript?

Answer 54:


1) In normal practice we first declare a variable and then define it.
2) var a, is declaring a variable. Here it is declared but undefined.
3) a = 30, giving some value to a variable is defining a variable.

(function(){
 var a; //declared but undefined
  console.log(a); //undefined

  var b;
  b = 10;
  // both declared and defined.

  c=12;
  // both declared and defined but declared globally.
})();

--------------------------------------------------------------------------------------------------------------------------
Q55. In how many ways you can clear Arrays in JavaScript?

Answer 55:
  1. assign array to empty array.
  2. make array.length = 0.
  3. using splice. use array.splice(0, array.length)
  4. pop all elements using for loop.
--------------------------------------------------------------------------------------------------------------------------

Q46-Q50

Q46. How to check whether an object is iterable or not?
Q47. What is Symbol in JavaScript?
Q48. What is use of new loop for..of?
Q49. What are anonymous function in JavaScript?
Q50. What is the type of array in JavaScript?
-------------------------------------------------------------------------------------------------------------------------
Q46. How to check whether an object is iterable or not?

Answer 46:

As per ECMA6 all iterable objects must have a key Symbol.Iterator as part of their prototype.

eg
let myArray = ['2', '4', 45];
console.dir(myArray); // you will find Symbol.Iterator in console as prototpye property.

While for below code you wont find this key.

let myObject = {
key1: 'value1',
key2:'value2',
key3: ['a','b','c'],
key4: function() {return key1.value}
}
https://www.youtube.com/watch?v=ZNrJPzjNt-o
-------------------------------------------------------------------------------------------------------------------------
Q47. What is Symbol in JavaScript?

Answer 47:

Its a new primitive datatype added in ES6. It is use to generate a unique id but we never have access to value of that id.
In example below symbol will give a unique value to user_id making it perfect to act as an id but We will never get what value it get assigned.

let user_id = Symbol();
let user = {};
user[user_id] = 24;
console.log(user[user_id]);
console.log (typeof user_id); // Symbol

** you can not create it with new keyword. ie var user_id1 = new Symbol(); will throw error.
** anything in bracket of symbol is a tag name for that symbol. Symbol still outputs a unique id which value is not accessible to us.

https://www.youtube.com/watch?v=gSKtdtSCYfY
https://www.youtube.com/watch?v=Psdf5Bo1SFM (better)

-------------------------------------------------------------------------------------------------------------------------
Q48. What is use of new loop for..of?

Answer 48:

Its a new loop for  iterative objects like Array, String, TypedArray, Map, Set etc
for..of loops through properties' values of object.


https://www.youtube.com/watch?v=ZNrJPzjNt-o
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
-------------------------------------------------------------------------------------------------------------------------
Q49. What are anonymous function in JavaScript?

Answer 49: 

Defining a function without name is called anonymous function. 
eg 

var func1 = function () { 
//code
 }
-------------------------------------------------------------------------------------------------------------------------
Q50. What is the type of array in JavaScript?

Answer 50: 

In JavaScript arrays are of type object.
-------------------------------------------------------------------------------------------------------------------------

Q41-Q45

Q41. What are Maps and Weak Maps in JavaScript?
Q42. What are the differences between objects and maps?
Q43. Can we iterate maps with for...of loop?
Q44. What are the primitives data types in JavaScript?
Q45. Can we execute anonymous function multiple times in JavaScript?
------------------------------------------------------------------------------------------------------------------------
Q41. What are Maps and Weak Maps in JavaScript?

Answer 41:

The Map object holds key-value pairs. Any value (both objects and primitive values) may be used as either a key or a value.

like map, weakmap also holds key value pairs but Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key).

var myMap = new Map();

  var keyString = 'a string',
    keyObj = {},
    keyFunc = function() {};

// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, 'value associated with keyObj');
myMap.set(keyFunc, 'value associated with keyFunc');

  // getting the values
myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
------------------------------------------------------------------------------------------------------------------------
Q42. What are the differences between objects and maps?

Answer 42:

Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key

>> The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
>> You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
>> A Map may perform better in scenarios involving frequent addition and removal of key pairs.
>> A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
------------------------------------------------------------------------------------------------------------------------
Q43. Can we iterate maps with for...of loop?

Answer 43:

Yes

var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
------------------------------------------------------------------------------------------------------------------------
Q44. What are the primitives data types in JavaScript?

Answer 44:

String, Symbol, Null, Boolean, undefined, Number.
Remember is by SSN-BUN
------------------------------------------------------------------------------------------------------------------------
Q45. Can we execute anonymous function multiple times in JavaScript

Answer 45:

yes. As many times you want.
------------------------------------------------------------------------------------------------------------------------


Q36-Q40

Q36. What is TypedArray in JavaScript?
Q37. What is eval() in JavaScript?
Q38. What is yield* in JavaScript?
Q39. What new method for..in is different from for..of?
Q40. What are Sets and Weak Sets in JavaScript?
--------------------------------------------------------------------------------------------------------------------------
Q36. What is TypedArray in JavaScript?

Answer 36:

JavaScript typed arrays are array-like objects and provide a mechanism for accessing raw binary data. As you may already know, Array objects grow and shrink dynamically and can have any JavaScript value. Raw data could be like audio, video, web sockets etc.

However, typed arrays are not to be confused with normal arrays, as calling Array.isArray() on a typed array returns false
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
------------------------------------------------------------------------------------------------------------------------
Q37. What is eval() in JavaScript?

Answer 37:

The eval() function evaluates JavaScript code represented as a string.

var x = 2, y = 4;
console.log(eval('x + y'));  // Direct call, uses local scope, result is 6
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
----------------------------------------------------------------------------------------------------------------------
Q38. What is yield* in JavaScript?

Answer 38:

The yield* expression is used to delegate to another generator or iterable object.

(function(){
  console.clear();
  function* f1(){
   yield "f1";
  }

  function* f2(){
    yield* f1();
  }
  const iterator = f2();
  console.log(iterator.next());
  console.log(iterator.next());

})();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*
------------------------------------------------------------------------------------------------------------------
Q39. What new method for..in is different from for..of?

Answer 39:
  • for..of is a new loop in JavaScript.
  • for..in loops through properties name of object.while for..of loops through properties values of object.

(function(){
  console.clear();
let fruits = ['apple','banana','carrot'];

//for-in loops through properties name of objects.
  for (let a in fruits)
    {
      console.log(fruits[a]);
    }

//for..of loops through properties values of object.
  for (let b of fruits)
    {
      console.log(b);
    }
})();

o/p
"apple"
"banana"
"carrot"
"apple"
"banana"
"carrot".
-----------------------------------------------------------------------------------------------------------------------
Q40. What are Sets and Weak Sets in JavaScript?

Answer 40:
  • The Set object lets you store unique values of any type, whether primitive values or object references.
  • In contrast to Sets, WeakSets are collections of objects only and not of arbitrary values of any type. 
  • The WeakSet is weak: References to objects in the collection are held weakly. If there is no other reference to an object stored in the WeakSet, they can be garbage collected. That also means that there is no list of current objects stored in the collection. WeakSets are not enumerable.


const set1 = new Set();
set1.add(1);
set1.add('string data');
let obj = {f:'Him', l:'Goel'};
set1.add(obj);
console.log(set1.has(1));
// expected output: true
console.log(set1.has('string data'));
// expected output: true
console.log(set1.has(obj1));
// expected output: true

Q31-Q35

Q31. What are the two property of yield in JavaScript? How we migrate to next value
Q32. How to traverse elements on HTML using JavaScript? or How to traverse DOM elements using javascript?
Q33. What are local variables and global variables in JavaScript?
Q34. What are generators in JavaScript?
Q35. What is yield in JavaScript?
---------------------------------------------------------------------------------------------------------------------
Q31. What are the two property of yield in JavaScript? How we migrate to next value

Answer 31:

"done" and "value" are the two properties present in yield. 
Initially "done" remain false till iterator object reaches the end of object using .next() where "done" become true and "value" become "undefined".

with the help of .next() we migrate to next value.
---------------------------------------------------------------------------------------------------------------------
Q32. How to traverse elements on HTML using JavaScript? or How to traverse DOM elements using javascript?

Answer 32:

There are multiple ways we can traverse DOM elements using javascript  eg. document.querySelector is the most common way. 

You can traverse in three directions:
  1. Downwards
  2. Sideways
  3. Upwards
https://zellwk.com/blog/dom-traversals/
---------------------------------------------------------------------------------------------------------------------
Q33. What are local variables and global variables in JavaScript?

Answer 33:
JavaScript has three scopes – global, functional and block scope. Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code. Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions
---------------------------------------------------------------------------------------------------------------------
Q34. What are generators in JavaScript?

Answer 34:

With ES6 generators, we have a different kind of function, which may be paused in the middle, one or many times, and resumed later, allowing other code to run during these paused periods.

you use the new yield keyword to pause the function from inside itself. Nothing can pause a generator from the outside; it pauses itself when it comes across a yield.

However, once a generator has yield-paused itself, it cannot resume on its own. An external control must be used to restart the generator. 

Even more importantly, this stopping and starting is not just a control on the execution of the generator function, but it also enables 2-way message passing into and out of the generator, as it progresses. With normal functions, you get parameters at the beginning and a return value at the end. With generator functions, you send messages out with each yield, and you send messages back in with each restart.

Syntax:
function *foo() { // ..}

The way we control generator functions from the outside is to construct and interact with a generator iterator. We use is using the 'next' keyword


Good learning in below url after the heading "Generator Iterator"

https://davidwalsh.name/es6-generators
----------------------------------------------------------------------------------------------------------------------
Q35. What is yield in JavaScript?

Answer 35:

It can be thought of as a generator-based version of the return keyword. The yield keyword actually returns an IteratorResult object with two properties, value and done. The value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed.

(function(){
  console.clear();
  function* foo(index){
    while(index <2){
      yield index++;
    }
  }
  const iterator = foo(0);
  console.log(iterator.next());
  console.log(iterator.next());
  console.log(iterator.next());

})();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

Unanswered

Q6. what will be the output of

Answer:
(function(){
  for (var i = 0; i < 5; i ++)
    {
      setTimeout(function(){
      console.log('Timer-' + i);
      },1000);
      console.log(i);
    }
})();

Answer:
0
1
2
3
4
"Timer-5"
"Timer-5"
"Timer-5"
"Timer-5"
"Timer-5"

Q. Difference between spread operator and REST operatgor in javascript



1. What is the difference between == and === in javaScript?
2. What is the output of 
 let a = 1 + '1'; // 11
= 1 + '1' + 1; // 111
= 1 + true + '1'; //21

3. out put of 
var a;
var a; // no Error
 let a;
let a; // Error: Duplicate declaration of a

------------------------
Q. why we need callback ?
Q. How to use next symbol with iterator in JavaScript?

Q33. What are Iterators and Generators in JavaScript?

Answer:
An object is an iterator when it knows how to access items from a collection one at a time, while keeping track of its current position within that sequence.
A GeneratorFunction is a special type of function that works as a factory for iterators. A function becomes a GeneratorFunction if it uses the function* syntax.
Some built-in types, such as Array or Map, have a default iteration behavior, while other types (such as Object) do not. In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a Symbol.iterator key



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

What is *
----------------------------
Q 4) What is Polymorphism in JavaScript? (m = moved)

Answer: We can see polymorphism in JavaScript when we try to create a new object say objnew from exiting object say objold using Object.Create and then creating your objnew's function with same name as of objold's function. it would be like overriding the previous object function definition.
-------------------------------------------------------
68. Few new improvement of ECMA6?

Answer: Introduction of new keywords LET and CONST.
Keywords like CLASS, Constructor, Extend etc
Concept of this keyword
2. What is Iterators in JavaScript?
3. What is function* in JavaScript?

----------------JavaScript---------------------
q. What are Generators in JavaScript
3. Write a closure with example on paper.
4. output of console.log(null===undefined)? and why?
10) What are primitive data types in java script?

What about apply and call functions in java script?
 What about event propagation in java script?
 What about promises and callback in java script?
Q) why it is consider to be good practise to put your code in side closure wrapping or self executing method
eg
(function(){
...code here
})();

<----->
output of
var a = 12;
var b = a;
b = 20;
console.log(a);

what is difference between DOM elements and HTML elements.
javascript default inheritance type
by default javascript passes data  by value or by reference
difference between abstraction and encapsulation in javascript
can we change prototpye of parent using child object
98. What is difference between Callbacks, Ajax calls, Promises, observables?
7. What is forin and forat in  javascript?

5. output of console.log(a);

6. function () {
    var a = 2;
    console.log(a);
    function 2 () {
    let a = 3;
    console.log(a);
    }
    console.log(a);
    }
    Q41. Explain how for..each loop works in JavaScript and how it is different from for..in and for..of?
    Q. Whats the difference between iterators and iterables?

Q. loops in JavaScript
for loop
for..each
for..in
for..of


Q26-Q30

Q26: What is the difference between block scope and function scope in javscript?
Q27. What are prototypes in java script?
Q28. What is prototype chaining in java script.
Q29. What is prototype Inheritance in Javascript? 
Q30. What make generators different from normal function in javascript?
--------------------------------------------------------------------------------------------------------------------------
Q26: What is the difference between block scope and function scope in javscript?

Answer 26:

In actual there are three types of scopes in javascript- Global, functional, block scope. 

var in javascript can be reassigned and updated. var variables are ‘function scope.’ It means they are only available inside the function they’re created in, or if not created inside a function, they are ‘globally scoped.’ If var is defined inside a function and I subsequently try to call it outside the function, it won’t work.

function setWidth(){
    var width = 100;
    console.log(width);
}
width;
// Returns:

Uncaught ReferenceError: width is not defined


>> Let and Const keywords has scope of block instead of functions. A block is a set of opening and closing brackets.  so for below exmple

var age = 100;
  if (age > 12){
    let dogYears = age * 7;
    console.log(`You are ${dogYears} dog years old!`);

  }

if we try to get value of dogYears outside the block i.e curly braces, it will give not defined error. 


https://medium.com/@josephcardillo/the-difference-between-function-and-block-scope-in-javascript-4296b2322abe
--------------------------------------------------------------------------------------------------------------------------
Q27. What are prototypes in java script?

Answer 27.

1) All JavaScript objects inherit their properties and methods from their prototype. 
2) Objects created using an object.create literal, or with new Object(), inherit from a prototype called Object.prototype.
3) In JavaScript, all objects have a hidden [[Prototype]] property that’s either another object or null.
4) The object referenced by [[Prototype]] is called a “prototype”.
https://www.w3schools.com/js/js_object_prototypes.asp
--------------------------------------------------------------------------------------------------------------------------
Q28. What is prototype chaining in java script.

Answer 28:

<<Need Better Answer>>
Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain.  This provides a very powerful although potentially dangerous mechanism to override or extend object behavior

If you try to look up a key on an object and it is not found, JavaScript will look for it in the prototype. It will follow the "prototype chain" until it sees a null value. In that case, it returns undefined.
http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

--------------------------------------------------------------------------------------------------------------------------
Q29. What is prototype Inheritance in Javascript? 

Answer 29:

<<Yet to answer>>
--------------------------------------------------------------------------------------------------------------------------
Q30. What make generators different from normal function in javascript?

Answer 30:

Generators are introduced in ES6.

1) Generators functions can be stop and restarted as many times you choose. unlike normal functions
2) Generators allows two way passing of message as it progress. While in normal functions you pass parameters in the beginning and expect out at the end. With Generators functions, you send messages out with each yield and you send message back with each restart.


Q21-Q25

Q21. What is LET keyword in JavaScript?
Q22. What are closures in JavaScript?
Q23. What is variable Hoisting in JavaScript?
Q24. What is event propagation in JavaScript?
Q25. Is JavaScript single threaded or multi threaded?
------------------------------------------------------------------------------------------------------------------------
Q21. What is LET keyword in JavaScript?

Answer:

LET allows you to declare variables that are limited in scope to the block.it is a block scope variable. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. ie Var keyword is functional scope in general but if var keyword is not defined inside a function it has global scope. 

--- Problem with VAR--
(function(){
  console.clear();
var x = 1;
if (true) {
  var x = 2;
  console.log(x); //output 2
}
console.log(x); //output 2
})();

-- Use of LET keyword --
(function(){
  console.clear();
let x = 1;
if (true) {
  let x = 2;
  console.log(x); //output 2
}
console.log(x); //output 1
})();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
------------------------------------------------------------------------------------------------------------------------
Q22. What are closures(not callback) in JavaScript?

Answer: 

A closure is an inner function that has access to the outer (enclosing) function's variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function's variables, and it has access to the global variables.

Although function can access variable from outside in concept of closure function still individuality of every call is maintained
eg.

function makeCounter() {
  let count = 0;
  return function() {
    return count++;
  };
}

let counter1 = makeCounter();
let counter2 = makeCounter();

alert( counter1() ); // 0
alert( counter1() ); // 1

alert( counter2() ); // 0 (independent)


https://javascript.info/closure
http://javascriptissexy.com/understand-javascript-closures-with-ease/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
------------------------------------------------------------------------------------------------------------------------
Q23. What is variable Hoisting in JavaScript?

Answer: 

Hoisting is JavaScript's default behavior of moving declarations to the top. In JavaScript, a variable can be declared after it has been used. 
Its important to note JavaScript only hoists declarations, not initialization.
 means if you can give some value to variable x first and write var x below it - No Error

But if you write alert (x + 5); and below it you write var x = 2; this wont work and will give you error.

Similarly below will not work
console.log(name); // Uncaught ReferenceError: name is not defined
let name = "Andrew";
because the name value is giving in next line not before Console.log(name);

👀 Let, Const can also be hoisted but their hosted is specific to block as they are block scope variables. 


So now as of ES6 Hoisting has both functional and block scope. 

------------------------------------------------------------------------------------------------------------------------
Q24. What is event propagation in JavaScript?

 Answer:

When ever we have parent child dom elements structure and some event occurred at some level then both event bubbling or event capturing concept happen. Event bubbling is default behavior of modern browsers. 

Combination of both event bubbling  and event capturing is known as event propagation.
------------------------------------------------------------------------------------------------------------------------
Q25. Is JavaScript single threaded or multi threaded?

Answer: 

JavaScript is single threaded and synchronous by default

Q16-Q20

Q16. What is MAPS in javascript?
Q17. How MAPS are different from any javascript object?
Q18. What are SETS in Javascript?
Q19. How is map.set is different from set in javascript?
Q20. What is spread operator in javascript?
--------------------------------------------------------------------------------------------------------------------------
Q16. What is MAPS in javascript?

Answer 16:

Map is a collection of elements where each element is stored as a Key, value pair.  Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key,value pair in the same order as inserted.

A Map object can iterate its elements in insertion order - a for..of loop will return an array of [key, value] for each iteration.

var map1 = new Map([["one",1],["two",2],["three",3]]);

console.log(map1);

https://www.geeksforgeeks.org/map-in-javascript/ 
--------------------------------------------------------------------------------------------------------------------------
Q17. How MAPS are different from any javascript object?

Answer 17:

Map is a data structure which helps in storing the data in the form of pairs. The pair consists of a unique key and a value mapped to the key. It helps prevent duplicity.

Object follows the same concept as that of map i.e. using key-value pair for storing data. But there are slight differences which makes map a better performer in certain situations.

Few basic differences are as follows:
  1. In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!)
  2. In the Map, the original order of elements is preserved. This is not true in case of objects.
  3. The Map is an instance of an object but the vice-versa is not true.
--------------------------------------------------------------------------------------------------------------------------
Q18. What are SETS in Javascript?

Answer 18:

Sets are a new object type included in ES6 that allow the creation of collections of unique values. The values in a set can be either simple primitives, such as strings and integers or more complex object types like object literals or arrays. 
  • Think of sets as an array with no repeated elements.
There are many instances where we have an array containing many elements that we want to convert to a unique array. While it can be done by brute force on the array, checking elements, using loops, distinct callback method, etc., the best method is using  set().


let arrayOne=['1','2','1','2']
console.log(arrayOne)
// ['1','2','1','2']
let setOne= new Set(arrayOne) 
for(elem of setOne){
  console.log(elem)
}
//'1'
//'2'
// Another way of doing
let setTwo= [...new Set(arrayOne)]
console.log(setTwo)
// ["1" ,"2"]



--------------------------------------------------------------------------------------------------------------------------
Q19. How is map.set is different from set in javascript?

Answer 19:

Map.Set is way we can add elements in map type collection. Where as SET is a collection in itself different from MAP. 
--------------------------------------------------------------------------------------------------------------------------
Q20. What is spread operator in javascript?

Answer 20:
1. Spread operator can be used to create shallow copies. 
2. spread operator spread array into individual elements.

👀 [Quick Recap: By default primitive data types are copied by value while objects and arrays(they are objects in javascript) are copied by reference. Shallow copy and Deep copy are techniques to copy the objects and array by value.  Shallow copy copies the top elements by value while nested elements by reference. ]

--create shallow copy --
int arr[] = [1,2,3];
int arr2[] = [...arr]; //shallow copy
int arr3[] = arr[]; // this will create a reference copy means if any chagnes are made in arr3, they will reflect in arr1 as well. 

----Spread elements ----
(function(){
  'use strict';
  function sumAll (a, b, c){
    console.log(a + b + c);
  }

  let arrAll = [2,3,4];
  sumAll(...arrAll); // spread all elements 

})();