Está en la página 1de 2

BY VALUE:

a. given a primitive value - num or boolen or string


b. set a variable equal to it.
c. Now the var, say a, has an address location where it knows where the primitive
value sits in memory. reference is to a location in memory.
d. let's say we set
b = a
or a was passed to a function as the parameter.
e. b points to a new address, a new location in memory. and a copy of the primitive
value is placed into that spot in memory. ie, if a = 3, it sits in one address in
memory. Then b is also equal to 3, but it is just a copy, a separate location in
memory that has been filled with the same value

summary, setting one variable equals to another by copying the value. 2 variables
become the same by copying the same value into 2 separate spots in memory.

BY REFERENCE
if we have an object instead...
a. when I set a variable equal to an object. we still get a location, an address in
memory so that the variable knows where that object lives. that's how we reference
it.
b. b=a or pass to a function.
b, instead of getting a new location in memory, simply points to the same location
in memory that a does. no new object is created. no copy of the original object is
created. instead, two names point to the same address. it's just like an alias. you
have two names, it doesn't matter because you live in the same place. both a and b
have the same value because when you ask a and b they point to the same location in
memory.

*all objects interact by reference

ie. BY VALUE
var a = 3;
var b;
b=a;
a=2//you can change a without affecting b
console.log(a);
console.log(b);

//the equals operator, seeing a primitive value, makes a copy.

output:
2
3

ie. BY REFERENCE (all objects)


var c = {greeting: 'hi'};
var d;

d=c; //equals operator sees an object and points both names to the same spot in
memory.

c.greeting = 'hello';//mutate

//BIG WORD ALERT:


mutate: to change something. "Immutable" means it cant be changed.
console.log(c);
console.log(d);

output:
object hello
object hello

ie. BY REFERENCE (even as parameters)


additional code:
function changeGreeting(obj){//mutate the object
obj.greeting = 'Hola';
}
changeGreeting(d);
console.log(c);
console.log(d);

output:
object Hola
object Hola

addt'l code:
//equals operator sets up new memory space (new address)
c = {greeting:'howdy'};
console.log(c);
console.log(d);

//d and c will no,longer be pointing to the same object in memory. (initialization?
first decalration?)

*in some languages, by reference and by values are in control by developers. In JS,
we do not have that option. All primitive types are by value and all objects are by
reference.

También podría gustarte