5
var e = 15;

function change_value(e){

    e = 10;
}

change_value(e);

console.log(e);

The Value of e is still 15.

2
  • This is not changing of variable globally take e. and function parameter value set perform only. Commented Jun 26, 2015 at 11:18
  • 1
    There is this answer which can be helpful: stackoverflow.com/questions/19721313/… Commented Jun 26, 2015 at 11:24

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

3 Comments

But in my case, i need the value of e variable. e variable is inside another function so I'm passing it.
You can access the value directly. E.g. e = e * 10
Yeah you solved my problem, I first declared the variable at the top with null value and then assigned the value. Thank you.
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.

1 Comment

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.
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);

2 Comments

So how can i pass by reference in JavaScript ? we use '&' sign in C++ but how can I do this in JavaScript ?
@ShehrozSheikh There is no such this as pass by reference in Javascript.
-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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.