JavaScript Interview Questions 2
Tags: javascript, webdev, programming, career
Published: 2022-02-16 14:08:18

On the previous iteration of the series I talked about 5 commonly asked questions in JavaScript or JavaScript frameworks and libraries interviews like MEAN, MERN Or VUEjs.
In this blog I'll continue to answer a few more questions that I have been asked many times as well as accounted its occurrence from my friends and colleagues. 

> TOC:
1. What is Hoisting?
2. What are Closures?
3. What is a promise?
4. What is a callback function and why we need it?
5. What is a thunk function?

So let's get started!
## What is Hoisting?
You can find this anywhere but I say it with a bit of flair in my interviews. So the answer is that, imagine it as a putting your copy on the top of the stack in your school so the teacher checks yours first. Basically interpreter does the same with the variable and function **declarations**. It takes them to the top of their scope before the code execution begins. 
One thing to note is that only declarations are moved to the top and not initializations. 

```javascript
// Returns 'undefined' from hoisted let and var declarations of the strings
console.log(obiwan, grevious)

let obiwan = "Hello There!"
var grevious
grevious =  "General Kenobi!"

//Hello There! General Kenobi!
console.log(obiwan, grevious) 
```
![Kenobi!](https://media.giphy.com/media/8JTFsZmnTR1Rs1JFVP/giphy.gif)
## What are Closures?
When we have a function within a function, the inner function has access to the variables that are declared in the outer function. Closures have 3 scopes: Their own function scope. Function scope of the outer function and Global scope.
As per the below code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.
```javascript
function Name(name){
  var greetingInfo = function(message){
   console.log(message+' '+name);
  }
return greetingInfo;
}
var myFunction = Name('Jake');
myFunction('How you doing'); //Output: How you doing John
myFunction('Up Top'); //output: Up Top Jake
```
![Up Top Jakey](https://carrietippen.files.wordpress.com/2020/08/jake-and-charles-feature.jpg)

## What is a promise?
When you go to a person who borrowed ..nah just kidding. Think of this, you go to your friend and tell him "Let's go watch some movie" and he replies "I promise we'll go tomorrow". 
Yes, that's exactly the promise in question. You're not sure if you will go or not tomorrow but you don't have to stop and wait the whole time right?
Similarly, in JavaScript a Promise is usually used to handle async operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.
A Promise may return any of the three states, fulfilled, rejected or pending.
The action flow of a promise is shown below:
![Promise](https://github.com/sudheerj/javascript-interview-questions/raw/master/images/promises.png)

## What is a callback function and why we need it?
A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action.
Don't get it confused with closures. I once did it and was really embarrassed after the interview was over and realized why the interviewer was smiling when answering. 

```javascript
function callbackFunction(ipstr) {
  console.log(ipstr, "Yeah! I Know..");
}

function outerFunction(callback) {
  let cap = "I can do this all day";
  callback(cap);
}

outerFunction(callbackFunction);
```
![Yah, I know, I know](https://c.tenor.com/fBgaXKw2wmoAAAAC/captain-america-endgame.gif)

Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below.

```javascript
async1(function(){
    async2(function(){
        async3(function(){
            async4(function(){
                ....
            });
        });
    });
});
```
## What's a thunk function?
Thunk acts similar to webAPI setTimeout. It delays the evaluation of the value. 
It doesn’t take any arguments but gives the value whenever you invoke the thunk i.e., We use it to execute in the near future rather than current moment. We can use synchronously as well as asynchronously. Let's take a synchronous example:
```javascript
const add = (x,y) => x * y;

const thunk = () => multiply(2,3);

thunk() // 6
```
And a asynchronous application as well. Here, The getData function won't be called immediately but will be invoked only when the data is available from the API endpoint.
```javascript
function fetchData(fn){
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => fn(json))
}

const asyncThunk = function (){
   return fetchData(function getData(data){
      console.log(data)
  })
}

asyncThunk()
```
Do let me know your thoughts and follow my [Twitter](https://twitter.com/Neo_kaizerr) and [LinkedIn](https://www.linkedin.com/in/sobhandash/).