February 17, 2019

## Answering Coding Questions: Part 1

This is the first entry of a series where I will be answering common coding interview questions. My goal is to illustrate my understanding of the questions and also help explain the answers to beginning developers that might be struggling.

### What is the value of foo?

`var foo = 10 + '20';`

The primitive values in JavaScript are number, string, boolean, null, undefined, and Symbol. In the problem above, we have an addition operator and two operands, one of type number and the other of type string. So, we need to know if the JavaScript engine will coerce the ‘20’ to a number or will coerce the 10 to a string.

In JavaScript, if any operand is a string and implicit coercion occurs, the other operands will be coerced to a string.

Knowing this, we can now confidently answer that foo will be ‘1020’.

`var foo = 10 + '20'; // '1020'`

### What will be the output of the code below?

`console.log(0.1 + 0.2 == 0.3);`

Many of you would guess false (you can pretty well sense that this is a trick question). But, why?

It has to do with the fact that the computer processing the code operates on a base 2 (binary) system. Each number system can only express fractions that use a prime factor of the base. For example, in base 10, the prime factors are 2 and 5, so 1/2, 1/4, 1/5,1/8, and 1/10 would all be expressed cleanly. But, 1/3, 1/6, 1/7, and 1/9 would all be repeating.

In base 2, the only prime factor is 2, so 1/2, 1/4, 1/8, etc. would all be expressed cleanly. So, when the computer processes the problem above (1/10 + 1/5) in base 2 it does so without having clean decimals to operate with. Then, it converts the number back into base 10 and thats why the equality shows as false.

`console.log(0.1 + 0.2 == 0.3) // 0.30000000000000004 == 0.3 is false`

### How would you make this work?

```
add(2, 5); // 7
add(2)(5); // 7
```

There are a few things that one has to understand in order to quickly develop a solution.

First, we need to understand that the function needs to allow either one or two parameters. Second, the function needs to return different results depending on whether one or two parameters were passed.

One of the great things about JavaScript is that functions are first-class. This means that we can return functions as values and also pass functions as parameters. This is what allows us to come up with an easy solution for the requirements above.

```
function add(a, b) {
if (b === undefined) { // if only 1 parameter is passed
return (b) => a + b;
}
return a + b;
}
```

The above code will work because the returned function will continue to have access to the variable a (due to closures) from the first function call.