var
is the historical keyword used for variable declaration.var
declares variables in function scope, or global scope if not inside a function.var
to be deprecated and it is never used in this course.let
is the keyword we use most often for variable declaration.let
declares variables in block scope.let
are re-assignable.const
is a specialized form of let
that can only be used to initialize a variable.const
variable.const
scopes variables the same way that let
does.Consider this run
function, inside which foo
and bar
have function scope
. i
and baz
are scoped to the block expression.
// function and block scope in this example
function run() {
var foo = "Foo";
let bar = "Bar";
console.log(foo, bar);
{
console.log(foo);
let baz = "Bazz";
console.log(baz);
}
console.log(baz); // ReferenceError
}
run();
Notice that referencing baz
from outside it’s block results in JavaScript throwing a ReferenceError.
Consider this run
function, inside of which foo
has function scope
.
Consider this func1
function and it’s nested scopes.
// global scope
function func1(arg1) {
// func1 scope
return function func2(arg2) {
// func2 scope
return function func3(arg3) {
// func3 scope
console.log(arg1, arg2, arg3);
}
}
}
const adder = (arg1) => {
return (arg2) => {
return arg1 + arg2;
}
};
const func2 = adder(2);
const result = func2(2);
console.log(result); // => 4;
```js function