Function definitions not raised

Wrt Raising the Definitions of fxn.

if (true) {
  function foo() {
    alert(1)
  }
} else {
  function foo() {
    alert(2)
  }
}
foo()
Run codeHide result

Chrome, about 2-3 months ago, will print 2. Now it prints 1. I missed something or made a console stopping at fxn!

DEMO - prints 1. I'm not sure where to find a demo of an older version of the browser. Probably the old version of v8 engine node. The current version of chrome is 49

+5
source share
2 answers

The code you have is invalid in strict mode. Functions are not extracted from blocks (or at least they should not), function declarations inside blocks were completely illegal until ES6. You have to write

"use strict";
var foo;
if (true) {
  foo = function() {
    alert(1)
  };
} else {
  foo = function() {
    alert(2)
  };
}
foo()

.

- , fxn!

, V8 , ES6. "" /, , ( ).

+8

.

, :

if (false){
 function foo(){
  console.log(1)
 }
}
foo()

Firefox , ReferenceError: foo is not defined. Chrome, , 1. , , . ( , ).

. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

, if. , Mozilla, , , . . , .

, , . , Chrome, , - . , .

, , FREEZE, 'use strict';, , .

+8

Source: https://habr.com/ru/post/1016196/


All Articles