3 ms·
I'm not a JavaScript expert so I may be wrong, but I don't think that's right is it? If you are in a function scope (which you would be in the context of this
by chrisseaton 10y ago
I'm not a JavaScript expert so I may be wrong, but I don't think that's right is it?
If you are in a function scope (which you would be in the context of this article as we're talking about what the receiver is at different points) then variables assigned without any modifier are defined as locals, in the scope of that function. They are hoisted to the function scope, out of any block scope, unless you use 'var', but they're still locals aren't they?
- JasonSage 10y agoNo, they're actually globals.
- sbuttgereit 10y ago"Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed." From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- Animats 10y agoRight. This is a typical language design mistake. It happens in phases: - "We're not going to have declarations in our language. First use defines a variable". - "We need some way to define local variables. But if we make that the default, existing code will break. So the default has to be global." - Embrace the pain. There are variants on this theme. Python is local by default. Go has variable creation by assignment with ":=", but with weird semantics for multiple assignment. Other classic mistakes are "we don't need a Boolean type; 1 and 0 are enough", and "there's only one kind of integer". Fixing those later always sucks.
- jonreem 10y agoNo, GP is correct. If you omit the `var` (or `let`/`const` in es6) then you are implicitly assigning a property on the global object (`window` in the browser), in essence setting a global variable. Never omit `var`. If you are in a function scope, `var` declarations are hoisted to the top of the function scope, outside of any block scope, as you described. `let` and `const` declarations from es6 are block scoped. Personally I highly recommend never using `var` and simply adopting es6 and using `let` and `const`, preferring `const`, everywhere as they have significantly simpler and more intuitive semantics.
- sopooneo 10y agoI agree with the way you've responded. But there can be a case where omitting var on a variable definition will not assign it on the global object. That is, if you hit a variable by the same name as you go up the scope stack, you will just overwrite that variable's value. Example: function f1(){ var v = 'val'; var f2 = function(){ v = 'inner'; // will not hit global scope } f2(); console.log(v); } f1(); console.log(v); output: val Uncaught ReferenceError: v is not defined