Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the value of variable in a function in javascript?

var e = 15;

function change_value(e){

    e = 10;
}

change_value(e);

console.log(e);

The Value of e is still 15.

like image 942
Shehroz Ahmed Avatar asked Jun 26 '15 11:06

Shehroz Ahmed


2 Answers

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);
like image 51
Sebastian Nette Avatar answered Oct 13 '22 12:10

Sebastian Nette


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.

like image 20
Magus Avatar answered Oct 13 '22 10:10

Magus