This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript Pass Variables Through Reference
How can you do something like this in javascript?
In PHP you can put a & in a function in front of the parameter to write directly back to the variable.. How can you do something like this in javascript?
In JavaScript, values are passed to functions by value. Objects, however, are passed by reference.
Passing values:
function myfunction(x)
{
// x is equal to 4
x = 5;
// x is now equal to 5
}
var x = 4;
alert(x); // x is equal to 4
myfunction(x);
alert(x); // x is still equal to 4
Passing objects:
function myobject()
{
this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6
Source: http://snook.ca/archives/javascript/javascript_pass
If you pass an object into a function it is always treated as passing a reference to it.
To have a similar effect for primitive values, you might wrap them in an object before like
var intVal = { val: 0 };
That way you can pass it to a function and still modify the actual variable.
Related
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Its known that someone can make a one-line array function like this to return the single value:
var func = (x) => x + 1 //func(2) == 3
and you can also make multi-line array-functions, whose values need to be manually returned:
var funcMultiline = (x) => {
var result = 1;
result += x;
return result;
}
funcMultiline(4) == 5; //true
So the question:
let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:
[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Returning object literals using the concise body syntax params => {object:literal} will not work as expected.
You have to wrap the object literal with parenthesis:
var res = [...Array(25)].map(e => ({x: 5, y:10}))
console.log(res);
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 4 years ago.
Why this code returns 43 as the result, I expect it to result 42. The code is as follows:
function say667() {
// Local variable that ends up within closure
var num = 42;
var say = function() { console.log(num); }
num++;
return say;
}
var sayNumber = say667();
sayNumber();
You've closed over the variable num, not the value the variable has at the time you define the function.
This is the order of events:
You assign 42 to num
You increment num to 43
You return a function and store it in sayNumber
You call that function, which reads the value of num, which is 43
This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 7 years ago.
Why doesn't this work and is there any way to get it to work?
Im pretty sure it doesn't work because of variable scoping in javascript, but I can't think of any ways to get it to work.
Code
var x = 5;
var z = function(y) { y = 10; };
z(x);
console.log(x) // Outputs 5 instead of 10
var x = 5
var z = function(y) { y = 10; }
console.log(x) // Outputs 5 instead of 10
Where exactly did you changed X? you dont have X and you did not call the function as well.
I assume you wish to do this:
var x = {x: 5}
var z = function(y) { y.x = 10; }
z(x);
console.log(x.x) // Outputs 10
The code is using x as variable on an object instead of a primitive number which is passed by value and not by reference and thus cannot be modified.
Using object you can modify the attributes (properties) of the object
X won't change for a couple reasons. The first is that you are modifying the parameter y inside of the function. If you passed an object this would work as those are passes by reference. It would also work if you changed x directly instead of passing it as an argument.
The second reason is that you never ran the function. You need to call z with z()
What happens when you invoke the function z is that the parameters get initialized and assigned the value you passed in.
So the function might read something like
var y = 5;
y = 10;
and so, the y that is in the scope outside of the function, remains unchanged because this y is actually a whole new y variable just for this function's scope.
var x = 5;
var z = function(y)
{
y = 10;
//assigned value 10 to the function parameter variable y.
//You haven't done x=y or x=10 and so how do you expect the value of x to change?
}
console.log(x) // Outputs 5 instead of 10
Change it to:
var x = 5 ;
var z = function(y)
{
x = 10; //changed value of x to 10
}
console.log(x) // Outputs 10
The problem is not related to vatiable scope at all.Your variable x is global since it is outside the function.
AND YES,you can change it's value inside a function.But the problem with your code was that you never changed the value of x.
If this is what you intended to do:
z(x); //x=5 is passed to the function z
function(y)
{
y=10; //initially the value of y is 5.Since you have passed x.
//Doing y=10 does not change the value of x because y is another variable.The value of x was copied to y and y is not x.
x=y;//You have assigned 10 to x
}
console.log(x); //outputs 10
Changing the value of the function parameter does not change the value of the variable whose value you passed to the function.You are actually passing the value of x to y that is you are passing 5 to y and not the variable itself.
You are not passing the variable reference.You are just passing the value.
This question already has answers here:
Determine original name of variable after its passed to a function
(9 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 7 years ago.
I know this is completely useless, but I'm nonetheless curious. Is it possible to do something like the below?
function getVariableName ( v )
{
// .... do something .....
// return the string "v"
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console
function getArgNames(fn) {
var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
if (matches.length > 1) {
return matches[1].replace(/\s+/g, '').split(',');
}
return [];
}
That will return an array of the names of all arguments passed in to the function.
This question already has answers here:
how do I compare 2 functions in javascript
(6 answers)
Closed 6 years ago.
how to compare two static functions in javascript equal or not equal?
String(f1) === String(f2)
var f1 = f2 = function( a ){ return a; };
here, you can use f1 === f2 because they're pointing to the same memory and they're the same type
var f1 = function( a ){ return a; },
f2 = function( a ){ return a; };
here you can use that byte-saver Andy E used (which is implicitly converting the function to it's body's text as a String),
''+f1 == ''+f2.
this is the gist of what is happening behind the scences:
f1.toString( ) == f2.toString( )
Edit: Looking back on this post over a year after, I agree with #kangax - you should probably never do this.
Whenever I need to compare functions I make sure there is no scope ambiguity and use the same function object.
Say I have some a pair of library functions that take a callback as one of the parameters. For the sake of this example create1minuteCallback function will set a 1 minute timer and call the callback on each tick. kill1minuteCallback will turn off the callback and you must pass the same callback function as you did for create1minuteCallback.
function create1minuteCallback(callback){
//implementation
}
function kill1minuteCallback(callback){
//implementation
}
Quite clearly this will not work as the function we are passing is different on the second line:
create1minuteCallback(function(){alert("1 minute callback is called");});
kill1minuteCallback(function(){alert("1 minute callback is called");});
I normally do this:
function callbackFunc(){alert("1 minute callback is called");}
create1minuteCallback(callbackFunc);
kill1minuteCallback(callbackFunc);
Well, as simply as that - if you are going to compare functions, you do it for a reason I assume. What is your reason?
My reason was to not run a certain function twice.
I did it this way (just snippet code to get the idea)
var x = function(){
console.error("i am a functionX");
}
var y = function(){
console.error("i am a functionX");
}
var z = function(){
console.error("i am a functionZ");
}
var x2= x;
var obj = new Object();
obj[x] = "";
obj[x2] = "";
obj[y] = "";
obj[z] = "";
obj.abc = "xaxa";
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.error(obj[prop] + " hello " + prop);
}
}
Function x and y are the same, even though they have different whitespaces. x and y are not the same as z, since z has a different console.error.
Btw open your firebug console to see it in the jsbin example