What is the output for each code mentioned below and Why ?
Add your solutions with explanation in the comment section.
Question 1
var y = 1; if (function f(){}) { y += typeof f; } console.log(y);
Question 2
var output = (function(x){ delete x; return x; })(0); console.log(output);
Question 3
var Employee = { company: ’myCompany’ } var emp1 = Object.create(Employee); delete emp1.company console.log(emp1.company);
Question 4
(function() { var a = b = 5; })(); console.log(b);
Question 5
function test() { console.log(a); console.log(foo()); var a = 1; function foo() { return 2; } } test();
Top comments (6)
damn. those are tricky!
Now that I've looked into them, I understand all of them except for question 1. how is a function declaration legal in an if statement?
Consider this -
You will get its type as
function
. The function can be treated as a value , as in javascript everything is an object. Even functions are objects. Functions can be assigned to a variable as well.OK. I think I get it. Because a function declaration can be on the RHS of an assignment statement it can go in the middle of an if statement?
Checkout Part 1 as well !
I failed all of them lol