var
declarations
Declaring a variable in JavaScript has always traditionally been done with the var
keyword.
1 | var a = 10; |
As you might’ve figured out, we just declared a variable named a
with the value 10
.
We can also declare a variable inside of a function:
1 2 3 4 5 | function f() { var message = "Hello, world!" ; return message; } |
and we can also access those same variables within other functions:
1 2 3 4 5 6 7 8 9 10 | function f() { var a = 10; return function g() { var b = a + 1; return b; } } var g = f(); g(); // returns '11' |
In this above example, g
captured the variable a
declared in f
. At any point that g
gets called, the value of a
will be tied to the value of a
in f
. Even if g
is called once f
is done running, it will be able to access and modify a
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function f() { var a = 1; a = 2; var b = g(); a = 3; return b; function g() { return a; } } f(); // returns '2' |
Please login to continue.