0

I have a doubt about the following codes. I thought that data-type primitives assigned to a variable in JS were passed by value, while objects were passed by reference. If functions are objects in JS, I thought they should be passed by reference, but the following two codes behave as passed by value:

CODE 1

var x = function hello(){ console.log("hello")};

console.log(x);

var y = x;

console.log(y);

x = function bye(){console.log("bye")};

console.log(x);

console.log(y);

OUTPUT

[Function: hello]
[Function: hello]
[Function: bye]
[Function: hello]

CODE 2

In this case I assigned a method to a global variable and the behavior is the same:

var x = {name:"Max",
        action: function one(){console.log("one")}
}

var y = x.action;

console.log(y);

x.action = function two(){console.log("two")};

console.log(x.action);

console.log(y);

OUTPUT

[Function: one]
[Function: two]
[Function: one]

I truly appreciate any insight and explanation on this.

max fraguas
  • 438
  • 1
  • 6
  • 12

4 Answers4

2

From that regard, JavaScript is pass-by-value.

Assigning variable X to variable Y will place the value of X in Y, even if the value of X is a reference to an object.

You can see the "by reference" nature that you're looking for when you modify a deeper property in an object:

var x = { foo: () => "bar"; }
var y = x;

x.foo = () => "baz";

y.foo(); // "baz", and not "bar".

If I were to set x to { foo: () => "baz" }, y.foo() would still result in "bar", because I didn't modify the original object, I replaced it with another.


To clarify, JavaScript does not have var x = &y; or something similar like in PHP.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • Thank you for your answer Madara. I'm aware of the example you posted. Now, how could I modify in code 1, the function hello, by reference? – max fraguas Aug 13 '16 at 21:57
0

In this code y won't be reference of x later, x is re-assigned with a new function. If you modify a property in x, y will still be a reference of x then.

The same happens with every object in JS.

0

You are simply assigning functions to variables, there's nothing tricky in this code and it's working as it should, feel free to ask something more.

Pexa
  • 45
  • 1
  • 7
0

Pass by reference/value doesn't matter here as there is no passing involved.

The values that these variable contain is a reference to a function. I think what you're expecting is that y and x are linked somehow after the assignment but the assignment only changes what function y refers to with no further association with x.

First x holds a reference to hello, then y is set to hold a reference to hello, then x is set to contain a reference to bye. So at the end, x contains a reference to bye, and y contains a reference to hello.

This is basically the same as:

var x = "hello";
var y = x;
x = "bye";

console.log(x);
console.log(y);
fgb
  • 18,439
  • 2
  • 38
  • 52