Change variable through function in JavaScript [duplicate] - javascript

This question already has an answer here:
Changing variable in another function in JavaScript
(1 answer)
Closed 7 years ago.
I am trying to automate the changing of a variable through a function. However although it returns the right value, it doesn't change the actual value of the variable passed to it.
function change(one, two){
one = two;
return one;
}
var test = 1;
change(test, 5);
// returns 5;
console.log(test);
// still 1
Why does this happen and how can I solve this?

You can't pass variables. When you call change(test, 5); you are passing the value of test not the variable test.
That value is copied to the variable one.
You then assign a new value to one, but that doesn't touch test.
If you want to do anything like this, you need to pass an object and then modify the value of a property of the object.
function change(one, two){
one.test = two;
return one.test;
}
var myObject = {
test: 1
};
change(myObject, 5);
console.log(myObject.test);

You can't do this in JavaScript. Variables cannot be passed by reference, they are always passed by value.

Related

Javascript -What happens if a variable and a function have the same name? [duplicate]

This question already has answers here:
Function and variable with the same name
(2 answers)
Closed 5 years ago.
Might be a kind of easy question, but I have a question on the issue of having the same name for a variable and a function.
If there's a variable,
var add = 1;
and a function,
function add(x,y) {return x+y;}
and there're two console.log,
console.log(add)
console.log(add(1,2))
I've expected those 2 console.log would work properly since add contains the Number and add() is classified as a Function, but the second one prints an error. So they aren't considered the same.
But the result says I'm wrong.
Can anyone explain what's going on in my code?
Variables and function definitions(not expressions) are hoisted to up, it means that wherever in scope you wrote your function or variable they will be moved to the start of the scope. First goes functions definitions then variables. So it means that functions will be overwritten by variables.
var add = 1;
function add(x,y) {return x+y;}
console.log(add);
The order doesn't matter. Later will be the variable and will overwrite
function add(x,y) {return x+y;}
var add = 1;
console.log(add);

JavaScript variable assignment [duplicate]

This question already has answers here:
Change the value of an array changes original array JavaScript
(3 answers)
Closed 6 years ago.
Maybe the question already exists, but I don't find anything because I don't know how to call this problem.
I have an object function and want to assign the object variable into a variable:
this.myFunction = function() {
var selection; // internal variable
selection = this.selection; // both are [0,0]
console.log(this.selection); // result: [0,0]
selection[0] = 500; // set internal variable[0] 500
console.log(selection); // result: [500,0]
console.log(this.selection); // result: [500,0] <-- expected: [0,0]
}
How I can change the local variable without changing the other?
When you call selection = this.selection, you are copying the reference of this.selection value. So when you change the local variable selection, you are changing this.selection too.
You have to use the method slice() to create a new array from the value. Like this:
selection = this.selection.slice();

Parameters pass by value vs parameters as local variables in Javascript [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
Say for example you have a function like below
var value = 1;
function test(myVar) {
myVar = 2
}
test(value)
console.log(value)
//prints out 1
Now, I have read that there are two things that happen in JS functions.
1) Javascript passes primitives by value. When "value" is passed as an argument to test(), a copy is created that is separate from the global variable "value". Therefore the "myVar" is a separate variable from "value"
2) Parameters in JS functions are really just local variables to the function. So, the "myVar" parameter has scope only inside of the test() function.
I know both statements are true, but which one of these statements causes console.log(value) to print out 1
Both of those statements are true. The reason why it prints out 1 is that, as you mentioned, parameters are passed by value. As such, the value of your variable value is never altered.
Although point #2 is also true, it doesn't really have much to do with this behaviour. it is more related to doing something like using myVar outside of that function's scope.
Both of the statements are correct
Please check this URL from Mozilla Variable Scope in Javascript

Toggle boolean using function? [duplicate]

This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 6 years ago.
I would like to create a single function to toggle any boolean of my code, but I'm not able to get the expected result :
function toggle(x){
x=!x;
}
var test=false;
toggle(test);
alert(test);
Why doesn't this return true ?
Boolean datatype is passed by value. So, any changes made to the argument x will not reflect the actual variable test. You need to return the updated value from the function and assign it back to the variable.
function toggle(x) {
return !x; // Return negated value
}
var test = false;
test = toggle(test); // Assign the updated value back to the variable
alert(test);
But, as said in comments, it's better to use
test = !test;

how to pass by reference in javascript [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 8 years ago.
How should I pass by reference in a JavaScript function?
For example:
function passByReference(a){
a = "banana";
}
var x = "apple";
passByReference(x);
Here x should output banana.
I am new to JavaScript; any help would be appreciated. Thanks in advance.
Wrap the variable with an object. Properties of objects are passed by reference.
function passByReference(a) {
a.fruit = 'banana';
}
var wrapper = {fruit: 'apple'};
passByReference(wrapper);
You cannot pass by reference. If you want to modify the state of your caller from within the called function, there are two ways you could do:
Sometimes it fits best to wrap the state in an object:
var x = { valueToChange: 'initialValue' };
passByReference(x);
This works because with objects, a pointer to the address where the object lies is passed. That pointer is passed by value but it still points to the same object.
In some other cases a callback does the trick:
var x = "apple";
passByReference(function (newValue) { x = newValue; });
function passByReference(callback) {
callback("banana");
}
This works because if you define a function as above it builds a closure together with all variables it references. When your function gets called it really modifies the value of x.

Categories