var declarations

var declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword.

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:

function f() {
  var message = "Hello, world!";

  return message;
}

and we can also access those same variables within other functions:

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.

function f() {
  var a = 1;

  a = 2;
  var b = g();
  a = 3;

  return b;

  function g() {
    return a;
  }
}

f(); // returns '2'
doc_TypeScript
2016-10-04 19:25:44
Comments
Leave a Comment

Please login to continue.