Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

would var declaration (such as var x;) overwrite previous value

I am learning the hoisting concept in javascript. One piece of code which blocked me is this:

function foo() {
  console.log(8);
}

var foo;

console.log(foo);

Question 1: I typed in this code in chrome console, print out is

function foo(){
    console.log(8)
}

would the variable declaration overwrite the function declaration? I think the print out should be undefined

Question 2: I typed in the same code in an online editer https://jsbin.com/dezixozewi/edit?js,console, it throws error as 'Identifier 'foo' has already been declared'. so it does not allow duplicate declaration at all.

Could any one help to explain the logic behind? Thanks a lot in advance!

like image 867
Gaoyan Avatar asked Jan 31 '26 18:01

Gaoyan


2 Answers

The reason the function is the value of foo is because in this line:

var foo;

You're just stating foo - that's a statement that doesn't do anything.

If you actually set foo to something, for example "FooBar":

function foo() {
  console.log(8);
}

var foo = "FooBar";

console.log(foo);

It overwrites the function, because as shown in this question, declaring anything with var that is a value will result in that value being "hoisted" to the top, and as such being the actual value of the identifier.

like image 94
Jack Bashford Avatar answered Feb 02 '26 06:02

Jack Bashford


would the variable declaration overwrite the function declaration?

No. Before any code is executed, the runtime finds all function and variable declarations and initializes the new scope with them. Things vary slightly between evaluating script code and evaluating function scope, but the result is the same:

  • Duplicate declarations are ignored.
  • Function declaration are evaluated at the end and assigned to their respective name.

In global scope, because foo is both a function name as well as a variable declaration, the variable declaration is ignored. And since it doesn't have an initializer, the value of foo doesn't change when that line is actually evaluated.

The details can be found in the language specification.


Question 2: I typed in the same code in an online editer https://jsbin.com/dezixozewi/edit?js,console, it throws error as 'Identifier 'foo' has already been declared'. so it does not allow duplicate declaration at all.

Unclear how jsbin evaluates the code, but it is valid.

like image 28
Felix Kling Avatar answered Feb 02 '26 07:02

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!