1

I am reading Javascript the Good Parts and came across the following snippet under Chapter 5 Inheritance:

var coolcat = function (spec) {
   var that = cat(spec),
             super_get_name = that.superior('get_name');
   that.get_name = function (n) {
    return 'like ' + super_get_name() + ' baby'; return that;
    }
  }

I am confused by the coma after cat(spec) in line 2. What does the line do exactly? (line 2 +line 3) Thanks

3 Answers 3

5

That's just a shortcut for declaring two variables in one statement, it is equivalent to this:

var that           = cat(spec);
var super_get_name = that.superior('get_name');

The comma is actually an operator in JavaScript:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.

A var statement is made up of one or more expressions of the form:

varname [= value]

where the square brackets indicate an optional component. The general var statement looks like this:

var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];

You'll usually only see the comma operator used in var statements and for loops:

for(var i = 0, x = complicated_array[0]; i < complicated_array.length; x = complicated_array[++i])

but it can be used in other places.

Sign up to request clarification or add additional context in comments.

2 Comments

var x = y; is a statement but it contains an expression (y). However, expressions inside var statements cannot contain the comma operator.
@Šime: But the entire statement is not an expression so I'm a little uncertain about how to properly explain such details to a beginner. Is my latest updated a bit clearer/more-accurate?
3

It lets you declare another variable. It's equivalent to the following:

var that = cat(spec);
var super_get_name = that.superior('get_name');

See the var statement docs @ MDC.

Comments

2

The indentation is wrong, it should be:

var that = cat(spec),
    super_get_name = that.superior('get_name');

It is the same as saying:

var that = cat(spec);
var super_get_name = that.superior('get_name');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.