5
var e = 15;

function change_value(e){

    e = 10;
}

change_value(e);

console.log(e);

The Value of e is still 15.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
Shehroz Ahmed
  • 537
  • 4
  • 16
  • This is not changing of variable globally take e. and function parameter value set perform only. – Parth Trivedi Jun 26 '15 at 11:18
  • 1
    There is this answer which can be helpful: http://stackoverflow.com/questions/19721313/javascript-local-and-global-variable-confusion – briosheje Jun 26 '15 at 11:24

4 Answers4

4

The e inside the function scope is different from the e inside the global scope.

Just remove the function parameter:

var e = 15;

function change_value(){
    e = 10;
}

change_value();
console.log(e);
Sebastian Nette
  • 7,364
  • 2
  • 17
  • 17
2

javascript does not use reference for simple types. It use a copy method instead. So you can't do this.

You have 2 solutions. This way :

var e = 15;

function change_value(e) {
    return 10;
}

e = change_value(e);

Or this one :

var e = 15;

function change_value() {
    e = 10;
}

But note that this solution is not really clean and it will only works for this e variable.

Magus
  • 14,796
  • 3
  • 36
  • 51
  • I would recommend the OP to go for the first choice. It doesn't have side effect which means the other variable with the same name in even outer scope won't be unintentionally changed. – TaoPR Jun 26 '15 at 11:21
1

When you have a parameter in a function, the passed value is copied in the scope of the function and gets destroyed when the function is finished.

all variables in Javascript are created globally so you can just use and modify it without passing it:

var e = 15;

function change_value(){

    e = 10;
}

change_value();

console.log(e);
moffeltje
  • 4,521
  • 4
  • 33
  • 57
-1

You can do something like this if you want to assign the passed value to the outer e variable. this is just a sample. In the block you might have any logic in future.

var e = 15;
function change_value(e){

    return e;
}

e = change_value(10);

console.log(e);

But if you want to only call the function and change the e value then remove the parameter from the function because it has different scope then the outer one.

 var e = 15;
 function change_value(){

   e = 10;
}

change_value(10);

console.log(e);
Newinjava
  • 972
  • 1
  • 12
  • 19