Oleksiy's Blog

JavaScript core singularity


Having some spare time to play with the concole, so...

Function.constructor === Function; // true

Object.constructor === Function; // true;

Function instanceof Object; // true

Object instanceof Function; // true

Object instanceof Object; // true

Function instanceof Function; // true

Object.getPrototypeOf(Object) instanceof Object; // true

Object.getPrototypeOf(Function.prototype) === Object.prototype; // true

Object.getPrototypeOf(Function).constructor === Function; // true

Object.prototype.constructor === Object; // true

Object.getPrototypeOf(Object.getPrototypeOf(Object)).constructor === Object; // true

Object.getPrototypeOf(Object.getPrototypeOf(Object)).toString(); // "[object Object]" (okay, it's an object...)

Object.getPrototypeOf(Object.getPrototypeOf(Object)) instanceof Object; // false

Object.getPrototypeOf(Object.getPrototypeOf(Object)) instanceof Function; // false

Object.getPrototypeOf(Object).toString() === (function () {}).toString(); // true

Object.getPrototypeOf(Object) instanceof Function; // false

Object.prototype === Object.getPrototypeOf(Object); // false

Object.prototype === Object.getPrototypeOf(Object.getPrototypeOf(Object)); // true

And a less one...

Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Function.prototype) === Object.getPrototypeOf(Object.getPrototypeOf(Object)))).isPrototypeOf(Object.getPrototypeOf(Object))// true
Tags: javascript, WTF

Swap variables in JavaScript


A quite common interview question is how to swap two variables w/o creating a third one for that purpose. That's a good one for checking you understanding of core language concepts, rather than best-practice. I'd prefer using intermediate var, rather than violate comprehension.

Array approach

a = [b][b = a, 0];

or another equivalent one:

a = [b, b = a][0];

The claim of not using a var is right here, but technically we create an inline array object in between which lives while the context's active, which can contain more operational overhead than a simple var using.

Closure approach

a = (function (c) { b = a; return c; }(b));

Here we store the intermediate value in lexical scope instead. That's not the best performer either although.

Bitwise approach

If you're dealing with integers and want to make your colleaugues hate you a little bit more, use this:


Let's zoom in:

a = (a = a ^ b, b = a ^ b, a ^ b);

And more zoom:

a = a ^ b;
b = a ^ b;
a = a ^ b;

This approach is also known as XOR algorithm.

Arithmetic approach:

a = b + (b=a, 0);

This one is type sensitive. For strings it may look like this:

a = b + (b=a, '');

And less one:


ES6 way

It's just making our live easier:

[a,b] = [b,a];