xhallix
xhallix

Reputation: 3011

Javascript defining object, comma case

While I was trying some fundemantels in Javascript, I came across a question, which suprised me, and I cannot find an answer to that. I got the following, which works perfecty:

var obj= new Object ();
    obj.test = "Hello" 

    obj.testTwo= function (){
        console.log(this.test)
    },obj.testTwo();

When I'm trying it without a comma, it does not work.

var obj= new Object ();
    obj.test = "Hello" 

    obj.testTwo= function (){
        console.log(this.test)
    }obj.testTwo();

So I tried this as a third option...and it works?

var obj= new Object ();
    obj.test = "Hello" 

    obj.testTwo= function (){
        console.log(this.test)
    }
    obj.testTwo();

Now I'm quiet confused. Why to use a comma and why does it work with a break?

Upvotes: 0

Views: 109

Answers (4)

Teemu
Teemu

Reputation: 23396

In the first snippet, the comma operator does its duty as it is documentated: "evaluates both of its operands (from left to right) and returns the value of the second operand." MDN.

Basicly your second snippet is an assignment. Assignments should always be terminated with a semicolon, even if their last expression would be a block of statements. However, this is not obvious to ASI. Hence this snippet fails without either a semicolon or a newline between the block and object method call, where interpreter expects to see an operator or a termination of the assignment. If none of these is found, an Unexpected token error is thrown. This same explanation stands for why the third snippet works.

Upvotes: 2

Amrendra
Amrendra

Reputation: 2077

Newlines (\n or \r\n) and commas (,) acts as statement separators.

Upvotes: 0

pdoherty926
pdoherty926

Reputation: 10349

What you're seeing is the comma operator in action. https://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

Upvotes: 3

ATOzTOA
ATOzTOA

Reputation: 35950

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

So, it evaluates both your codes. But it doesn't when you put them together.

Read more...

Example:

It is same as when you do

var a = 10, b = 40;

Upvotes: 0

Related Questions