Without "var", you're assigning to a global variable which you don't want in most cases.
Without "var", you're assigning to a global variable which you don't want in most cases.
function foo() {
'use strict';
bar = 5; // Error (maybe)
window.bar = 6; // No error
} that = this; var that;
would work. JavaScript!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?
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- "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.
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.
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