Javascript: Why doesn’t an error occur when calling this code?

I play with an HTML canvas and write text on it using Javascript.

In doing so, I made a simple mistake, which took me some time to find. I wrote:

context.fillText = ("My message", x-coord, y-coord); 

An equal sign prevented the behavior that I expected. But there is one thing that I don’t understand: why does this code not give me an error in the Chrome Javascript console?

Is this valid javascript? If yes: could you explain what the code does when there is an equal sign?

+4
source share
3 answers

Yes, this is valid Javascript. It uses a comma operator, which simply evaluates the expression on the left, then the one on the right, and returns the value of the value pointed to the right.

Since the expressions "My message" and x-coord have no side effects, this is the same as:

 context.fillText = y-coord; 

Or:

 "My message"; // Does nothing x-coord; // Does nothing context.fillText = y-coord; 
+6
source

The comma operator evaluates each expression and returns the last, so the right side evaluates only:

 y-coord 

... and context.fillText set equal to it.

+4
source

If you ask about the difference between

context.fillText = ("My message", x-coord, y-coord);

and

context.fillText("My message", x-coord, y-coord);

The answer is that you assign the expression to the right of the = sign to context.fillText , so you are trying to rewrite the method itself, and not refer to it with arguments.

+1
source

All Articles