DEV Community

Code Craft-Fun with Javascript
Code Craft-Fun with Javascript

Posted on

Javascript 【tricky】💡interview output questions (Part 2)

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);
Enter fullscreen mode Exit fullscreen mode

Question 2

var output = (function(x){
    delete x;
    return x;
  })(0);
  console.log(output);
Enter fullscreen mode Exit fullscreen mode

Question 3

var Employee = {
  company: myCompany
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);
Enter fullscreen mode Exit fullscreen mode

Question 4

(function() {
   var a = b = 5;
})();
console.log(b);
Enter fullscreen mode Exit fullscreen mode

Question 5

function test() {
   console.log(a);
   console.log(foo());
   var a = 1;
   function foo() {
return 2; }
}
test();
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
mellen profile image
Matt Ellen

damn. those are tricky!

Collapse
 
mellen profile image
Matt Ellen

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?

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript • Edited

Consider this -

console.log(typeof function f(){})
Enter fullscreen mode Exit fullscreen mode

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.

let sum = (a,b) => a + b;
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
mellen profile image
Matt Ellen

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?

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

Checkout Part 1 as well !

Collapse
 
tylim88 profile image
Acid Coder

I failed all of them lol