Q1. Write a method sum
that would work with the following syntax?
console.log(sum(2,3)); // Outputs 5
console.log(sum(2)(3)); // Outputs 5
Solution
function sum(x) {
if (arguments.length == 2) {
return arguments[0] + arguments[1];
} else {
return function(y) { return x + y; };
}
}
Q2. What gets logged in the following code?
(function() {
console.log(1);
setTimeout(function(){console.log(2)}, 1000);
setTimeout(function(){console.log(3)}, 0);
console.log(4);
})();
Solution
1
4
3
2
Q3. What will be the output? How can we fix this?
for (var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
Solution
Output:
5
5
5
5
5
The fix:
- Using
let
for (let i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
- Using closures:
for (let i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
Q4. What is the output?
var x = 21;
var foo = function () {
console.log(x);
var x = 20;
};
foo();
Solution
undefined
Q5: What will be the output?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Solution
true
false
Q6: What will be the output?
var b = 1;
function outer(){
var b = 2
function inner(){
b++;
var b = 3;
console.log(b)
}
inner();
}
outer();
Solution
3
Q7. Memoize a function.
Solution
function memoize(fn) {
const cache = {}
return function() {
const args = JSON.stringify(arguments);
if (cache[args]) {
return cache[args]
}
const evaluatedValue = fn.apply(this, arguments);
cache[args] = evaluatedValue;
return evaluatedValue;
}
}
// example use
function factorial(n) {
if(n === 0 || n === 1) {
return 1
}
return factorial(n-1) * n;
}
const memoizedFactorial = memoize(factorial)
factorial(1000) // slow
memoizedFactorial(1000) // faster