Search This Blog

Q66-Q70

Q66. What are high order functions in javascript?


================================================================================
Q66. What are high order functions in javascript?

Answer:
In general functions are called high order functions in javascript because they are very different in multiple ways than functions in object oriented languages like C#
Below are the features of fucntions in javascript

1. Functions are treated as objects in javascript
2. functions can be stored in a variable in javascript. 
3. they can be passed as an arugument to another function
4. We can create a function inside another functions
5. we can return a fucntoin from another function. 
================================================================================


================================================================================



================================================================================



================================================================================



================================================================================

Q61-Q65

Q61. How to stop event bubbling ?
Q62. What is the use of Array.map()?
Q63. How you can join two arrays into third array in JavaScript?
Q64. What is Slice operator on Array? How it is different from Spread operator?
Q65. What 'this' keyword denotes in JavaScript?
---------------------------------------------------------------------------------------------------------------------------
Q61. How to stop event bubbling ?

Answer:
event.stopPropagation()
---------------------------------------------------------------------------------------------------------------------------
Q62. What is the use of Array.map()?

Answer:
The map() method creates a new array with the results of calling a new function or inline logic. 
eg

var numbers = [65, 44, 12, 4];

var newarray1 = numbers.map(doubleFunction)

var newarray2 = numbers.map(x=>x*2)


function doubleFunction(num) {
  return num * 10;
}

---------------------------------------------------------------------------------------------------------------------------
Q63. How you can join two arrays into third array in JavaScript?

Answer:
Two ways by which we can concatinate two arrays in javascript
1. Concat
2. Spread

// 2 Ways to Merge Arrays

const cars = ['🚗', '🚙'];
const trucks = ['🚚', '🚛'];

// Method 1: Concat
const combined1 = [].concat(cars, trucks);

// Method 2: Spread
const combined2 = [...cars, ...trucks];

---------------------------------------------------------------------------------------------------------------------------
Q64. What is Slice operator on Array? How it is different from Spread operator?

Answer:
The slice() method returns the selected elements in an array, as a new array object. We can say Slice operator can be used to create a deep copy. 

array.slice(start, end)

Example:
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(0, 5); //This will copy all elements of fruits array by values (deep copy). By deafult copying of array in javascript is by reference. Now making changes in one array will not effect the other array as they are deep copoied. 


Spread Operator:
Like slice method, spread operator can be used to create a copy but it is shallow copy (it also creates a copy by value on array). 


---------------------------------------------------------------------------------------------------------------------------
Q65. What 'this' keyword denotes in JavaScript?

Answer:
This in case of inside a method refers to the instance of that method
for example:

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};


---------------------------------------------------------------------------------------------------------------------------

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.
------------------------------------------------------------------------------------------------------------------------