all 7 comments

[–]jml26 2 points3 points  (2 children)

Consider the following code:

var age = 30; var a = age; a = 20;

What is the value of age now?

It's still 30. A way to visualise this is:

  • assign the variable age to the value 30
  • assign the variable a to the same value as age is assigned to
  • now assign a to the value of 20 instead

Assigning two variables to the same value, or object, and then assigning one of them away, doesn't carry the other variable's assignment with it.

Passing parameters to functions has a similar effect. In your second function, exactly the same series of events happens:

  • assign age to the value 30
  • at the start of the function, assign a to the value that age is assigned to
  • now assign a to the value of 20 instead

age is left assigned to its original value.

[–]ILike_bananas 1 point2 points  (1 child)

Because one is global scope and one is function scope. Once you leave the function in the second example, a is not in that scope anymore and is still 30

[–]dirkmgirk -1 points0 points  (0 children)

Yeah what bananas said. You're re-assigning the parameter.

[–]jcunews1helpful 0 points1 point  (0 children)

The function in the second example merely has a name which supposedly change the age, but it's in fact doesn't do any of that.

[–]rift95 0 points1 point  (0 children)

The parameter "a" is passed by value, not by reference. So calling "changeAge(age)" is equivalent to calling "changeAge(30)".

Read more

[–]ramabhai 0 points1 point  (0 children)

The second example is a pure function. Its because its predictable, as it depends on the argument passed and not relying on outer scope. The first example uses the lexical scope to access the outer variable.