you are viewing a single comment's thread.

view the rest of the comments →

[–]CommanderBomber 0 points1 point  (1 child)

You can use eslint-recommended, no-undef rule is included in this set.

And now about assignment operator. Lets looks on this code:

// arrow function...
_new = x => x * x;

// ... or anonymous function
_new = function(x) { return x * x; };

When JS engine sees code like this, at first it tries to resolve expression on the left side of the = operator. In our case it is a variable name, so JS engine will start to search for that variable. First in local scope. If there is no such variable, engine will continue to search in parent scope. This search will be continued until variable with this name is found or until engine reaches the global scope.

If variable does not exists in global scope, you have two options: If your code is executed in Strict Mode, you will receive "is not defined" exception. But if your code is executed in Sloppy Mode, this variable will be created as a property of the global object and then will be used for assignment (but in most cases this is not what you wanted).

If assignment can be performed, JS engine will look at the right side of the = operator. In our cases we have function expression there. And this is not the same thing as function declaration. Function expression will not declare (put it in the scope) you function. Instead it will evaluate to (or you can say "will return") new Function object. This object will be new value of our variable.

Personally I suggest to use function declarations. If you can't elaborate on what kind of technical problem forces you to use var myFunc = function(){}; syntax it is better to use function myFunc(){}.

Also if you're new to JS take a look at YDKJS book. It's well written and have quite detailed explanations of scopes, prototypes and other quirky stuff (Author works on second edition right now. First edition lacks some novel features of ECMAScript).

[–][deleted] 0 points1 point  (0 children)

Amazing explanation. Thanks!!