9 Common JavaScript Interview Questions You Might Not Know The Answer For.
Tags: javascript, webdev, programming, beginners
Published: 2023-01-14 03:32:41

Whether you like them or not, tricky questions are still asked by interviewers in the wild.

The reason is, these questions can tell a lot about your core understanding of the language, and therefore if you are a fit for the job. 

Common concepts addressed in these questions include:
- Hoisting
- Closure
- Scope
- Value vs Reference type
- Prototype inheritance

Today we will kill two birds with one stone.

Prepare to ace your next interview and brush up on the core concepts, at once.


## Why typeof `f` is undefined?

```javascript
var y = 1;
if (function f() {}) {
  y += typeof f;
}

console.log(y); // 1undefined
```

**Explanation**
* The condition statement `if(function f() {})` returns `function f() {}` which is truthy, so the code executes inside the if statement.
* `typeof f` returns `undefined` because the function `f(){}` was never declared outside the `if` statement, so it doesn't "exist" outside the `if` brackets `if (f(){}) { It doesn't exist here }`

This is how we would "fix" this code snippet:
```javascript
var y = 1;

function f() {}; //declare function outside if brackets

if (f) { //f exists so we enter the if block
  y += typeof f; //here typeof f is function
}

console.log(y); // 1function
```

## Write an example of closure

```javascript
function createFunction(msg) {
    return function(name) {
        return msg + name;
    }
}

let myFunc = createFunction("Hey ");
console.log(myFunc("Dude")); // Hey Dude
```
**Explanation**
* The first function (createFunction) returns an anonymous function
* The anonymous function returns the parameter `msg` from the outer function(createFunction()) + `name` from itself.

When we declare the variable `javascript let myFunc = createFunction("Hey ")` the variable `myFunc` holds a reference to the anonymous function returned by the outer 

What is interesting is that when you call `javascript myFunc("Dude")` (passing just the 'name' parameter) it still "remembers" the value of `msg` that was passed in when `createFunction()` was executed.

The ability to access variables from the outer 'scope' where the function was created is one of the definitions of closure.

Learn more about closures [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)


## Write a multiply() function that can be called like multiply(2)(5)(10) and returns 100

This is similar to the example above, the difference being that we are retuning an additional function and invoking all of them straight away(no using variables for holding references)

```javascript
function multiply(x) {
    return function(y){
        return function(z) {
          return x*y*z;
        };
    }
}

multiply(2)(5)(10) //100
``` 

By invoking multiply like ```javascript multiply(2)(5)(10)``` We are invoking the returned functions one after the other.

We could use intermediate variables to make it clearer. Let's have a look:

```javascript
let func1 = multiply(2); // x is 2
console.log(func1) // function(y) { return function(z) { return x*y*z } }

let func2 = func1(5); // y is 5
console.log(func1) // function(z) { return x*y*z }

func2(10); // z is 10
// finally has all 3 values and returns their product.
```

Learn more aboute Nested Functions[here](https://www.geeksforgeeks.org/javascript-nested-functions/)


## `delete` operator on a local variable

**What would be the output of the following code?**

```javascript
let output = (function(x) {
    delete x;
    return x;
})(0);
```

*The delete operator is meant to be used to delete properties of objects, and not on value types(number in this case).

This would work:
```javascript
let obj = { name: 'Gus', age: 32 }
delete obj.age;

console.log(obj) // { name: 'Gus' }
```

## `delete` operator on Object

```javascript 
const Person = {
    name: 'Gus',
    age: 32,
}

const person1 = Object.create(Person);
delete person1.age

console.log(person1.age); // 32
```

* `person1` is created with its prototype set to the `Person` object. 
* When the instance `person1` has it's `age` property deleted, we can still access the `age` property of the prototype object(Person)
* That is why it seems like it didn't work.

This is a big topic, you can learn more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)


## `delete` operator on Array

**What would be the result of logging arr.length ?**

```javascript
  let arr = ["a", "b", "c", "d"];
  delete arr[2];

  arr.length // 4
```

* When used on arrays, the delete operator sets the delete element to 'empty' but does not remove it from the array, not changing the length of the array.

## What will be the value of both console.log's?

```javascript
var favouriteAnime = "Dragon Ball";
(function() {
    console.log(favouriteAnime);
    var favouriteAnime = "Naruto";
    console.log(favouriteAnime);
})();

// undefined 
// Naruto
```
Here is how the compiler interpreted this code:

```javascript
var favouriteAnime; // declared and initialized with undefined
(function() {
    console.log(favouriteAnime);
    var favouriteAnime = "Naruto";
    console.log(favouriteAnime);
})();

favouriteAnime = "Dragon Ball";

// undefined 
// Naruto
```

A few things to keep in mind when declaring JavaScript functions and variables.

* Variable assignment(myVar = 5) takes precedence over function declaration(function func(){})
* Function declarations(function func(){}) take precedence over variable declarations(var myVar;) *let or const
* Function declarations(function func(){}) are hoisted over variable declarations(var myVar;) but not over variable assignments(myVar = 5;).

As a best practice, you should always declare your functions before invoking them.

Learn more about hoisting [here](https://www.digitalocean.com/community/tutorials/understanding-hoisting-in-javascript)

## How would you check if a number is an integer?

The easiest way to check if a numner is a decimal ir integer is by using the built-in `Number.isInteger()`

```javascript
console.log(Number.isInteger(4)); // true
console.log(Number.isInteger(12.2)); // false
console.log(Number.isInteger(0.3)); // false
```

Another way is to see if there is a remainder left when you divide by 1.

```javascript
function isInt(num) {
  return num % 1 === 0;
}

console.log(isInt(4)); // true
console.log(isInt(12.2)); // false
console.log(isInt(0.3)); // false
```

Note: There is a limit to JavaScript precision when handling floating points. If you check `Number.isInteger(1.0000000000000001)` will return `true`. You can learn more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger)


## Conclusion

Remember to hit f12 and try out the examples for yourself.

This tiny action will help you remember what you learned for much longer.

This is a recap of what we have seen today:

* Why typeof `f` is undefined?
* Write an example of closure
* Write a multiply() function that can be called like multiply(2)(5)(10) and returns 100
* Delete operator on a local variable
* Delete operator on Object
* Delete operator on Array
* What will be the value of both console.log's?
* How would you check if a number is an integer?


Thanks for reading!

If you like this article:

*Leave a comment below(You can just say hi!)
*Follow me on Twitter [@theguspear](https://twitter.com/theguspear).

Catch you later my dude,

Gus.