Tilak Raj
Tilak Raj

Reputation: 1499

interpreting var a=b.c={} in javascript?

I was going through node.js where i came across something like this var exports = module.exports = {}; in the modules section .

This would be much similar to var a=b.c={}, how do i visualize it?

What's happening here?

From what i can understand is that both a and b are assigned as object, they both describe the same thing or is it that they both references same thing?

Example

exports.sayHelloInEnglish = function() {
  return "HELLO";
};

exports.sayHelloInSpanish = function() {
  return "Hola";
};

Same as

module.exports = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

  sayHelloInSpanish: function() {
    return "Hola";
  }
};

Can someone please explain it to me in much simpler terms?

Upvotes: 0

Views: 189

Answers (2)

Adithya Bhat
Adithya Bhat

Reputation: 3752

enter image description here

According to the parse tree of the statement, here are the things that happen in order.

  1. The object b will be added with a member called c or if it already exists, it is accessed.
  2. b.c is set to the literal {}
  3. The value of a is set to the value of b.c In step 3, it means both refer to the same thing.

For example, you can try this.

 var a = [1,5]
 var b = a
 b[1] = 2
 console.log(a)
 console.log(b)

Both will have updated values.

Upvotes: 0

Bergi
Bergi

Reputation: 665020

var exports = module.exports = {};, how do i visualize it?

First make sure to understand how it is parsed, what components the syntax consists of. It's basically two nested assignments1:

var exports = (module.exports = {});

You can translate this into the equivalent

var _temp = {};
module.exports = _temp;
var exports = _temp;

So yes, they both will contain the same object.

1: Grammatically it's an assignment expression in the initialiser of a variable declaration, but for ease of understanding we ignore the var

Upvotes: 3

Related Questions