0

let s = new Set("Foood");

console.log(s); //{}
console.log(typeof foo); // function

var foo = "string";
foo = 34;

function foo() {
  //some code
}

console.log(typeof foo); // number

I was going through a codebase and came across this sort of codebase, can anyone explain the output of "typeof" operator in this code. Why for the first time it gave "function" and "number" second time.

Divya Singh
  • 147
  • 1
  • 13

2 Answers2

1

As requested the snippet will be interpreted as following. As you can see the variables and functions get moved to the top.

However variables initialised with let or const will throw a ReferenceError if they are used before the point they were declared. More on that in this post

var foo, s;

function foo() {
  //some code
}

s = new Set("Foood");
console.log(s); //{}

console.log(typeof foo); // function

foo = "string";
foo = 34;

console.log(typeof foo); // number
Reyno
  • 6,119
  • 18
  • 27
0

As you asked in the comments, here is the function after hoisting:

function foo() {
  //some code
}

let s = new Set("Foood");

console.log(s); //{}
console.log(typeof foo); // function

var foo = "string";
foo = 34;

console.log(typeof foo); // number

function foo() {} is moved up to the top of it's scope - which, in this case, is the top of the page. When the first typeof foo is called, foo is a function. foo is then overwritten, and becomes 34. The second typeof returns number because foo = 34

Sour_Tooth
  • 125
  • 9