-3

Javascript beginner here. I am trying to understand the difference between the two examples below and why they present with different outcomes. Any help would be really appreciated! Thanks!

Example 1

var age = 30;

function changeAge(a) {
    a = 20;
}

changeAge(age);
console.log(age); // ------ output = 30

Example 2

var age = 30;

function changeAge() {
    age = 20;
}

changeAge();
console.log(age); // ------ output = 20
Mike Poole
  • 1,958
  • 5
  • 29
  • 41

2 Answers2

1

The two examples are different in that:

  • In the first example, you update a, which is a local variable lost at the end of the execution of the function.

  • In the second example, you update age, which is a global variable and accessible by all.

The quintessence of these examples is to illustrate that in JavaScript you can only pass variables by value and not by reference as in other languages.


To make the first example functionally the same as the second, you need to return a and assign the result of the function to age:

var age = 30;

function changeAge(a) {
  a = 20;
  return a; // or simply return 20;
}

age = changeAge(age);
console.log(age); // ------ output = 20
Angel Politis
  • 10,955
  • 14
  • 48
  • 66
0

Value of 'age' in the first case was not changed because you have changed the value of parameter's local variable 'a'.

In second case the value of 'age' was changed because it was a global which is available in the function.

Here two Concepts come in the scenerio please Study About both of them

Amit chauhan
  • 540
  • 9
  • 22