70 JavaScript Interview Questions
Tags: javascript, webdev, career, tutorial
Published: 2020-01-03 03:26:57

##Hi Guys Good Day and a Happy New Year :fireworks::fireworks::fireworks:!

This is a long one, so bear with me for a second or an hour. In every answer for every question there's an arrow up __&uarr;__ link that lets you go back to the List of Questions so that you don't waste time scrolling up and down. 

###The Questions 
* [1. What's the difference between <code>undefined</code> and <code>null</code>?](#1-whats-the-difference-between-undefined-and-null)
* [2. What does the && operator do?](#2-what-does-the-ampamp-operator-do)
* [3. What does the || operator do?](#3-what-does-the-operator-do)
* [4. Is using the + or unary plus operator the fastest way in converting a string to a number?](#4-is-using-the-or-unary-plus-operator-the-fastest-way-in-converting-a-string-to-a-number)
* [5. What is the DOM?](#5-what-is-the-dom)
* [6. What is Event Propagation?](#6-what-is-event-propagation)
* [7. What's Event Bubbling?](#7-whats-event-bubbling)
* [8. What's Event Capturing?](#8-whats-event-capturing)
* [9. What's the difference between <code>event.preventDefault()</code> and <code>event.stopPropagation()</code> methods?](#9-whats-the-difference-between-eventpreventdefault-and-eventstoppropagation-methods)
* [10. How to know if the <code>event.preventDefault()</code> method was used in an element?](#10-how-to-know-if-the-eventpreventdefault-method-was-used-in-an-element)
* [11. Why does this code obj.someprop.x throw an error?](#11-why-does-this-code-objsomepropx-throw-an-error)
* [12. What is `event.target` ?](#12-what-is-eventtarget-
)
* [13. What is `event.currentTarget`?](#13-what-is-eventcurrenttarget)
* [14. What's the difference between <code>==</code> and <code>===</code>?](#14-whats-the-difference-between-and-)
* [15. Why does it return false when comparing two similar objects in JavaScript?](#15-why-does-it-return-false-when-comparing-two-similar-objects-in-javascript)
* [16. What does the <code>!!</code> operator do?](#16-what-does-the-operator-do)
* [17. How to evaluate multiple expressions in one line?](#17-how-to-evaluate-multiple-expressions-in-one-line)
* [18. What is Hoisting?](#18-what-is-hoisting)
* [19. What is Scope?](#19-what-is-scope)
* [20. What are Closures?](#20-what-are-closures)
* [21. What are the falsy values in JavaScript?](#21-what-are-the-falsy-values-in-javascript)
* [22. How to check if a value is falsy?](#22-how-to-check-if-a-value-is-falsy)
* [23. What does <code>"use strict"</code> do?](#23-what-does-use-strict-do)
* [24. What's the value of <code>this</code> in JavaScript?](#24-whats-the-value-of-this-in-javascript)
* [25. What is the <code>prototype</code> of an object?](#25-what-is-the-prototype-of-an-object)
* [26. What is an IIFE, what is the use of it?](#26-what-is-an-iife-what-is-the-use-of-it
)
* [27. What is the use <code>Function.prototype.apply</code> method?](#27-what-is-the-use-functionprototypeapply-method)
* [28. What is the use <code>Function.prototype.call</code> method?](#28-what-is-the-use-functionprototypecall-method)
* [29. What's the difference between <code>Function.prototype.apply</code> and <code>Function.prototype.call</code>?](#29-whats-the-difference-between-functionprototypeapply-and-functionprototypecall)
* [30. What is the usage of <code>Function.prototype.bind</code>?](#30-what-is-the-usage-of-functionprototypebind)
* [31. What is Functional Programming and what are the features of JavaScript that makes it a candidate as a functional language?](#31-what-is-functional-programming-and-what-are-the-features-of-javascript-that-makes-it-a-candidate-as-a-functional-language
)
* [32. What are Higher Order Functions?](#32-what-are-higher-order-functions)
* [33. Why are functions called First-class Objects?](#33-why-are-functions-called-firstclass-objects)
* [34. Implement the <code>Array.prototype.map</code> method by hand.](#34-implement-the-arrayprototypemap-method-by-hand
)
* [35. Implement the <code>Array.prototype.filter</code> method by hand.](#35-implement-the-arrayprototypefilter-method-by-hand)
* [36. Implement the <code>Array.prototype.reduce</code> method by hand.](#36-implement-the-arrayprototypereduce-method-by-hand)
* [37. What is the <code>arguments </code> object?](#37-what-is-the-arguments-object)
* [38. How to create an object without a __prototype__?](#38-how-to-create-an-object-without-a-prototype)
* [39. Why does <code>b</code> in this code become a global variable when you call this function?](#39-why-does-b-in-this-code-become-a-global-variable-when-you-call-this-function)
* [40. What is __ECMAScript__?](#40-what-is-ecmascript)
* [41. What are the new features in __ES6__ or __ECMAScript 2015__?](#41-what-are-the-new-features-in-es6-or-ecmascript-2015)
* [42. What's the difference between <code>var</code>, <code>let</code> and <code>const</code> keywords?](#42-whats-the-difference-between-var-let-and-const-keywords)
* [43. What are __Arrow functions__?](#43-what-are-arrow-functions)
* [44. What are __Classes__?](#44-what-are-classes)
* [45. What are __Template Literals__?](#45-what-are-template-literals)
* [46. What is __Object Destructuring__?](#46-what-is-object-destructuring)
* [47. What are <code>ES6 Modules</code>?](#47-what-are-es6-modules)
* [48. What is the <code>Set</code> object and how does it work?](#48-what-is-the-set-object-and-how-does-it-work)
* [49. What is a Callback function?](#49-what-is-a-callback-function)
* [50. What are __Promises__?](#50-what-are-promises)
* [51. What is _async/await_ and How does it work?](#51-what-is-asyncawait-and-how-does-it-work)
* [52. What's the difference between __Spread operator__ and __Rest operator__?](#52-whats-the-difference-between-spread-operator-and-rest-operator)
* [53. What are __Default Parameters__?](#53-what-are-default-parameters)
* [54. What are __Wrapper Objects__?](#54-what-are-wrapper-objects)
* [55. What is the difference between __Implicit__ and __Explicit__ Coercion?](#55-what-is-the-difference-between-implicit-and-explicit-coercion)
* [56. What is <code>NaN</code>? and How to check if a value is <code>NaN</code>?](#56-what-is-nan-and-how-to-check-if-a-value-is-nan)
* [57. How to check if a value is an __Array__?](#57-how-to-check-if-a-value-is-an-array)
* [58. How to check if a number is even without using the <code>%</code> or modulo operator?](#58-how-to-check-if-a-number-is-even-without-using-the-or-modulo-operator)
* [59. How to check if a certain property exists in an object?](#59-how-to-check-if-a-certain-property-exists-in-an-object)
* [60. What is __AJAX__?](#60-what-is-ajax)
* [61. What are the ways of making objects in JavaScript?](#61-what-are-the-ways-of-making-objects-in-javascript)
* [62. What's the difference between <code>Object.seal</code> and <code>Object.freeze</code> methods?](#62-whats-the-difference-between-objectseal-and-objectfreeze-methods)
* [63. What's the difference between the <code>in</code> operator and the <code>hasOwnProperty</code>  method in objects?](#63-whats-the-difference-between-the-in-operator-and-the-hasownproperty-method-in-objects)
* [64. What are the ways to deal with __Asynchronous Code__ in JavasScript?](#64-what-are-the-ways-to-deal-with-asynchronous-code-in-javasscript)
* [65. What's the difference between a __function expression__ and __function declaration__?](#65-whats-the-difference-between-a-function-expression-and-function-declaration)
* [66. How many ways can a function be _invoked_?](
#66-how-many-ways-can-a-function-be-invoked)
* [67. What is _memoization_ and what's the use it?](#67-what-is-memoization-and-whats-the-use-it)
* [68. Implement a memoization helper function.](#68-implement-a-memoization-helper-function)
* [69. Why does <code>typeof null</code> return <code>object</code>? How to check if a value is <code>null</code>?](#69-why-does-typeof-null-return-object-how-to-check-if-a-value-is-null)
* [70. What does the <code>new</code> keyword do?](#70-what-does-the-new-keyword-do)



###1. What's the difference between <code>undefined</code> and <code>null</code>?. 
[&uarr;](#the-questions "Back To Questions") Before understanding the differences between <code>undefined</code> and <code>null</code> we must understand the similarities between them.

* They belong to __JavaScript's__ 7 primitive types.
```js
 let primitiveTypes = ['string','number','null','undefined','boolean','symbol', 'bigint'];
```


* They are __falsy__ values. Values that evaluated to false when converting it to boolean using <code>Boolean(value)</code> or <code>!!value</code>.
```js
   console.log(!!null); //logs false
   console.log(!!undefined); //logs false

   console.log(Boolean(null)); //logs false
   console.log(Boolean(undefined)); //logs false
```


Ok, let's talk about the differences.

* <code>undefined</code> is the default value of a variable that has not been assigned a specific value. Or a function that has no __explicit__ return value ex. <code>console.log(1)</code>. Or a property that does not exist in an object. The JavaScript engine does this for us the __assigning__ of <code>undefined</code> value.

```js
  let _thisIsUndefined;
  const doNothing = () => {};
  const someObj = {
    a : "ay",
    b : "bee",
    c : "si"
  };

  console.log(_thisIsUndefined); //logs undefined
  console.log(doNothing()); //logs undefined
  console.log(someObj["d"]); //logs undefined
```

* <code>null</code> is __"a value that represents no value"__. <code>null</code> is value that has been __explicitly__ defined to a variable. In this example we get a value of <code>null</code> when the <code>fs.readFile</code> method does not throw an error.
```js
  fs.readFile('path/to/file', (e,data) => {
     console.log(e); //it logs null when no error occurred
     if(e){
       console.log(e);
     }
     console.log(data);
   });
```

When comparing <code>null</code> and <code>undefined</code> we get <code>true</code> when using <code>==</code> and <code>false</code> when using <code>===</code>. You can read the reason [here](#14-whats-the-difference-between-and-).
```js
   console.log(null == undefined); // logs true
   console.log(null === undefined); // logs false
```

###2. What does the <code>&&</code> operator do?

[&uarr;](#the-questions "Back To Questions") The <code>&&</code> or __Logical AND__ operator finds the first _falsy_ expression in its operands and returns it and if it does not find any _falsy_ expression it returns the last expression. It employs short-circuiting to prevent unnecessary work. I've used this in the <code>catch</code> block when closing database connection in one of my projects.

```js
   console.log(false && 1 && []); //logs false
   console.log(" " && true && 5); //logs 5
```

Using __if__ statements.
```js
  const router: Router = Router();

  router.get('/endpoint', (req: Request, res: Response) => {
     let conMobile: PoolConnection;
     try {
        //do some db operations
     } catch (e) {
     if (conMobile) {
      conMobile.release();
     }
  }
});
```
Using __&&__ operator.
```js
const router: Router = Router();

router.get('/endpoint', (req: Request, res: Response) => {
  let conMobile: PoolConnection;
  try {
     //do some db operations
  } catch (e) {
    conMobile && conMobile.release()
  }
});
```
###3. What does the <code>||</code> operator do?

[&uarr;](#the-questions "Back To Questions") The <code>||</code> or __Logical OR__ operator finds the first _truthy_ expression in its operands and returns it. This too employs short-circuiting to prevent unnecessary work. It was used before to initialize default parameter values IN functions before __ES6 Default function parameters__ was supported.


```js
console.log(null || 1 || undefined); //logs 1

function logName(name) {
  var n = name || "Mark";
  console.log(n);
}

logName(); //logs "Mark"
```

###4. Is using the __+__ or unary plus operator the fastest way in converting a string to a number?

[&uarr;](#the-questions "Back To Questions") According to [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) the <code>+</code> is the fastest way of converting a string to a number because it does not perform any operations on the value if it is already a number.


###5. What is the __DOM__?

[&uarr;](#the-questions "Back To Questions") __DOM__ stands for __Document Object Model__ is an interface (__API__) for HTML and XML documents. When the browser first reads (_parses_) our HTML document it creates a big object, a really big object based on the HTML document this is the __DOM__. It is a tree-like structure that is modeled from the HTML document. The __DOM__ is used for interacting and modifying the __DOM structure__ or specific Elements or Nodes.

Imagine if we have an HTML structure like this.
```html
<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document Object Model</title>
</head>

<body>
   <div>
      <p>
         <span></span>
      </p>
      <label></label>
      <input>
   </div>
</body>

</html>

```
The __DOM__ equivalent would be like this.
![DOM equivalent](https://thepracticaldev.s3.amazonaws.com/i/mbqphfbjfie45ynj0teo.png)

The <code>document</code> object in __JavaScript__ represents the __DOM__. It provides us many methods that we can use to selecting elements to update element contents and many more.

###6. What is __Event Propagation__?
[&uarr;](#the-questions "Back To Questions") When an __event__ occurs on a __DOM__ element, that __event__ does not entirely occur on that just one element. In the __Bubbling Phase__, the __event__ bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the <code>window</code> while in the __Capturing Phase__ the event starts from the <code>window</code> down to the element that triggered the event or the <code>[event.target](#12-what-is-eventtarget-)</code>.


__Event Propagation__ has __three__ phases.

1. [Capturing Phase](#8-whats-event-capturing) – the event starts from <code>window</code> then goes down to every element until it reaches the target element.
2. [Target Phase](#12-what-is-eventtarget-) – the event has reached the target element.
3. [Bubbling Phase](#7-whats-event-bubbling) – the event bubbles up from the target element then goes up every element until it reaches the <code>window</code>.

![Event Propagation](https://thepracticaldev.s3.amazonaws.com/i/hjayqa99iejfhbsujlqd.png)

###7. What's __Event Bubbling__?
[&uarr;](#the-questions "Back To Questions") When an __event__ occurs on a __DOM__ element, that __event__ does not entirely occur on that just one element. In the __Bubbling Phase__, the __event__ bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the <code>window</code>. 

If we have an example markup like this.
```html
 <div class="grandparent">
    <div class="parent">
      <div class="child">1</div>
    </div>
  </div>
```

And our js code.
```js
function addEvent(el, event, callback, isCapture = false) {
  if (!el || !event || !callback || typeof callback !== 'function') return;
  if (typeof el === 'string') {
    el = document.querySelector(el);
  };
  el.addEventListener(event, callback, isCapture);
}

addEvent(document, 'DOMContentLoaded', () => {
  const child = document.querySelector('.child');
  const parent = document.querySelector('.parent');
  const grandparent = document.querySelector('.grandparent');

  addEvent(child, 'click', function (e) {
    console.log('child');
  });

  addEvent(parent, 'click', function (e) {
    console.log('parent');
  });

  addEvent(grandparent, 'click', function (e) {
    console.log('grandparent');
  });

  addEvent(document, 'click', function (e) {
    console.log('document');
  });

  addEvent('html', 'click', function (e) {
    console.log('html');
  })

  addEvent(window, 'click', function (e) {
    console.log('window');
  })

});
```

The <code>addEventListener</code> method has a third optional parameter __useCapture__ with a default value of <code>false</code> the event will occur in the __Bubbling phase__ if <code>true</code> the event will occur in the __Capturing Phase__. If we click on the <code>child</code> element it logs <code>child</code>,<code>parent</code>,<code>grandparent</code>, <code>html</code>, <code>document</code> and <code>window</code> respectively on the __console__. This is __Event Bubbling__.


###8. What's __Event Capturing__?
[&uarr;](#the-questions "Back To Questions") When an __event__ occurs on a __DOM__ element, that __event__ does not entirely occur on that just one element. In __Capturing Phase__, the event starts from the <code>window</code> all the way down to the element that triggered the event.

If we have an example markup like this.
```html
 <div class="grandparent">
    <div class="parent">
      <div class="child">1</div>
    </div>
  </div>
```

And our js code.
```js
function addEvent(el, event, callback, isCapture = false) {
  if (!el || !event || !callback || typeof callback !== 'function') return;
  if (typeof el === 'string') {
    el = document.querySelector(el);
  };
  el.addEventListener(event, callback, isCapture);
}

addEvent(document, 'DOMContentLoaded', () => {
  const child = document.querySelector('.child');
  const parent = document.querySelector('.parent');
  const grandparent = document.querySelector('.grandparent');

  addEvent(child, 'click', function (e) {
    console.log('child');
  }, true);

  addEvent(parent, 'click', function (e) {
    console.log('parent');
  }, true);

  addEvent(grandparent, 'click', function (e) {
    console.log('grandparent');
  }, true);

  addEvent(document, 'click', function (e) {
    console.log('document');
  }, true);

  addEvent('html', 'click', function (e) {
    console.log('html');
  }, true)

  addEvent(window, 'click', function (e) {
    console.log('window');
  }, true)

});
```

The <code>addEventListener</code> method has a third optional parameter __useCapture__ with a default value of <code>false</code> the event will occur in the __Bubbling phase__ if <code>true</code> the event will occur in the __Capturing Phase__. If we click on the <code>child</code> element it logs <code>window</code>,<code>document</code>,<code>html</code>, <code>grandparent</code> and <code>parent</code> and <code>child</code> respectively on the __console__. This is __Event Capturing__.

###9. What's the difference between <code>event.preventDefault()</code> and <code>event.stopPropagation()</code> methods?

[&uarr;](#the-questions "Back To Questions") The <code>event.preventDefault()</code> method __prevents__ the default behavior of an element. If used in a <code>form</code> element it __prevents__ it from submitting. If used in an <code>anchor</code> element it __prevents__ it from navigating. If used in a <code>contextmenu</code> it __prevents__ it from showing or displaying. While the <code>event.stopPropagation()</code> method stops the propogation of an event or it stops the event from occurring in the [bubbling](#7-whats-event-bubbling) or [capturing](#8-whats-event-capturing) phase.



###10. How to know if the <code>event.preventDefault()</code> method was used in an element?

[&uarr;](#the-questions "Back To Questions") We can use the <code>event.defaultPrevented</code> property in the event object. It returns a <code>boolean</code> indicating if the <code>event.preventDefault()</code> was called in a particular element. 


###11. Why does this code <code>obj.someprop.x</code> throw an error?

```js
const obj = {};
console.log(obj.someprop.x);
```
[&uarr;](#the-questions "Back To Questions")Obviously, this throws an error due to the reason we are trying to access a 
 <code>x</code> property in the <code>someprop</code> property which have an <code>undefined</code> value. Remember __properties__ in an object which does not exist in itself and its __prototype__ has a default value of <code>undefined</code> and <code>undefined</code> has no property <code>x</code>.

###12. What is __event.target__ ?
[&uarr;](#the-questions "Back To Questions") In simplest terms, the __event.target__ is the element on which the event __occurred__ or the element that __triggered__ the event.

Sample HTML Markup.
```html
<div onclick="clickFunc(event)" style="text-align: center;margin:15px;
border:1px solid red;border-radius:3px;">
    <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;">
        <div style="margin:25px;border:1px solid skyblue;border-radius:3px;">
          <button style="margin:10px">
             Button
          </button>
        </div>
    </div>
  </div>
```
Sample JavaScript.
```js
 function clickFunc(event) {
  console.log(event.target);
}
```

If you click the button it will log the __button__ markup even though we attach the event on the outermost <code>div</code> it will always log the __button__ so we can conclude that the __event.target__ is the element that triggered the event.

###13. What is __event.currentTarget__?
[&uarr;](#the-questions "Back To Questions") The __event.currentTarget__ is the element on which we attach the event handler __explicitly__.

Copying the markup in __Question 12__.
Sample HTML Markup.
```html
<div onclick="clickFunc(event)" style="text-align: center;margin:15px;
border:1px solid red;border-radius:3px;">
    <div style="margin: 25px; border:1px solid royalblue;border-radius:3px;">
        <div style="margin:25px;border:1px solid skyblue;border-radius:3px;">
          <button style="margin:10px">
             Button
          </button>
        </div>
    </div>
  </div>
```

And changing our the __JS__ a little bit.
```js
function clickFunc(event) {
  console.log(event.currentTarget);
}
```

If you click the button it will log the outermost __div__ markup even though we click the button. In this example, we can conclude that the __event.currentTarget__ is the element on which we attach the event handler.


###14. What's the difference between <code>==</code> and <code>===</code> ?

[&uarr;](#the-questions "Back To Questions") The difference between <code>==</code>__(abstract equality)__ and <code>===</code>__(strict equality)__ is that the <code>==</code> compares by __value__ after _coercion_ and <code>===</code>  compares by __value__ and __type__ without _coercion_.

Let's dig deeper on the <code>==</code>. So first let's talk about _coercion_.

_coercion_ is the process of converting a value to another type. As in this case, the <code>==</code> does _implicit coercion_. The <code>==</code> has some conditions to perform before comparing the two values.

Suppose we have to compare <code>x == y</code> values.

1. If <code>x</code> and <code>y</code> have same type.
  Then compare them with the <code>===</code> operator.
2. If <code>x</code> is <code>null</code> and <code>y</code> is <code>undefined</code> then return <code>true</code>.
3. If <code>x</code> is <code>undefined</code> and <code>y</code> is <code>null</code> then return <code>true</code>.
4. If <code>x</code> is type <code>number</code> and <code>y</code> is type <code>string</code> 
   Then return <code>x == toNumber(y)</code>.
5. If <code>x</code> is type <code>string</code> and <code>y</code> is type <code>number</code> 
   Then return <code>toNumber(x) == y</code>.
6. If <code>x</code> is type <code>boolean</code>
   Then return <code>toNumber(x) == y</code>.
7. If <code>y</code> is type <code>boolean</code>
   Then return <code>x == toNumber(y)</code>.
8. If <code>x</code> is either <code>string</code>,<code>symbol</code> or <code>number</code> and <code>y</code> is type <code>object</code>
   Then return <code>x == toPrimitive(y)</code>.
9. If <code>x</code> is either <code>object</code> and <code>x</code> is either <code>string</code>,<code>symbol</code>
   Then return <code>toPrimitive(x) == y</code>.
10. Return <code>false</code>.

__Note:__  <code>toPrimitive</code> uses first the <code>valueOf</code> method then the <code>toString</code> method in objects to get the primitive value of that object.

Let's have examples.

|<code>x</code> |<code>y</code> |<code>x == y</code>|
| ------------- |:-------------:| ----------------: |
| <code>5</code>  |<code>5</code>             |<code>true</code> |
| <code>1</code> | <code>'1'</code>          |<code>true</code> |
|<code>null</code>| <code>undefined</code>             |<code>true</code> |
| <code>0</code>| <code>false</code>|<code>true</code> |
| <code>'1,2'</code>| <code>[1,2]</code>|<code>true</code> |
| <code>'[object Object]'</code>|<code>{}</code> |<code>true</code> |


These examples all return <code>true</code>.

The __first example__ goes to __condition one__ because <code>x</code> and <code>y</code> have the same type and value.

The __second example__ goes to __condition four__ <code>y</code> is converted to a <code>number</code> before comparing.

The __third example__ goes to __condition two__.

The __fourth example__ goes to __condition seven__ because <code>y</code> is <code>boolean</code>.

The __fifth example__ goes to __condition eight__. The array is converted to a <code>string</code> using the <code>toString()</code> method which returns <code>1,2</code>.

The __last example__ goes to __condition ten__. The object is converted to a <code>string</code> using the <code>toString()</code> method which returns <code>[object Object]</code>.
 

|<code>x</code> |<code>y</code> |<code>x === y</code>|
| ------------- |:-------------:| ----------------: |
| <code>5</code>  |<code>5</code>             |<code>true</code> |
| <code>1</code> | <code>'1'</code>          |<code>false</code> |
|<code>null</code>| <code>undefined</code>             |<code>false</code> |
| <code>0</code>| <code>false</code>|<code>false</code> |
| <code>'1,2'</code>| <code>[1,2]</code>|<code>false</code> |
| <code>'[object Object]'</code>| <code>{}</code>|<code>false</code> |

If we use the <code>===</code> operator all the comparisons except for the first example will return <code>false</code> because they don't have the same type while the first example will return <code>true</code> because the two have the same type and value.


###15. Why does it return __false__ when comparing two similar objects in JavaScript?

[&uarr;](#the-questions "Back To Questions") Suppose we have an example below.
```js
let a = { a: 1 };
let b = { a: 1 };
let c = a;

console.log(a === b); // logs false even though they have the same property
console.log(a === c); // logs true hmm
```
__JavaScript__ compares _objects_ and _primitives_ differently. In _primitives_ it compares them by __value__ while in _objects_ it compares them by __reference__ or the __address in memory where the variable is stored__. That's why the first <code>console.log</code> statement returns <code>false</code> and the second <code>console.log</code> statement returns <code>true</code>. <code>a</code> and <code>c</code> have the same reference and <code>a</code> and <code>b</code> are not.


###16. What does the __!!__ operator do?
[&uarr;](#the-questions "Back To Questions") The __Double NOT__ operator or __!!__ coerces the value on the right side into a boolean. basically it's a fancy way of converting a value into a boolean.
```js
console.log(!!null); //logs false
console.log(!!undefined); //logs false
console.log(!!''); //logs false
console.log(!!0); //logs false
console.log(!!NaN); //logs false
console.log(!!' '); //logs true
console.log(!!{}); //logs true
console.log(!![]); //logs true
console.log(!!1); //logs true
console.log(!![].length); //logs false
```
###17. How to evaluate multiple expressions in one line?
[&uarr;](#the-questions "Back To Questions")We can use the <code>,</code> or comma operator to evaluate multiple expressions in one line. It evaluates from left-to-right and returns the value of the last item on the right or the last operand.

```js
let x = 5;

x = (x++ , x = addFive(x), x *= 2, x -= 5, x += 10);

function addFive(num) {
  return num + 5;
}
```
If you log the value of <code>x</code> it would be __27__. First, we __increment__ the value of x it would be __6__, then we invoke the function <code>addFive(6)</code> and pass the 6 as a parameter and assign the result to <code>x</code> the new value of <code>x</code> would be __11__. After that, we multiply the current value of <code>x</code> to __2__ and assign it to <code>x</code> the updated value of <code>x</code> would be __22__. Then, we subtract the current value of <code>x</code> to 5 and assign the result to <code>x</code> the updated value would be __17__. And lastly, we increment the value of <code>x</code> by 10 and assign the updated value to <code>x</code> now the value of <code>x</code> would be __27__.


###18. What is __Hoisting__?

[&uarr;](#the-questions "Back To Questions") __Hoisting__ is the term used to describe the moving of _variables_ and _functions_ to the top of their _(global or function)_ scope on where we define that variable or function.

Ok to understand __Hoisting__, I have to explain the _execution context_.
The __Execution Context__  is the "environment of code" that is currently executing. The __Execution Context__ has two phases _compilation_ and _execution_.


__Compilation__ - in this phase it gets all the _function declarations_ and _hoists_ them up to the top of their scope so we can reference them later and gets all _variables declaration_ __(declare with the var keyword)__  and also _hoists_ them up and give them a default value of _undefined_.

__Execution__ - in this phase it assigns values to the variables _hoisted_ earlier and it _executes_ or _invokes_  functions __(methods in objects)__.

__Note:__ only __function declarations__ and variables declared with the _var_ keyword are _hoisted_ not __function expressions__ or __arrow functions__, <code>let</code> and <code>const</code> keywords.


Ok, suppose we have an example code in the _global scope_ below.
```js
console.log(y);
y = 1;
console.log(y);
console.log(greet("Mark"));

function greet(name){
  return 'Hello ' + name + '!';
}

var y;
```
This code logs <code>undefined</code>,<code>1</code>, <code>Hello Mark!</code> respectively.


So the _compilation_ phase would look like this.
```js
function greet(name) {
  return 'Hello ' + name + '!';
}

var y; //implicit "undefined" assignment

//waiting for "compilation" phase to finish

//then start "execution" phase
/*
console.log(y);
y = 1;
console.log(y);
console.log(greet("Mark"));
*/

```
for example purposes, I commented on the _assignment_ of variable and _function call_.

After the _compilation_ phase finishes it starts the _execution_ phase invoking methods and assigns values to variables.
```js
function greet(name) {
  return 'Hello ' + name + '!';
}

var y;

//start "execution" phase

console.log(y);
y = 1;
console.log(y);
console.log(greet("Mark"));
```

###19. What is __Scope__?

[&uarr;](#the-questions "Back To Questions") __Scope__ in JavaScript is the __area__ where we have valid access to variables or functions. JavaScript has three types of Scopes. __Global Scope__, __Function Scope__, and __Block Scope(ES6)__.

* __Global Scope__ - variables or functions declared in the global namespace are in the global scope and therefore is accessible everywhere in our code. 
```js
   //global namespace
   var g = "global";
   
   function globalFunc(){
     function innerFunc(){
          console.log(g); // can access "g" because "g" is a global variable
     }
     innerFunc();
   }  
```
* __Function Scope__ - variables,functions and parameters declared within a function are accessible inside that function but not outside of it.
```js
    function myFavoriteFunc(a) {
       if (true) {
          var b = "Hello " + a;
       }
       return b;
   }
   myFavoriteFunc("World");
   
   console.log(a); // Throws a ReferenceError "a" is not defined
   console.log(b); // does not continue here 
```
* __Block Scope__ - variables __(<code>let</code>,<code>const</code>)__ declared within a block <code>{}</code> can only be access within it.
```js
 function testBlock(){
   if(true){
     let z = 5;
   }
   return z; 
 }
 
 testBlock(); // Throws a ReferenceError "z" is not defined
```

__Scope__ is also a set of rules for finding variables. If a variable does not exist in the __current scope__ it __look ups__ and searches for a variable in the __outer scope__ and if does not exist again it __looks up__ again until it reaches the __global scope__ if the variable exists then we can use it if not it throws an error. It searches for the __nearest__ variable and it stops __searching__ or __looking up__ once it finds it. This is called __Scope Chain__.

```js
   /* Scope Chain
   Inside inner function perspective

   inner's scope -> outer's scope -> global's scope
  */


  //Global Scope
  var variable1 = "Comrades";   
  var variable2 = "Sayonara";
  
  function outer(){
  //outer's scope
    var variable1 = "World";
    function inner(){
    //inner's scope
      var variable2 = "Hello";
      console.log(variable2 + " " + variable1);
    }
    inner();
  }  
  outer(); 
// logs Hello World 
// because (variable2 = "Hello") and (variable1 = "World") are the nearest 
// variables inside inner's scope.
```


![Scope](https://thepracticaldev.s3.amazonaws.com/i/l81b3nmdonimex0qsgyr.png)



###20. What are __Closures__?
[&uarr;](#the-questions "Back To Questions") This is probably the hardest question of all these questions because __Closures__ is a controversial topic. So I'm gonna explain it from what I understand. 

__Closures__ is simply the ability of a function at the time of declaration to remember the references of variables and parameters on its current scope, on its parent function scope, on its parent's parent function scope until it reaches the global scope with the help of __Scope Chain__. Basically it is the __Scope__ created when the function was declared.

Examples are a great way to explain closures.
```js
   //Global's Scope
   var globalVar = "abc";

   function a(){
   //testClosures's Scope
     console.log(globalVar);
   }
   
   a(); //logs "abc" 
   /* Scope Chain
      Inside a function perspective
      
      a's scope -> global's scope  
   */ 
```
In this example, when we declare the <code>a</code> function the __Global Scope__ is part of <code>a's</code> _closure_.

![a's closure](https://thepracticaldev.s3.amazonaws.com/i/teatokuw4xvgtlzbzhn8.png)

The reason for the variable <code>globalVar</code> which does not have a value in the image because of the reason that the value of that variable can change based on __where__ and __when__ we invoke the <code>a</code> function.
But in our example above the <code>globalVar</code> variable will have the value of __abc__.


Ok, let's have a complex example.
```js
var globalVar = "global";
var outerVar = "outer"

function outerFunc(outerParam) {
  function innerFunc(innerParam) {
    console.log(globalVar, outerParam, innerParam);
  }
  return innerFunc;
}

const x = outerFunc(outerVar);
outerVar = "outer-2";
globalVar = "guess"
x("inner");
```
![Complex](https://thepracticaldev.s3.amazonaws.com/i/e4hxm7zvz8eun2ppenwp.png)
This will print "guess outer inner". The explanation for this is that when we invoke the <code>outerFunc</code> function and assigned the returned value the <code>innerFunc</code> function to the variable <code>x</code>, the <code>outerParam</code> will have a value of __outer__ even though we assign a new value __outer-2__ to the <code>outerVar</code> variable because
the reassignment happened after the invocation of the <code>outer</code> function and in that time when we invoke the <code>outerFunc</code> function it's look up the value of <code>outerVar</code> in the __Scope Chain__, the <code>outerVar</code> will have a value of __"outer"__. Now, when we invoke the <code>x</code> variable which have a reference to the <code>innerFunc</code>, the
<code>innerParam</code> will have a value of __inner__ because thats the value we pass in the invocation and the <code>globalVar</code> variable will have a value of __guess__ because before the invocation of the <code>x</code> variable we assign a new value to the <code>globalVar</code> and at the time of invocation <code>x</code> the value of <code>globalVar</code> in the __Scope Chain__ is __guess__.

We have an example that demonstrates a problem of not understanding closure correctly.
```js
const arrFuncs = [];
for(var i = 0; i < 5; i++){
  arrFuncs.push(function (){
    return i;
  });
}
console.log(i); // i is 5

for (let i = 0; i < arrFuncs.length; i++) {
  console.log(arrFuncs[i]()); // all logs "5"
}
```

This code is not working as we expected because of __Closures__.
The <code>var</code> keyword makes a global variable and when we push a function 
we return the global variable <code>i</code>. So when we call one of those functions in that array after the loop it logs <code>5</code> because we get
the current value of <code>i</code> which is <code>5</code> and we can  access it because it's a global variable. Because __Closures__ keeps the __references__ of that variable not its __values__ at the time of it's creation. We can solve this using __IIFES__ or changing the <code>var</code> keyword to <code>let</code> for block-scoping.

###21. What are the __falsy__ values in __JavaScript__?
[&uarr;](#the-questions "Back To Questions")
```js
 const falsyValues = ['', 0, null, undefined, NaN, false];
```
__falsy__ values are values that when converted to boolean becomes __false__.


###22. How to check if a value is __falsy__?
[&uarr;](#the-questions "Back To Questions") Use the __Boolean__ function or the Double NOT operator __[!!](#16-what-does-the-operator-do)__


###23. What does <code>"use strict"</code> do?
[&uarr;](#the-questions "Back To Questions") <code>"use strict"</code> is a ES5 feature in __JavaScript__ that makes our code in __Strict Mode__  in _functions_ or _entire scripts_. __Strict Mode__ helps us avoid __bugs__ early on in our code and adds restrictions to it.

Restrictions that __Strict Mode__ gives us.

* Assigning or Accessing a variable that is not declared.
```js
 function returnY(){
    "use strict";
    y = 123;
    return y;
 }
```

* Assigning a value to a read-only or non-writable global variable;
```js
   "use strict";
   var NaN = NaN;
   var undefined = undefined;
   var Infinity = "and beyond";
```

* Deleting an undeletable property.
```js
   "use strict";
   const obj = {};
   
   Object.defineProperty(obj, 'x', {
      value : '1'
   });  
    
   delete obj.x;
```

* Duplicate parameter names.
```js
   "use strict";
   
   function someFunc(a, b, b, c){

   }
```

* Creating variables with the use of the __eval__ function.
```js
 "use strict";
   
 eval("var x = 1;");

 console.log(x); //Throws a Reference Error x is not defined

```
* The default value of __this__ will be <code>undefined</code>.
```js
  "use strict";
  
  function showMeThis(){
    return this;
  }
  
  showMeThis(); //returns undefined
```
There are many more restrictions in __Strict Mode__ than these.

###24. What's the value of <code>this</code> in JavaScript?
[&uarr;](#the-questions "Back To Questions") Basically, <code>this</code> refers to the value of the object that is currently executing or invoking the function. I say __currently__ due to the reason that the value of __this__ changes depending on the context on which we use it and where we use it.

```js
   const carDetails = {
     name: "Ford Mustang",
     yearBought: 2005,
     getName(){
        return this.name;
     },
     isRegistered: true
   };
  
   console.log(carDetails.getName()); // logs Ford Mustang
```
This is what we would normally expect because in the __getName__ method we return <code>this.name</code>, <code>this</code> in this context refers to the object which is the <code>carDetails</code> object that is currently the "owner" object of the function executing.

Ok, Let's some add some code to make it weird. Below the <code>console.log</code> statement add this three lines of code 

```js
   var name = "Ford Ranger";
   var getCarName = carDetails.getName;

   console.log(getCarName()); // logs Ford Ranger
```
The second <code>console.log</code> statement prints the word __Ford Ranger__ which is weird because in our first <code>console.log</code> statement it printed __Ford Mustang__. The reason to this is that the <code>getCarName</code> method has a different "owner" object that is the <code>window</code> object. Declaring variables with the <code>var</code> keyword in the global scope attaches properties in the <code>window</code> object with the same name as the variables. Remember <code>this</code> in the global scope refers to the <code>window</code> object when <code>"use strict"</code> is not used.

```js
  console.log(getCarName === window.getCarName); //logs true
  console.log(getCarName === this.getCarName); // logs true
```
<code>this</code> and <code>window</code> in this example refer to the same object.

One way of solving this problem is by using the <code>[apply](#27-what-is-the-use-functionprototypeapply-method)</code> and <code>[call](#28-what-is-the-use-functionprototypecall-method)</code> methods in functions.
```js
   console.log(getCarName.apply(carDetails)); //logs Ford Mustang
   console.log(getCarName.call(carDetails));  //logs Ford Mustang
```
The <code>apply</code> and <code>call</code> methods expects the first parameter to be an object which would be value of <code>this</code> inside that function. 


__IIFE__ or __Immediately Invoked Function Expression__, Functions that are declared in the global scope, __Anonymous Functions__ and Inner functions in methods inside an object has a default of __this__ which points to the __window__ object.
```js
   (function (){
     console.log(this);
   })(); //logs the "window" object

   function iHateThis(){
      console.log(this);
   }
 
   iHateThis(); //logs the "window" object  

   const myFavoriteObj = {
     guessThis(){
        function getThis(){
          console.log(this);
        }
        getThis();
     },
     name: 'Marko Polo',
     thisIsAnnoying(callback){
       callback();
     }
   };


   myFavoriteObj.guessThis(); //logs the "window" object
   myFavoriteObj.thisIsAnnoying(function (){
     console.log(this); //logs the "window" object
   });
```
If we want to get the value of the <code>name</code> property which is __Marko Polo__ in the <code>myFavoriteObj</code> object there are two ways to solve this.

First, we save the value of <code>this</code> in a variable.
```js
   const myFavoriteObj = {
     guessThis(){
         const self = this; //saves the this value to the "self" variable
         function getName(){
           console.log(self.name);
         }
         getName();
     },
     name: 'Marko Polo',
     thisIsAnnoying(callback){
       callback();
     }
   };
```
In this image we save the value of <code>this</code> which would be the <code>myFavoriteObj</code> object. So we can access it inside the <code>getName</code> inner function.

Second, we use __ES6 [Arrow Functions](#43-what-are-arrow-functions)__.
```js
   const myFavoriteObj = {
     guessThis(){
         const getName = () => { 
           //copies the value of "this" outside of this arrow function
           console.log(this.name);
         }
         getName();
     },
     name: 'Marko Polo',
     thisIsAnnoying(callback){
       callback();
     }
   };
```
[Arrow Functions](#43-what-are-arrow-functions) does not have its own <code>this</code>. It copies the value of <code>this</code> of the enclosing lexical scope or in this example the value of <code>this</code> outside the <code>getName</code> inner function which would be the <code>myFavoriteObj</code> object. We can also determine the value of <code>this</code> on [how the function is invoked](#66-how-many-ways-can-a-function-be-invoked).

###25. What is the <code>prototype</code> of an object?

[&uarr;](#the-questions "Back To Questions") A <code>prototype</code> in simplest terms is a _blueprint_ of an object. It is used as a fallback for __properties__ and __methods__ if it does exist in the current object. It's the way to share properties and functionality between objects. It's the core concept around JavaScript's __Prototypal Inheritance__.


```js
  const o = {};
  console.log(o.toString()); // logs [object Object] 
```

Even though the <code>o.toString</code> method does not exist in the <code>o</code> object it does not throw an error instead returns a string <code>[object Object]</code>. When a property does not exist in the object it looks into its __prototype__ and if it still does not exist it looks into the  __prototype's prototype__ and so on until it finds a property with the same in the __Prototype Chain__. The end of the __Prototype Chain__ is `null` after the __Object.prototype__.

```js
   console.log(o.toString === Object.prototype.toString); // logs true
   // which means we we're looking up the Prototype Chain and it reached 
   // the Object.prototype and used the "toString" method.
```




###26. What is an __IIFE__, what is the use of it?

[&uarr;](#the-questions "Back To Questions") An __IIFE__ or __Immediately Invoked Function Expression__ is a function that is gonna get invoked or executed after its creation or declaration. The syntax for creating __IIFE__ is that we wrap the <code>function (){}</code> inside a parentheses <code>()</code> or the __Grouping Operator__ to treat the function as an expression and after that we invoke it with another parentheses <code>()</code>. So an __IIFE__ looks like this <code>(function(){})()</code>.

```js
(function () {

}());

(function () {

})();

(function named(params) {

})();

(() => {

})();

(function (global) {

})(window);

const utility = (function () {
   return {
      //utilities
   };
})();
```
These examples are all valid __IIFE__. The second to the last example shows we can pass arguments to an __IIFE__ function. The last example shows that we can save the result of the __IIFE__ to a variable so we can reference it later.

The best use of __IIFE__ is making initialization setup functionalities and to avoid __naming collisions__ with other variables in the global scope or polluting the global namespace. Let's have an example.  
```html
<script src="https://cdnurl.com/somelibrary.js"></script>
```
Suppose we have a link to a library <code>somelibrary.js</code> that exposes some global functions that we use can in our code but this library has two methods that we don't use <code>createGraph</code> and <code>drawGraph</code> because these methods have bugs in them. And we want to implement our own <code>createGraph</code> and <code>drawGraph</code> methods. 

* One way of solving this is by changing the structure of our scripts.
```html
<script src="https://cdnurl.com/somelibrary.js"></script>
<script>
   function createGraph() {
      // createGraph logic here
   }
   function drawGraph() {
      // drawGraph logic here
   }
</script>
```
When we use this solution we are overriding those two methods that the library gives us.


* Another way of solving this is by changing the name of our own helper functions.
```html
<script src="https://cdnurl.com/somelibrary.js"></script>
<script>
   function myCreateGraph() {
      // createGraph logic here
   }
   function myDrawGraph() {
      // drawGraph logic here
   }
</script>
```
When we use this solution we will also change those function calls to the new function names.

* Another way is using an __IIFE__.
```html
<script src="https://cdnurl.com/somelibrary.js"></script>
<script>
   const graphUtility = (function () {
      function createGraph() {
         // createGraph logic here
      }
      function drawGraph() {
         // drawGraph logic here
      }
      return {
         createGraph,
         drawGraph
      }
   })();
</script>
```
In this solution, we are making a utility variable that is the result of __IIFE__ which returns an object that contains two methods <code>createGraph</code> and <code>drawGraph</code>.



Another problem that __IIFE__ solves is in this example.
```js
var li = document.querySelectorAll('.list-group > li');
for (var i = 0, len = li.length; i < len; i++) {
   li[i].addEventListener('click', function (e) {
      console.log(i);
   })
}
```
Suppose we have a <code>ul</code> element with a class of __list-group__ and it has 5 <code>li</code> child elements. And we want to <code>console.log</code> the value of <code>i</code> when we __click__ an individual <code>li</code> element. 
But the behavior we want in this code does not work. Instead, it logs <code>5</code> in any __click__ on an <code>li</code> element. The problem we're having is due to how __Closures__ work. __Closures__ are simply the ability of functions to remember the references of variables on its current scope, on its parent function scope and in the global scope. When we declare variables using the <code>var</code> keyword in the global scope, obviously we are making a global variable <code>i</code>. So when we click an <code>li</code> element it logs __5__ because that is the value of <code>i</code> when we reference it later in the callback function.

* One solution to this is an __IIFE__.
 ```js
var li = document.querySelectorAll('.list-group > li');
for (var i = 0, len = li.length; i < len; i++) {
   (function (currentIndex) {
      li[currentIndex].addEventListener('click', function (e) {
         console.log(currentIndex);
      })
   })(i);
}
```
This solution works because of the reason that the __IIFE__ creates a new scope for every iteration and we capture the value of <code>i</code> and pass it into the <code>currentIndex</code> parameter so the value of <code>currentIndex</code> is different for every iteration when we invoke the __IIFE__.

###27. What is the use <code>Function.prototype.apply</code> method?
[&uarr;](#the-questions "Back To Questions") The <code>apply</code> invokes a function specifying the <code>this</code> or the "owner" object of that function on that time of invocation. 
```js
const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}

getMessage.apply(details); // returns 'Hello World!'
```
This method works like <code>[Function.prototype.call](#28-what-is-the-use-functionprototypecall-method)</code> the only difference is how we pass arguments. In <code>apply</code> we pass arguments as an array.
```js
const person = {
  name: "Marko Polo"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.apply(person, ['Hello']); // returns "Hello Marko Polo!"
```
###28. What is the use <code>Function.prototype.call</code> method?
[&uarr;](#the-questions "Back To Questions") The <code>call</code> invokes a function specifying the <code>this</code> or the "owner" object of that function on that time of invocation. 
```js
const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}

getMessage.call(details); // returns 'Hello World!'
```
This method works like <code>[Function.prototype.apply](#27-what-is-the-use-functionprototypeapply-method)</code> the only difference is how we pass arguments. In <code>call</code> we pass directly the arguments separating them with a comma <code>,</code> for every argument.

```js
const person = {
  name: "Marko Polo"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.call(person, 'Hello'); // returns "Hello Marko Polo!"
```
###29. What's the difference between <code>Function.prototype.apply</code> and <code>Function.prototype.call</code>?

[&uarr;](#the-questions "Back To Questions") The only difference between <code>apply</code> and <code>call</code> is how we pass the __arguments__ in the function being called. In <code>apply</code> we pass the arguments as an __array__ and in <code>call</code> we pass the arguments directly in the argument list.

```js
const obj1 = {
 result:0
};

const obj2 = {
 result:0
};

function reduceAdd(){
   let result = 0;
   for(let i = 0, len = arguments.length; i < len; i++){
     result += arguments[i];
   }
   this.result = result;
}

reduceAdd.apply(obj1, [1, 2, 3, 4, 5]); // returns 15
reduceAdd.call(obj2, 1, 2, 3, 4, 5); // returns 15
```
###30. What is the usage of <code>Function.prototype.bind</code>?
[&uarr;](#the-questions "Back To Questions") The <code>bind</code> method returns a new function that is _bound_ 
to a specific <code>this</code> value or the "owner" object, So we can use it later in our code. The <code>call</code>,<code>apply</code> methods invokes the function immediately instead of returning a new function like the <code>bind</code> method.
```js
import React from 'react';

class MyComponent extends React.Component {
     constructor(props){
          super(props); 
          this.state = {
             value : ""
          }  
          this.handleChange = this.handleChange.bind(this); 
          // Binds the "handleChange" method to the "MyComponent" component
     }
 
     handleChange(e){
       //do something amazing here
     }

     render(){
        return (
              <>
                <input type={this.props.type}
                        value={this.state.value}
                     onChange={this.handleChange}                      
                  />
              </>
        )
     }
}
```


###31. What is __Functional Programming__ and what are the features of __JavaScript__ that makes it a candidate as a __functional language__?


[&uarr;](#the-questions "Back To Questions") __Functional Programming__ is a __declarative__ programming paradigm or pattern on how we build our applications with __functions__ using __expressions__ that calculates a value without mutating or changing the arguments that are passed to it.

JavaScript __Array__ has  __map__, __filter__, __reduce__ methods which are the most famous functions in the functional programming world because of their usefulness and because they don't mutate or change the array which makes these functions __pure__ and JavaScript supports __Closures__ and __Higher Order Functions__ which are a characteristic of a __Functional Programming Language__.

* The __map__ method creates a new array with the results of calling a provided callback function on every element in the array.
```js
const words = ["Functional", "Procedural", "Object-Oriented"];

const wordsLength = words.map(word => word.length);
```

* The __filter__ method creates a new array with all elements that pass the test in the callback function.
```js
const data = [
  { name: 'Mark', isRegistered: true },
  { name: 'Mary', isRegistered: false },
  { name: 'Mae', isRegistered: true }
];

const registeredUsers = data.filter(user => user.isRegistered);
```

* The __reduce__ method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
```js
const strs = ["I", " ", "am", " ", "Iron", " ", "Man"];
const result = strs.reduce((acc, currentStr) => acc + currentStr, "");
```

###32. What are __Higher Order Functions__?

[&uarr;](#the-questions "Back To Questions") __Higher-Order Function__ are functions that can return a function or receive argument or arguments which have a value of a function.

```js
function higherOrderFunction(param,callback){
    return callback(param);
}
```
###33. Why are functions called __First-class Objects__?
[&uarr;](#the-questions "Back To Questions")__Functions__ in JavaScript are __First-class Objects__ because they are treated as any other value in the language. They can be assigned to __variables__, they can be __properties of an object__ which are called __methods__, they can be an __item in array__, they can be __passed as arguments to a function__, and they can be __returned as values of a function__. The only difference between a function and any other value in __JavaScript__ is that __functions__ can be invoked or called.


###34. Implement the <code>Array.prototype.map</code> method by hand.
[&uarr;](#the-questions "Back To Questions")
```js
function map(arr, mapCallback) {
  // First, we check if the parameters passed are right.
  if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') { 
    return [];
  } else {
    let result = [];
    // We're making a results array every time we call this function
    // because we don't want to mutate the original array.
    for (let i = 0, len = arr.length; i < len; i++) {
      result.push(mapCallback(arr[i], i, arr)); 
      // push the result of the mapCallback in the 'result' array
    }
    return result; // return the result array
  }
}
```
As the MDN description of the <code>Array.prototype.map</code> method.

__The map() method creates a new array with the results of calling a provided function on every element in the calling array.__


###35. Implement the <code>Array.prototype.filter</code> method by hand.
[&uarr;](#the-questions "Back To Questions")
```js
function filter(arr, filterCallback) {
  // First, we check if the parameters passed are right.
  if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== 'function') 
  {
    return [];
  } else {
    let result = [];
    // We're making a results array every time we call this function
    // because we don't want to mutate the original array.
    for (let i = 0, len = arr.length; i < len; i++) {
      // check if the return value of the filterCallback is true or "truthy"
      if (filterCallback(arr[i], i, arr)) { 
      // push the current item in the 'result' array if the condition is true
        result.push(arr[i]);
      }
    }
    return result; // return the result array
  }
}
```
As the MDN description of the <code>Array.prototype.filter</code> method.

__The filter() method creates a new array with all elements that pass the test implemented by the provided function.__


###36. Implement the <code>Array.prototype.reduce</code> method by hand.
[&uarr;](#the-questions "Back To Questions")```js
function reduce(arr, reduceCallback, initialValue) {
  // First, we check if the parameters passed are right.
  if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function') 
  {
    return [];
  } else {
    // If no initialValue has been passed to the function we're gonna use the 
    let hasInitialValue = initialValue !== undefined;
    let value = hasInitialValue ? initialValue : arr[0];
    // first array item as the initialValue
    
    // Then we're gonna start looping at index 1 if there is no 
    // initialValue has been passed to the function else we start at 0 if 
    // there is an initialValue.
    for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) {
      // Then for every iteration we assign the result of the 
      // reduceCallback to the variable value.
      value = reduceCallback(value, arr[i], i, arr); 
    }
    return value;
  }
}
```
As the MDN description of the <code>Array.prototype.reduce</code> method.

__The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.__


###37. What is the __arguments__ object?
[&uarr;](#the-questions "Back To Questions") The __arguments__ object is a collection of parameter values pass in a function. It's an __Array-like__ object because it has a __length__ property and we can access individual values using array indexing notation <code>arguments[1]</code> but it does not have the built-in methods in an array <code>forEach</code>,<code>reduce</code>,<code>filter</code> and <code>map</code>.
It helps us know the number of arguments pass in a function.

We can convert the <code>arguments</code> object into an array using the <code>Array.prototype.slice</code>.
```js
function one() {
  return Array.prototype.slice.call(arguments);
}
```
Note: __the <code>arguments</code> object does not work on ES6 arrow functions.__
```js
function one() {
  return arguments;
}
const two = function () {
  return arguments;
}
const three = function three() {
  return arguments;
}

const four = () => arguments;

four(); // Throws an error  - arguments is not defined
```
When we invoke the function <code>four</code> it throws a <code>ReferenceError: arguments is not defined</code> error. We can solve this problem if your enviroment supports the __rest syntax__.

```js
const four = (...args) => args;
```
This puts all parameter values in an array automatically.


###38. How to create an object without a __prototype__?
[&uarr;](#the-questions "Back To Questions") We can create an object without a _prototype_ using the <code>Object.create</code> method.

```js
   const o1 = {};
   console.log(o1.toString()); 
   // logs [object Object] get this method to the Object.prototype 

   const o2 = Object.create(null);
   // the first parameter is the prototype of the object "o2" which in this
   // case will be null specifying we don't want any prototype
   console.log(o2.toString());
   // throws an error o2.toString is not a function 
```

###39. Why does <code>b</code> in this code become a global variable when you call this function?
[&uarr;](#the-questions "Back To Questions")
```js
function myFunc() {
  let a = b = 0;
}

myFunc();
```
The reason for this is that __assignment operator__ or __=__ has right-to-left __associativity__ or __evaluation__. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this.

```js
function myFunc() {
  let a = (b = 0);
}

myFunc();
```
First, the expression <code>b = 0</code> evaluated and in this example <code>b</code> is not declared. So, The JS Engine makes a global variable <code>b</code> outside this function after that the return value of the expression <code>b = 0</code> would be 0 and it's assigned to the new local variable <code>a</code> with a <code>let</code> keyword.

We can solve this problem by declaring the variables first before assigning them with value.
```js
function myFunc() {
  let a,b;
  a = b = 0;
}
myFunc();
```

###40. <div id="ecmascript">What is __ECMAScript__</div>?

[&uarr;](#the-questions "Back To Questions") __ECMAScript__ is a standard for making scripting languages which means that __JavaScript__ follows the specification changes in __ECMAScript__ standard because it is the __blueprint__ of __JavaScript__.


###41. What are the new features in __ES6__ or __ECMAScript 2015__?
[&uarr;](#the-questions "Back To Questions")
* [Arrow Functions](#43-what-are-arrow-functions)
    
* [Classes](#44-what-are-classes)
     
* [Template Strings](#45-what-are-template-literals)

* __Enhanced Object literals__

* [Object Destructuring](#46-what-is-object-destructuring)

* [Promises](#50-what-are-promises)

* __Generators__

* [Modules](#47-what-are-es6-modules) 

* Symbol

* __Proxies__

* [Sets](#48-what-is-the-set-object-and-how-does-it-work)

* [Default Function parameters](#53-what-are-default-parameters)

* [Rest and Spread](#52-whats-the-difference-between-spread-operator-and-rest-operator)

* [Block Scoping with <code>let</code> and <code>const</code>](#42-whats-the-difference-between-var-let-and-const-keywords)

###42. What's the difference between <code>var</code>, <code>let</code> and <code>const</code> keywords?
[&uarr;](#the-questions "Back To Questions") Variables declared with <code>var</code> keyword are _function scoped_.
What this means that variables can be accessed across that function even if we declare that variable inside a block.
```js
function giveMeX(showX) {
  if (showX) {
    var x = 5;
  }
  return x;
}

console.log(giveMeX(false));
console.log(giveMeX(true));
```
The first <code>console.log</code> statement logs <code>undefined</code>
and the second <code>5</code>. We can access the <code>x</code> variable due
to the reason that it gets _hoisted_ at the top of the function scope. So our function code is intepreted like this.
```js
function giveMeX(showX) {
  var x; // has a default value of undefined
  if (showX) {
    x = 5;
  }
  return x;
}
```
If you are wondering why it logs <code>undefined</code> in the first <code>console.log</code> statement remember variables declared without an initial value has a default value of <code>undefined</code>.

Variables declared with <code>let</code> and <code>const</code>  keyword are _block scoped_. What this means that variable can only be accessed on that block <code>{}</code> on where we declare it.

```js
function giveMeX(showX) {
  if (showX) {
    let x = 5;
  }
  return x;
}


function giveMeY(showY) {
  if (showY) {
    let y = 5;
  }
  return y;
}
```
If we call this functions with an argument of <code>false</code> it throws a <code>Reference Error</code> because we can't access the <code>x</code> and <code>y</code> variables outside that block and those variables are not _hoisted_.

There is also a difference between <code>let</code> and <code>const</code> we can assign new values using <code>let</code> but we can't in <code>const</code> but <code>const</code> are mutable meaning. What this means is if the value that we assign to a <code>const</code> is an object we can change the values of those properties but can't reassign a new value to that variable.

###43. What are __Arrow functions__?

[&uarr;](#the-questions "Back To Questions") __Arrow Functions__ are a new way of making functions in JavaScript. __Arrow Functions__ takes a little time in making functions and has a cleaner syntax than a __function expression__ because we omit the <code>function</code> keyword in making them.

```js
//ES5 Version
var getCurrentDate = function (){
  return new Date();
}

//ES6 Version
const getCurrentDate = () => new Date();
```
In this example, in the ES5 Version have <code>function(){}</code> declaration and <code>return</code> keyword needed to make a function and return a value respectively. In the __Arrow Function__ version we only need the <code>()</code> parentheses and we don't need a <code>return</code> statement because __Arrow Functions__ have a implicit return if we have only one expression or value to return.

```js
//ES5 Version
function greet(name) {
  return 'Hello ' + name + '!';
}

//ES6 Version
const greet = (name) => `Hello ${name}`;
const greet2 = name => `Hello ${name}`;

```
We can also parameters in __Arrow functions__ the same as the __function expressions__ and __function declarations__. If we have one parameter in an __Arrow Function__ we can omit the parentheses it is also valid.



```js
const getArgs = () => arguments

const getArgs2 = (...rest) => rest
```
__Arrow functions__ don't have access to the <code>arguments</code> object. So calling the first <code>getArgs</code> func will throw an Error. Instead we can use the __rest parameters__ to get all the arguments passed in an arrow function.

```js
const data = {
  result: 0,
  nums: [1, 2, 3, 4, 5],
  computeResult() {
    // "this" here refers to the "data" object
    const addAll = () => {
      // arrow functions "copies" the "this" value of 
      // the lexical enclosing function
      return this.nums.reduce((total, cur) => total + cur, 0)
    };
    this.result = addAll();
  }
};
```
__Arrow functions__ don't have their own <code>this</code> value. It captures or gets the <code>this</code> value of  lexically enclosing function or in this example, the <code>addAll</code> function copies the <code>this</code> value of the <code>computeResult</code> method and if we declare an arrow function in the global scope the value of <code>this</code> would be the <code>window</code> object.


###44. What are __Classes__?
[&uarr;](#the-questions "Back To Questions") __Classes__ is the new way of writing _constructor functions_ in __JavaScript__. It is _syntactic sugar_ for using _constructor functions_, it still uses __prototypes__ and __Prototype-Based Inheritance__ under the hood.

```js
   //ES5 Version
   function Person(firstName, lastName, age, address){
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.address = address;
   }

   Person.self = function(){
     return this;
   }

   Person.prototype.toString = function(){
     return "[object Person]";
   }

   Person.prototype.getFullName = function (){
     return this.firstName + " " + this.lastName;
   }  

   //ES6 Version
   class Person {
        constructor(firstName, lastName, age, address){
            this.lastName = lastName;
            this.firstName = firstName;
            this.age = age;
            this.address = address;
        }

        static self() {
           return this;
        }
     
        toString(){
           return "[object Person]";
        }

        getFullName(){
           return `${this.firstName} ${this.lastName}`;
        }
   }
```

__Overriding Methods__ and __Inheriting from another class__.
```js 
//ES5 Version
Employee.prototype = Object.create(Person.prototype);

function Employee(firstName, lastName, age, address, jobTitle, yearStarted) {
  Person.call(this, firstName, lastName, age, address);
  this.jobTitle = jobTitle;
  this.yearStarted = yearStarted;
}

Employee.prototype.describe = function () {
  return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}`;
}

Employee.prototype.toString = function () {
  return "[object Employee]";
}

//ES6 Version
class Employee extends Person { //Inherits from "Person" class
  constructor(firstName, lastName, age, address, jobTitle, yearStarted) {
    super(firstName, lastName, age, address);
    this.jobTitle = jobTitle;
    this.yearStarted = yearStarted;
  }

  describe() {
    return `I am ${this.getFullName()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted}`;
  }

  toString() { // Overriding the "toString" method of "Person"
    return "[object Employee]";
  }
}

```
So how do we know that it uses _prototypes_ under the hood?
```js
   class Something {

   }
   
   function AnotherSomething(){

   }
   const as = new AnotherSomething();
   const s = new Something();

   console.log(typeof Something); // logs "function"
   console.log(typeof AnotherSomething); // logs "function"
   console.log(as.toString()); // logs "[object Object]"
   console.log(as.toString()); // logs "[object Object]"
   console.log(as.toString === Object.prototype.toString); 
   console.log(s.toString === Object.prototype.toString); 
   // both logs return true indicating that we are still using 
   // prototypes under the hoods because the Object.prototype is
   // the last part of the Prototype Chain and "Something"
   // and "AnotherSomething" both inherit from Object.prototype
```
###45. What are __Template Literals__?
[&uarr;](#the-questions "Back To Questions") __Template Literals__ are a new way of making __strings__ in JavaScript. We can make __Template Literal__ by using the backtick or back-quote symbol.
```js
//ES5 Version
var greet = 'Hi I\'m Mark';

//ES6 Version
let greet = `Hi I'm Mark`;
```
In the ES5 version, we need to escape the <code>'</code> using the <code>\\</code>  to _escape_ the normal functionality of that symbol which in this case is to finish that string value. In Template Literals, we don't need to do that.


```js
//ES5 Version
var lastWords = '\n'
  + '   I  \n'
  + '   Am  \n'
  + 'Iron Man \n';


//ES6 Version
let lastWords = `
    I
    Am
  Iron Man   
`;
```
In the ES5 version, we need to add this <code>\n</code> to have a new line in our string. In Template Literals, we don't need to do that.

```js
//ES5 Version
function greet(name) {
  return 'Hello ' + name + '!';
}


//ES6 Version
const greet = name => {
  return `Hello ${name} !`;
}
```
In the ES5 version, If we need to add an expression or value in a string we need to use the <code>+</code> or string concatenation operator. In Template Literals, we can embed an expression using <code>${expr}</code> which makes it cleaner than the ES5 version.


###46. What is __Object Destructuring__?
[&uarr;](#the-questions "Back To Questions") __Object Destructuring__ is a new and cleaner way of __getting__ or __extracting__ values from an object or an array.

Suppose we have an object that looks like this.
```js
const employee = {
  firstName: "Marko",
  lastName: "Polo",
  position: "Software Developer",
  yearHired: 2017
};

```
The old way of getting properties from an object is we make a variable that has the same name as the object property. This way is a hassle because we're making a new variable for every property. Imagine we have a big object with lots of properties and methods using this way in extracting properties will be irritating.
```js
var firstName = employee.firstName;
var lastName = employee.lastName;
var position = employee.position;
var yearHired = employee.yearHired;
```

If we use __object destructuring__ it looks cleaner and takes a little time than the old way. The syntax for object destructuring is that if we are getting properties in an object we use the <code>{}</code> and inside that, we specify the properties we want to extract and if we are getting data from an array we use the <code>[]</code>.
```js
let { firstName, lastName, position, yearHired } = employee;
```

If we want to change the variable name we want to extract we use the <code>propertyName:newName</code> syntax. In this example the value of <code>fName</code> variable will hold the value of the <code>firstName</code> property and <code>lName</code> variable will hold the value of the <code>lastName</code> property.
```js
let { firstName: fName, lastName: lName, position, yearHired } = employee;
```
We can also have default values when destructuring. In this example, if the <code>firstName</code> property holds an <code>undefined</code> value in the object then when we destructure the <code>firstName</code> variable will hold a default of <code>"Mark"</code>.
```js
let { firstName = "Mark", lastName: lName, position, yearHired } = employee;
```

###47. What are <code>ES6 Modules</code>?
[&uarr;](#the-questions "Back To Questions") __Modules__ lets us split our code base to multiple files for more maintainability and this lets us avoid putting all of our code in one big file (yucksss). Before ES6 has supported Modules there were two popular module systems that were used for Code Maintainability in __JavaScript__.

* CommonJS - __Nodejs__
* AMD (Asynchronous Module Definition) - __Browsers__


Basically, the sytanx for using modules are straightforward, 
<code>import</code> is used for _getting_ functionality from another file or several functionalities or values while 
<code>export</code> is used for _exposing_ functionality from a file or several functionalities or values.


__Exporting functionalites in a File or Named Exports__

_Using ES5 (CommonJS)_
```js
// Using ES5 CommonJS - helpers.js
exports.isNull = function (val) {
  return val === null;
}

exports.isUndefined = function (val) {
  return val === undefined;
}

exports.isNullOrUndefined = function (val) {
  return exports.isNull(val) || exports.isUndefined(val);
}
```
_Using ES6 Modules_
```js
// Using ES6 Modules - helpers.js
export function isNull(val){
  return val === null;
}

export function isUndefined(val) {
  return val === undefined;
}

export function isNullOrUndefined(val) {
  return isNull(val) || isUndefined(val);
}


```

__Importing functionalites in another File__

```js
// Using ES5 (CommonJS) - index.js
const helpers = require('./helpers.js'); // helpers is an object
const isNull = helpers.isNull;
const isUndefined = helpers.isUndefined;
const isNullOrUndefined = helpers.isNullOrUndefined;

// or if your environment supports Destructuring
const { isNull, isUndefined, isNullOrUndefined } = require('./helpers.js');
```


```js
// ES6 Modules - index.js
import * as helpers from './helpers.js'; // helpers is an object

// or 

import { isNull, isUndefined, isNullOrUndefined as isValid } from './helpers.js';

// using "as" for renaming named exports
```

__Exporting a Single Functionality in a File or Default Exports__

_Using ES5 (CommonJS)_
```js
// Using ES5 (CommonJS) - index.js
class Helpers {
  static isNull(val) {
    return val === null;
  }

  static isUndefined(val) {
    return val === undefined;
  }

  static isNullOrUndefined(val) {
    return this.isNull(val) || this.isUndefined(val);
  }
}


module.exports = Helpers;
```
_Using ES6 Modules_
```js
// Using ES6 Modules - helpers.js
class Helpers {
  static isNull(val) {
    return val === null;
  }

  static isUndefined(val) {
    return val === undefined;
  }

  static isNullOrUndefined(val) {
    return this.isNull(val) || this.isUndefined(val);
  }
}

export default Helpers
```

__Importing a Single Functionality from another File__

_Using ES5 (CommonJS)_
```js
// Using ES5 (CommonJS) - index.js
const Helpers = require('./helpers.js'); 
console.log(Helpers.isNull(null));
```
_Using ES6 Modules_
```js
import Helpers from '.helpers.js'
console.log(Helpers.isNull(null));
```

This is the basics of using __ES6 Modules__. I won't explain all about Modules because it's a broad topic and my Post is now really long.


###48. What is the <code>Set</code> object and how does it work?

[&uarr;](#the-questions "Back To Questions") The __Set__ object is an __ES6__ feature that lets you store unique values, __primitives__ or __object references__. A value in a Set can only occur __once__. It checks if a value exists in the set object using the __SameValueZero__  algorithm.


We can make <code>Set</code> instance using <code>Set</code> constructor and we can optionally pass an <code>Iterable</code> as the initial value.
```js

const set1 = new Set();
const set2 = new Set(["a","b","c","d","d","e"]);

```
We can add a new value into the <code>Set</code> instance using the <code>add</code> method and since the <code>add</code> returns the <code>Set</code> object we can chain <code>add</code> calls. If a value already exists in <code>Set</code> object it will not be added again.
```js

set2.add("f");
set2.add("g").add("h").add("i").add("j").add("k").add("k");
// the last "k" will not be added to the set object because it already exists

```

We can remove a value from the <code>Set</code> instance using the <code>delete</code> method, this method returns a <code>boolean</code> indicating <code>true</code> if a value exists in the <code>Set</code> object and <code>false</code> indicating that value does not exist.

```js

set2.delete("k") // returns true because "k" exists in the set object
set2.delete("z") // returns false because "z" does not exists in the set object

```

We can check if a specific value exists in the <code>Set</code> instance using the <code>has</code> method.
```js

set2.has("a") // returns true because "a" exists in the set object
set2.has("z") // returns false because "z" does not exists in the set object

```
We can get the length of the <code>Set</code> instance using the <code>size</code> property.
```js

set2.size // returns 10

```
We can delete or remove all the elements in the <code>Set</code> instance using the <code>clear</code>.
```js

set2.clear(); // clears the set data

```
We can use the <code>Set</code> object for removing duplicate elements in an array.
```js

const numbers = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 5];
const uniqueNums = [...new Set(numbers)]; // has a value of [1,2,3,4,5,6,7,8]

```

###49. What is a Callback function?

[&uarr;](#the-questions "Back To Questions") A __Callback__ function is a function that is gonna get called at a later point in time.

```js
const btnAdd = document.getElementById('btnAdd');

btnAdd.addEventListener('click', function clickCallback(e) {
    // do something useless
});
```
In this example, we wait for the <code>click event</code> in the element with an id of __btnAdd__, if it is <code>clicked</code>, the <code>clickCallback</code> function is executed. A __Callback__ function adds some functionality to some data or event. The <code>reduce</code>, <code>filter</code> and <code>map</code> methods in __Array__ expects a callback as a parameter. A good analogy for a callback is when you call someone and if they don't answer you leave a message and you expect them to __callback__. The act of calling someone or leaving a __message__ is the __event or data__ and the __callback__ is the __action that you expect to occur later__.

###50. What are __Promises__?
[&uarr;](#the-questions "Back To Questions") __Promises__ are one way in handling asynchronous operations in __JavaScript__. It represents the value of an asynchronous operation. __Promises__ was made to solve the problem of doing and dealing with async code before promises we're using callbacks.
```js
fs.readFile('somefile.txt', function (e, data) {
  if (e) {
    console.log(e);
  }
  console.log(data);
});
```
The problem with this approach if we have another async operation inside the callback and another. We will have a code that is messy and unreadable. This code is called __Callback Hell__.
```js
//Callback Hell yucksss
fs.readFile('somefile.txt', function (e, data) {
  //your code here
  fs.readdir('directory', function (e, files) {
    //your code here
    fs.mkdir('directory', function (e) {
      //your code here
    })
  })
})
```
If we use promises in this code it will be more readable and easy to understand and easy to maintain.
```js
promReadFile('file/path')
  .then(data => {
    return promReaddir('directory');
  })
  .then(data => {
    return promMkdir('directory');
  })
  .catch(e => {
    console.log(e);
  })
```
Promises have 3 different states.

__Pending__ - The initial state of a promise. The promise's outcome has not yet been known because the operation has not been completed yet.

__Fulfilled__ - The async operation is completed and successful with the resulting value. 

__Rejected__ -  The async operation has failed and has a _reason_ on why it failed.

__Settled__ - If the promise has been either __Fulfilled__ or __Rejected__.

The __Promise__ constructor has two parameters which are functions <code>resolve</code> and <code>reject</code> respectively.
If the async operation has been completed without errors call the <code>resolve</code> function to resolve the promise or if an error occurred 
call the <code>reject</code> function and pass the error or reason to it.
We can access the result of the fulfilled promise using the <code>.then</code>
method and we catch errors in the <code>.catch</code> method. We chain multiple async promise operations in the <code>.then</code> method because the <code>.then</code> method returns a __Promise__ just like the example in the imag e above.
```js
const myPromiseAsync = (...args) => {
  return new Promise((resolve, reject) => {
    doSomeAsync(...args, (error, data) => {
      if (error) {
        reject(error);
      } else {
        resolve(data);
      }
    })
  })
}

myPromiseAsync()
  .then(result => {
    console.log(result);
  })
  .catch(reason => {
    console.log(reason);
  })
```

We can make a helper func that converts an async operation with a callback to promise. It works like the __promisify__  utility function from the node core module <code>util</code>. 
 
```js
const toPromise = (asyncFuncWithCallback) => {
  return (...args) => {
    return new Promise((res, rej) => {
      asyncFuncWithCallback(...args, (e, result) => {
        return e ? rej(e) : res(result);
      });
    });
  }
}

const promReadFile = toPromise(fs.readFile);

promReadFile('file/path')
  .then((data) => {
    console.log(data);
  })
  .catch(e => console.log(e));
```

###51. What is _async/await_ and How does it work?
[&uarr;](#the-questions "Back To Questions") _async/await_ is the new way of writing asynchronous or non-blocking code in __JavaScript's__. It is built on top of __Promises__. It makes writing asynchronous code more readable and cleaner than 
__[Promises](#50-what-are-promises)__ and __[Callbacks](#49-what-is-a-callback-function)__. But you must learn the basics of __Promises__ before using this feature because as I said earlier it is built on top of __Promises__ which means is still uses __Promises__ under the hood.

Using Promises.
```js
function callApi() {
  return fetch("url/to/api/endpoint")
    .then(resp => resp.json())
    .then(data => {
      //do something with "data"
    }).catch(err => {
      //do something with "err"
    });
}

```

Using Async/Await.

__Note__: We're using the old _try/catch_ statement to __catch__ any errors that happened in any of those async operations inside the _try_ statement.

```js
async function callApi() {
  try {
    const resp = await fetch("url/to/api/endpoint");
    const data = await resp.json();
    //do something with "data"
  } catch (e) {
    //do something with "err"
  }
}
```

__Note__: The _async_ keyword before the function declaration makes the function return _implicitly_ a __Promise__.

```js
const giveMeOne = async () => 1;

giveMeOne()
  .then((num) => {
    console.log(num); // logs 1
  });
```

__Note__: The _await_ keyword can __only__ be used inside an __async function__. Using _await_ keyword in any other function which is not an __async function__ will throw an error. The _await_ keyword __awaits__ the right-hand side expression (presumably a __Promise__) to return before executing the next line of code. 

```js
const giveMeOne = async () => 1;

function getOne() {
  try {
    const num = await giveMeOne();
    console.log(num);
  } catch (e) {
    console.log(e);
  }
}

//Throws a Compile-Time Error = Uncaught SyntaxError: await is only valid in an async function

async function getTwo() {
  try {
    const num1 = await giveMeOne(); //finishes this async operation first before going to
    const num2 = await giveMeOne(); //this line
    return num1 + num2;
  } catch (e) {
    console.log(e);
  }
}

await getTwo(); // returns 2
```

###52. What's the difference between __Spread operator__ and __Rest operator__?

[&uarr;](#the-questions "Back To Questions") The __Spread operator__ and __Rest paremeters__ have the same operator <code>...</code> the difference between is that the __Spread operator__ we __give__ or __spread__ individual data of an array to another data while the __Rest parameters__ is used in a function or an array to __get__ all the arguments or values and put them in an array or __extract__ some pieces of them.

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

const nums = [5, 6];
const sum = add(...nums);
console.log(sum);

```
In this example, we're using the __Spread Operator__ when we call the <code>add</code> function we are __spreading__ the <code>nums</code> array. So the value of parameter <code>a</code> will be __5__ and the value of <code>b</code> will be __6__. So the sum will be __11__.


```js
function add(...rest) {
  return rest.reduce((total,current) => total + current);
};

console.log(add(1, 2)); // logs 3
console.log(add(1, 2, 3, 4, 5)); // logs 15
```
In this example, we have a function <code>add</code> that accepts any number of arguments and adds them all and return the total.

```js
const [first, ...others] = [1, 2, 3, 4, 5];
console.log(first); //logs 1
console.log(others); //logs [2,3,4,5]
```
In this another example, we are using the __Rest operator__ to extract all the remaining array values and put them in array <code>others</code> except the first item.


###53. What are __Default Parameters__?
[&uarr;](#the-questions "Back To Questions") __Default Parameters__ is a new way of defining default variables in __JavaScript__ it is available in the __ES6__ or __ECMAScript 2015__ Version.
```js
//ES5 Version
function add(a,b){
  a = a || 0;
  b = b || 0;
  return a + b;
}

//ES6 Version
function add(a = 0, b = 0){
  return a + b;
}
//If we don't pass any argument for 'a' or 'b' then 
// it's gonna use the "default parameter" value which is 0
add(1); // returns 1 
```

We can also use __[Destructuring](#46-what-is-object-destructuring)__ in __Default Paremeters__.
```js
function getFirst([first, ...rest] = [0, 1]) {
  return first;
}

getFirst();  // returns 0
getFirst([10,20,30]);  // returns 10

function getArr({ nums } = { nums: [1, 2, 3, 4] }){
    return nums;
}

getArr(); // returns [1, 2, 3, 4]
getArr({nums:[5,4,3,2,1]}); // returns [5,4,3,2,1]
```
We can also use the parameters defined first to the parameters defined after them.
```js
function doSomethingWithValue(value = "Hello World", callback = () => { console.log(value) }) {
  callback();
}
doSomethingWithValue(); //logs "Hello World"
```
###54. What are __Wrapper Objects__?
[&uarr;](#the-questions "Back To Questions") __Primitive Values__ like <code>string</code>,<code>number</code> and <code>boolean</code> with the exception of <code>null</code> and <code>undefined</code> have properties and methods even though they are not <code>objects</code>. 

```js
let name = "marko";

console.log(typeof name); // logs  "string"
console.log(name.toUpperCase()); // logs  "MARKO"
```
<code>name</code> is a <code>primitive string</code> value that has no properties and methods but in this example we are calling a <code>toUpperCase()</code> method which does not throw an error but returns <code>MARKO</code>.

The reason for this is that the <code>primitive</code> value is temporarily converted or _coerce_ to an <code>object</code> so the <code>name</code> variable behaves like an <code>object</code>. Every <code>primitive</code> except <code>null</code> and <code>undefined</code> have __Wrapper Objects__. The Wrapper Objects are <code>String</code>,<code>Number</code>,<code>Boolean</code>,<code>Symbol</code> and <code>BigInt</code>. In this case, the <code>name.toUpperCase()</code> invocation, behind the scenes it looks like this.
```js

console.log(new String(name).toUpperCase()); // logs  "MARKO"

```
The newly created object is immediately discarded after we finished accessing a property or calling a method.


###55. What is the difference between __Implicit__ and __Explicit__ Coercion?

[&uarr;](#the-questions "Back To Questions") __Implicit__ Coercion is a way of converting values to another type without us programmer doing it directly or by hand.

Suppose we have an example below.
```js
console.log(1 + '6');
console.log(false + true);
console.log(6 * '2');

```
The __first__ <code>console.log</code> statement logs <code>16</code>. In other languages this would throw a compile time error but in __JavaScript__ the <code>1</code> is converted to a <code>string</code> then concatenated with the <code>+</code> operator. We did not do anything, yet it was converted automatically by __JavaScript__ for us. 
The __second__ <code>console.log</code> statement logs <code>1</code>, it converts the <code>false</code> to a <code>boolean</code> which will result to a <code>0</code> and the <code>true</code> will be <code>1</code> hence the result is <code>1</code>. 
The __third__ <code>console.log</code> statement logs <code>12</code>, it converts the <code>'2'</code> to a <code>number</code> before multiplying <code>6 * 2</code> hence the result <code>12</code>.
[JavaScript Coercion Rules](https://delapouite.com/ramblings/javascript-coercion-rules.html)

While __Explicit__ Coercion is the way of converting values to another type where we (_programmers_) __explicitly__ do it.
```js
console.log(1 + parseInt('6'));
```
In this example, we use the <code>parseInt</code> function to convert the <code>'6'</code> to a <code>number</code> then adding the <code>1</code> and <code>6</code> using the <code>+</code> operator.

###56. What is <code>NaN</code>? and How to check if a value is <code>NaN</code>?

[&uarr;](#the-questions "Back To Questions") <code>NaN</code> means __"Not A Number"__ is a value in __JavaScript__ that is a result in converting or performing an operation to a number to non-number value hence results to <code>NaN</code>.
```js
let a;

console.log(parseInt('abc'));
console.log(parseInt(null));
console.log(parseInt(undefined));
console.log(parseInt(++a));
console.log(parseInt({} * 10));
console.log(parseInt('abc' - 2));
console.log(parseInt(0 / 0));
console.log(parseInt('10a' * 10));

```
__JavaScript__ has a built-in method <code>isNaN</code> that tests if value is <code>isNaN</code> value. But this function has a weird behaviour.
```js
console.log(isNaN()); //logs true
console.log(isNaN(undefined)); //logs true
console.log(isNaN({})); //logs true
console.log(isNaN(String('a'))); //logs true
console.log(isNaN(() => { })); //logs true
```
All these <code>console.log</code> statements return <code>true</code> even though those values we pass are not <code>NaN</code>.


In __ES6__ or __ECMAScript 2015__, it is recommended that we use <code>Number.isNaN</code> method because it really checks the value if it really is <code>NaN</code> or we can make our own helper function that check for this problem because in __JavaScript__ <code>NaN</code> is the only value that is not equal to itself.
```js
function checkIfNaN(value) {
  return value !== value;
}
```
###57. How to check if a value is an __Array__?

[&uarr;](#the-questions "Back To Questions") We can check if a value is an __Array__ by using the <code>Array.isArray</code> method available from the __Array__ global object. It returns true when the parameter pass to it is an __Array__ otherwise false.

```js
console.log(Array.isArray(5));  //logs false
console.log(Array.isArray("")); //logs false
console.log(Array.isArray()); //logs false
console.log(Array.isArray(null)); //logs false
console.log(Array.isArray({ length: 5 })); //logs false

console.log(Array.isArray([])); //logs true
```
If your environment does not support this method you can use the polyfill implementation.
```js
   function isArray(value){
     return Object.prototype.toString.call(value) === "[object Array]"
   }
```
###58. How to check if a number is even without using the <code>%</code> or modulo operator?

[&uarr;](#the-questions "Back To Questions") We can use the __bitwise AND__<code>&</code> operator for this problem. The <code>&</code> operates on its operand and treats them as binary values and performs the __AND__ operation.

```js
function isEven(num) {
  if (num & 1) {
    return false;
  } else {
    return true;
  }
};
```
<code>0</code> in binary is __000__.
<code>1</code> in binary is __001__.
<code>2</code> in binary is __010__.
<code>3</code> in binary is __011__.
<code>4</code> in binary is __100__.
<code>5</code> in binary is __101__.
<code>6</code> in binary is __110__.
<code>7</code> in binary is __111__.
and so on...


|<code>a</code> |<code>b</code> |<code>a & b</code>|
| ------------- |:-------------:| ----------------:|
| 0             | 0             |        0         |
| 0             | 1             |        0         |
| 1             | 0             |        0         |
| 1             | 1             |        1         |

So when we <code>console.log</code> this expression <code>5 & 1</code> it returns <code>1</code>. Ok, first the <code>&</code> operator converts both numbers to binary so <code>5</code> turns to __101__ and <code>1</code> turns to __001__. 
Then it compares every bit __(0's and 1's)__ using the bitwise __AND__ operator. __101__ <code>&</code> __001__. As we can see from the table the result can be only <code>1</code> if <code>a</code> __AND__ <code>b</code> are <code>1</code>.

| <code>101 & 001</code>     |
| ------------- |
| 101           |
| 001           | 
| __001__       |

* So first we compare the left most bit <code>1</code><code>&</code><code>0</code> the result should be <code>0</code>.
* Then we compare the middle bit <code>0</code><code>&</code><code>0</code> the result should be <code>0</code>.
* Then we compare the last bit <code>1</code><code>&</code><code>1</code> the result should be <code>1</code>.
* Then the binary result <code>001</code> will be converted to a decimal number which will be <code>1</code>.


If we <code>console.log</code> this expression <code>4 & 1</code> it will return <code>0</code>. Knowing the last bit of <code>4</code> is <code>0</code> and <code>0 & 1</code> will be <code>0</code>. If you have a hard time understand this we could use a __recursive__ function to solve this problem.
```js
function isEven(num) {
  if (num < 0 || num === 1) return false;
  if (num == 0) return true;
  return isEven(num - 2);
}
```
###59. How to check if a certain property exists in an object?

[&uarr;](#the-questions "Back To Questions") There are three possible ways to check if a property exists in an object.

First , using the <code>in</code> operator. The syntax for using the <code>in</code> operator is like this <code>propertyname in object</code>. It returns <code>true</code> if the property exists otherwise it returns <code>false</code>.

```js
const o = { 
  "prop" : "bwahahah",
  "prop2" : "hweasa"
};

console.log("prop" in o); //This logs true indicating the property "prop" is in "o" object
console.log("prop1" in o); //This logs false indicating the property "prop" is not in  "o" object
```

Second, using the <code>hasOwnProperty</code> method in objects. This method is available on all objects in JavaScript. It returns <code>true</code> if the property exists otherwise it returns <code>false</code>.

```js
//Still using the o object in the first example.
console.log(o.hasOwnProperty("prop2")); // This logs true
console.log(o.hasOwnProperty("prop1")); // This logs false
```

Third, using the bracket notation <code>obj["prop"]</code>. If the property exists it returns the value of that property otherwise this will return <code>undefined</code>.

```js
//Still using the o object in the first example.
console.log(o["prop"]); // This logs "bwahahah"
console.log(o["prop1"]); // This logs undefined
```

###60. What is __AJAX__?
[&uarr;](#the-questions "Back To Questions") __AJAX__ stands for __Asynchronous JavaScript and XML__. It is a group of related technologies used to display data asynchronously. What this means is that we can send data to the server and get data from the server without reloading the web page.

Technologies use for __AJAX__.

* __HTML__ - web page structure
* __CSS__  - the styling for the webpage
* __JavaScript__ - the behaviour of the webpage and updates to the __DOM__
* __XMLHttpRequest API__ - used to send and retrieve data from the server
* __PHP,Python,Nodejs__ - Some Server-Side language



###61. What are the ways of making objects in JavaScript?

[&uarr;](#the-questions "Back To Questions") Using __Object Literal__.
```js
  const o = {
   name: "Mark",
   greeting() {
      return `Hi, I'm ${this.name}`;
   }
  };

  o.greeting(); //returns "Hi, I'm Mark"
```

Using __Constructor Functions__.
```js
function Person(name) {
   this.name = name;
}

Person.prototype.greeting = function () {
   return `Hi, I'm ${this.name}`;
}

const mark = new Person("Mark");

mark.greeting(); //returns "Hi, I'm Mark"
```

Using __Object.create__ method.
```js
const n = {
   greeting() {
      return `Hi, I'm ${this.name}`;
   }
};

const o = Object.create(n); // sets the prototype of "o" to be "n"

o.name = "Mark";

console.log(o.greeting()); // logs "Hi, I'm Mark"


```


###62. What's the difference between <code>Object.seal</code> and <code>Object.freeze</code> methods?

[&uarr;](#the-questions "Back To Questions") The difference between these two methods is that when we use the <code>Object.freeze</code> method to an object, that object's properties are immutable meaning we can't change or edit the values of those properties. While in the <code>Object.seal</code> method we can change those existing properties but we cannot add new properties to the object.

###63. What's the difference between the <code>in</code> operator and the <code>hasOwnProperty</code>  method in objects?

[&uarr;](#the-questions "Back To Questions") As you know both of these features check if a property exists in an object. It will return <code>true</code if the property exists otherwise it returns <code>false</code>. The difference between them is that the <code>in</code> operator also checks the objects' __Prototype Chain__ if the property was not found in the current object while the  <code>hasOwnProperty</code> method just checks if the property exists in the current object ignoring the __Prototype Chain__.

```js
// We'll still use the object in the previous question.
console.log("prop" in o); // This logs true;
console.log("toString" in o); // This logs true, the toString method is available in this object's prototype which is the Object.prototype


console.log(o.hasOwnProperty("prop")); // This logs true
console.log(o.hasOwnProperty("toString")); // This logs false, does not check the object's prototype
```

###64. What are the ways to deal with __Asynchronous Code__ in JavasScript?
[&uarr;](#the-questions "Back To Questions")
* [Callbacks](#49-what-is-a-callback-function)
* [Promises](#50-what-are-promises)
* [async/await](#51-what-is-asyncawait-and-how-does-it-work)
* Libraries like [async.js](https://caolan.github.io/async/v3/), [bluebird](http://bluebirdjs.com/docs/getting-started.html), [q](http://documentup.com/kriskowal/q/), [co](https://www.npmjs.com/package/co)


###65. What's the difference between a __function expression__ and __function declaration__?

[&uarr;](#the-questions "Back To Questions") Suppose we have an example below.
```js
hoistedFunc();
notHoistedFunc();

function hoistedFunc(){
  console.log("I am hoisted");
}

var notHoistedFunc = function(){
  console.log("I will not be hoisted!");
}
```
The <code>notHoistedFunc</code> call throws an error while the <code>hoistedFunc</code> call does not because the <code>hoistedFunc</code> is _hoisted_ while the <code>notHoistedFunc</code> is not. 
Read __Hoisting__ [here](#18-what-is-hoisting).



###66. How many ways can a function be _invoked_?

[&uarr;](#the-questions "Back To Questions") There are 4 ways that a function can be _invoked_ in __JavaScript__. The __invocation__ determines the value of <code>[this](#24-whats-the-value-of-this-in-javascript)</code> or the "owner" object of that function.


* __Invocation as a function__ - If a function isn't invoked as a method, as a constructor or with the <code>apply</code>, <code>call</code> methods then it is __invoked as a function__. The "owner" object of this function will be the <code>window</code> object.

```js
  //Global Scope
 
  function add(a,b){
    console.log(this);
    return a + b;
  }  

  add(1,5); // logs the "window" object and returns 6

  const o = {
    method(callback){
      callback();
    }
  }
  
  o.method(function (){
      console.log(this); // logs the "window" object
  });
```


* __Invocation as a method__ - If a property of an object has a value of a function we call it a __method__. When that __method__ is _invoked_ the <code>this</code> value of that method will be that object.
```js
   const details = {
     name : "Marko",
     getName(){
       return this.name;
     }
   }
   
   details.getName(); // returns Marko
   // the "this" value inside "getName" method will be the "details" object 
```
* __Invocation as a constructor__ - If a function was _invoked_ with a <code>[new](#70-what-does-the-new-keyword-do)</code> keyword before it then it's called a <code>function constructor</code>. An empty object will be created and <code>this</code> will point to that object.
```js
function Employee(name, position, yearHired) {
  // creates an empty object {}
  // then assigns the empty object to the "this" keyword
  // this = {};
  this.name = name;
  this.position = position;
  this.yearHired = yearHired;
  // inherits from Employee.prototype
  // returns the "this" value implicitly if no 
  // explicit return statement is specified
};

const emp = new Employee("Marko Polo", "Software Developer", 2017);

```
* __Invocation with the <code>[apply](#27-what-is-the-use-functionprototypeapply-method)</code> and <code>[call](#26-what-is-the-use-functionprototypecall-method)</code> methods__ - If we want to _explicitly_ specify the <code>this</code> value or the "owner" object of a function we can use these methods. These methods are available for all functions.

```js
const obj1 = {
 result:0
};

const obj2 = {
 result:0
};


function reduceAdd(){
   let result = 0;
   for(let i = 0, len = arguments.length; i < len; i++){
     result += arguments[i];
   }
   this.result = result;
}


reduceAdd.apply(obj1, [1, 2, 3, 4, 5]);  //the "this" object inside the "reduceAdd" function will be "obj1"
reduceAdd.call(obj2, 1, 2, 3, 4, 5); //the "this" object inside the "reduceAdd" function will be "obj2"
```

###67. What is _memoization_ and what's the use it?

[&uarr;](#the-questions "Back To Questions") _memoization_ is a process of building a function that is capable of __remembering__ it's previously computed results or values. 
The use of making a _memoization_ function is that we avoid the computation of that function if it was already performed in the last calculations with the same arguments. This saves time but has a downside that we will consume more memory for saving the previous results.



###68. Implement a memoization helper function.
[&uarr;](#the-questions "Back To Questions") 
```js
function memoize(fn) {
  const cache = {};
  return function (param) {
    if (cache[param]) {
      console.log('cached');
      return cache[param];
    } else {
      let result = fn(param);
      cache[param] = result;
      console.log(`not cached`);
      return result;
    }
  }
}

const toUpper = (str ="")=> str.toUpperCase();

const toUpperMemoized = memoize(toUpper);

toUpperMemoized("abcdef");
toUpperMemoized("abcdef");
```
This _memoize_ helper function only works on a function that accepts one _argument_. We need to make a _memoize_ helper function that accepts multiple _arguments_.
```js
const slice = Array.prototype.slice;
function memoize(fn) {
  const cache = {};
  return (...args) => {
    const params = slice.call(args);
    console.log(params);
    if (cache[params]) {
      console.log('cached');
      return cache[params];
    } else {
      let result = fn(...args);
      cache[params] = result;
      console.log(`not cached`);
      return result;
    }
  }
}
const makeFullName = (fName, lName) => `${fName} ${lName}`;
const reduceAdd = (numbers, startingValue = 0) => numbers.reduce((total, cur) => total + cur, startingValue);

const memoizedMakeFullName = memoize(makeFullName);
const memoizedReduceAdd = memoize(reduceAdd);

memoizedMakeFullName("Marko", "Polo");
memoizedMakeFullName("Marko", "Polo");

memoizedReduceAdd([1, 2, 3, 4, 5], 5);
memoizedReduceAdd([1, 2, 3, 4, 5], 5);

```
###69. Why does <code>typeof null</code> return <code>object</code>? How to check if a value is <code>null</code>?

[&uarr;](#the-questions "Back To Questions") <code>[typeof null == 'object'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#null)</code> will always return <code>true</code> because this was the implementation of <code>null</code> since the birth of __JavaScript__. A fix was proposed to change <code>typeof null == 'object'</code> to <code>typeof null == 'null' </code> but was [rejected](https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null) because it will lead to more bugs to existing projects and softwares.

We can use the <code>===</code> or __strict equality__ operator to check if a value is <code>null</code>.
```js
  function isNull(value){
    return value === null;
  }
```

###70. What does the <code>new</code> keyword do?
[&uarr;](#the-questions "Back To Questions") The <code>new</code> keyword is used with _constructor_ functions to make objects 
in __JavaScript__.

Suppose we have an example code below.

```js
function Employee(name, position, yearHired) {
  this.name = name;
  this.position = position;
  this.yearHired = yearHired;
};

const emp = new Employee("Marko Polo", "Software Developer", 2017);

```

The <code>new</code> keyword does 4 things.
* Creates an empty object.
* Assigns that empty object to the <code>this</code> value.
* The function will _inherit_ from __functionName.[prototype](#25-what-is-the-prototype-of-an-object)__.
* Returns the <code>this</code> if no Explicit <code>return</code> statement is used.


In the above image, it will first create an empty object <code>{}</code> then 
it will the <code>this</code> value to that empty object <code>this = {}</code> and add properties to that <code>this</code> object. Because we don't have a explicit <code>return</code> statement it automatically returns the <code>this</code> for us.



##Thanks guys for reading this post.
## Have a Nice Day :smiley: and a Happy New Year :fireworks::fireworks::fireworks:.