Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does strict mode prohibit statement level function declarations?

"use strict";

if (true) {
  function foo() {
  }
}

In PhpStorm this code shows an error:

Function statement not at top level of a program or function is prohibited

However, Chrome happily executes it, even in the debugger and without any console output.

Now is it prohibited or not?

like image 478
AndreKR Avatar asked Aug 06 '15 16:08

AndreKR


People also ask

When would you not use strict mode?

If you have such an unrestrictedly typed code, that is used variables without declaring. One variable declared within some function/scope and used from somewhere else(it will be undeclared there) and you can't rewrite/change them, then you should not go for "use strict;" mode because it will break the code.

What does strict mode do?

Strict mode changes previously accepted "bad syntax" into real errors. As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

What is use strict What are the advantages and disadvantages to using it?

What is "use strict"; ? what are the advantages and disadvantages to using it? If you put "use strict"; at the top of your code (or function), then the JS is evaluated in strict mode. Strict mode throws more errors and disables some features in an effort to make your code more robust, readable, and accurate.

What if you use use strict but don't declare a variable?

In strict mode all variables have to be declared: if you assign a value to an identifier that has not been declared as variable, function, function parameter, catch-clause parameter or property of the global Object , then you will get a ReferenceError .


1 Answers

Yes, in ES5 they are prohibited (and in strict mode, all implementations throw). See also Kangax' great article for function statements in sloppy mode.

However, in ES6 they are block-level function declarations with new semantics. See also What are the precise semantics of block-level functions in ES6?. This seems to be what Chrome implements here; foo is not available outside of the if block.

like image 87
Bergi Avatar answered Sep 27 '22 22:09

Bergi