DEV Community

CorvusEtiam
CorvusEtiam

Posted on

When pointers bite you in Javascript.

That will be short and quick. If you already have background in any lower level language, then there will be nothing new. Still, I would love to hear your opinion.
If you still think that pointer in programming is:

a) white arrow on your screen
b) weird black magic

Don't worry. With webdev we always thing, we can get away from machine into perfect (almost, crying in CSS hacks intensifies) world of web-browser.

Sometimes those abstraction leak, or to say it better, show weird things happening behind a curtain. Frankly, those things are not weird at all.
It is just how machine is build, and memory works.

Ok, first things first. What is a pointer?

Pointer can be understood as indirection. Address of different object/variable/function etc.
Address itself do not store data*, but with address we can access original value.

Why should I care about it?

Let me start with simple example.

let arr = [1, 2, 3, 4, 5];
let o = { something: arr }

o['something'][0] = 4;

console.log("%o", o);
console.log("%o", arr);

What just happened?
Why assignment work this weird? Or rather, still who cares. It works that way, doh.

Well, because it is pretty important every time you work with complex data structure and I am not talking about some complex tree. I am talking about Date, Array, Object. Anything that is not primitive type.

Why primitives just works? Because, they are cheap to copy. Object are not, and you have to force JS, to make copy for you, because it moves around references aka. alias to your stuff.

Just like pointers they are not value themselves, but rather something, pointing to your original variable. JS doesn't show them in syntax, and they are always on. They can be pretty useful if your code looks like that:

class A {
   constructor(config) {
    this.options = config.a;
   }
}

class B {
   constructor(config) {
    this.options = config.b;
  }
}

var config = { a : { 'name' : 'X' }, 'b' : { 'name' : 'Y' } }

Change your config and it will change also new A(config).options.

Reference is just an alias. With one key difference really. You cannot assign to those references new values.

Wait, what?

let arr = [1,2,3,4];
function a(arr /* reference to Array object */) {
    arr = "hello"; /// it becomes local variable arr. Original is not changed 
}
function b(arr /* reference to Array object */) {
    arr[1] = "hello"; /// it changes inner element
}

console.log(arr);

Guess, what will be inside arr after executing a(arr) and b(arr).

Remember in JS by default you pass aliases or references and not copies. Only primitives like Booleans, Numbers and Strings are copied.

Alias isn't different from pointer under the hood. Safer, less functional, easier to use -- yes. Still it is just a alias into other value -- pointer.

See ya!

Top comments (0)