简体   繁体   中英

trying to figure out 'if' condition in js

<script>
sayHi();
if (1) {
  function sayHi() {  console.log(1)  }
} else {
  function sayHi() {  console.log(2)  } 
}
</script> 

In chrome->console, it shows: 2

Question:

why if(1)=false ?

Those function definitions aren't defined at the time of execution of that condition. Both functions are hoisted at the beginning, and the latter overwrites the former.

if(1) will always evaluate to true.

This hoisting is exactly what enables you to call the function apparently before it's defined. The following code will log 1 , but note that in that case you have to call it after the condition, otherwise you'll get an error undefined is not a function .

if (1) {
  var sayHi = function() {  console.log(1)  }
} else {
  var sayHi = function() {  console.log(2)  } 
}
sayHi();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM