Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Call By Reference

Tags:

javascript

I have a quick question regarding some code I do not understand:

var anonymousGreet = function(){
    console.log('Hi');
}

function log(a){
    console.log(a);
}

log(anonymousGreet);

In the code above when I call the function log and pass in the function expression anonymousGreet as a parameter to log. Does that mean the variable "a" in log is pointing to the variable anonymous greet which is then pointing to the function object. Or does a point directly to the function object pointed to by anonymousGreet? I am a little confused if a first points to the variable anonymous greet or does it directly point to the function object pointed to by anonymousGreet. Sorry if this is confusing but any help would be appreciated! Thanks you!

like image 430
Northern Star Avatar asked Aug 31 '26 22:08

Northern Star


1 Answers

If you come from a C++ background then a simple rationalization is

  • In Javascript everything is passed by value, references are never used
  • All passed values are however pointers to objects

For example when you write:

a = b + c;

you should imagine (in C++) something along the lines of

Object *a, *b, *c;
a = new Number(b->numericValue() + c->numericValue());

(note that however Javascript differently from C++ provides a garbage collector so no explicit delete is ever needed).

This is of course just a simple description of what is the observable behavior (and it was may be the implementation of very first Javascript engines). Today what really happens behind the scenes is much more sophisticated and includes run-time generation of machine code (JIT).

This is the reason for which for example:

function foo(x) {
   x[0] = 1;
}

var a = [0];
foo(a); // Will change the content of a[0]

but

function bar(x) {
    x = 9;
}

var b = 0;
bar(b); // Will *NOT* change the content of b
like image 88
6502 Avatar answered Sep 03 '26 13:09

6502