Search code examples
javascriptfunctionvariablesstrictreferenceerror

Why do I get an error when create a function but not when a variable?


Could you please explain why following code gives me an error (in strict mode only)?

'use strict';


name = 'Adam';
console.log(name);

doSomething = function() {};

CONSOLE:

Adam

ReferenceError: doSomething is not defined


Solution

  • Strict mode forbids implicit globals.

    Variables must be explicitly declared (with const, let, or var).

    You can create an explicit global by assigning a property to the global object (window in a browser)… but don't: Globals are a good way to get conflicts between different parts of code. (e.g. between the browser built-in name variable and your own name variable).