how to pass by reference in javascript [duplicate] - javascript

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.

Related

empty an array passed to a function [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 3 years ago.
I am trying to empty an array passed to a function within javascript:
var a = [1,2,3];
function emptyArrayNo(ar) {
// the following does not empty the global array
ar = [];
}
function emptyArrayYes(ar) {
// any of the following 3 methods empties the global array
ar.length = 0;
//ar.splice(0, ar.length)
//while(ar.length > 0) {ar.pop();}
}
emptyArrayNo(a);
console.log(a); // returns [1,2,3]
emptyArrayYes(a);
console.log(a); // returns []
All the three methods within emptyArrayYes() seem to work, which I think is due to the reference to the array passed not being modified within the function. However when we set the array to [] within the function, I believe the reference changes therefore causing issues i.e. not being seen at the global scope. Can someone please clarify what is going on here? Thanks.

Why do I need to bind a shadowed function that is called through the same object? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Change variable through function in JavaScript [duplicate]

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.

Create variable name based on argument sent to function in javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I wanted to create variable name based on value sent to function in javascript.
like following, when i call function variable : variable("zebra"); this should return variable name as zebra1
function create variable(i){
return i+"1";
}
var variable("zebra")="abc";//this line should create variable zebra1 and initialise as abc
Try:
window['zebra'] = 'abc';
The window object holds all the global variables, assuming this is a request for global variables.
To specifically answer your question, you could put return window[i + '1'] = 'abc'; in your variable naming function.
Alternatively, you could create a global (or local) object named variables to hold all your variables:
function whoknows() {
var variables = {};
variables['zebra'] = 'abc';
}
Read more on working with objects at mozilla.org
You can create global variable with
window["zebra"] = "abc";
and use later ether with the same indexer syntax or directly - zebra.

Convert String name into javascript variable name? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Problem with example:
Variable name: var product5519 = 10;
I can get this name in the form of a String i.e
var str = "product5519"
Is there any way to convert it into variable name so that i can use the value assigned to
product5519
I know one way to solve this problem i.e using eval(str)
If there is any another way to solve it please tell?
Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:
window[str] = 42;
This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.
It's a bit hacky but if you wanted to make a global variable you could do:
var str = "product5519";
window[str] = value;
You could then access the variable like:
window[str];
window.str;
str; // Assuming that there is no local variable already named "str"
you could do something like:
window['product5519'] = 'value'
it may be better to have an array of products, depending on the situation ofc.
You can use an associative array:
var variables = [];
variables['product5519'] = 10;
console.log(variables['product5519']);

Categories