DEV Community

Discussion on: 10 JavaScript concepts you need to know for interviews

Collapse
 
islicedi profile image
Jake • Edited

Wait, I am not sure that is correct. In this case you are you are reassigning the value of the variable n locally but that is just overwriting your reference inside the function. You are actually passing a reference, because you can do:
var o = { p: 'foo' };
(function(n) {
n.p: 'bar'; // Sets the value of n.p, Value of o affected.
})(o);
console.log(o); // Emits { p: 'bar' }

Collapse
 
birjolaxew profile image
Johan Fagerberg • Edited

You are passing a reference, but you are not passing by reference.

If you were passing by reference, the variable inside the function would refer to the variable outside of the function.

See this PHP example.

<?php
$o = "foo";
function modifyVariable(&$n) {
  $n = "bar";
}
modifyVariable($o);
echo $o; // "bar"
?>

This is not the case in JavaScript - the variable inside the function is completely separate from the variable outside the function, but it refers to the same value.

You are given a reference to the value - you are not given the variable by reference.