Why (+"") in draw.text? Qgzmbb


Hello fellow coders. I’m working on a pong game with .SVG with this https://css-tricks.com/pong-svg-js/ as my learning source. But there is one thing I don’t understand and I can’t seem to find the answer anywhere.

Here is the code in question:

var scoreLeft = draw.text(playerLeft+"").font({ size: 32, family: 'Menlo, sans-serif', anchor: 'end', fill: '#fff' }).move(width/2-10, 10);

Why is there at need to be a …+ “” after playerLeft in var scoreLeft

if I remove them, the code won’t execute.

Link to codepen: https://codepen.io/sellew/pen/Qgzmbb?editors=0010#0

Thanks in advance


The var playerLeft is assigned an integer while the text() method accepts a string. To convert an integer to a string you can append it with an empty string.


Thanks for the quick response. That was very helpfull:slight_smile: !


myVar + '' is effectively the same as String(myVar), and also similar to myVar.toString() (though myVar.toString() throws a type error if myVar === null).

As a general best practice, implicitly converting something to a string using yourVal + '' is best avoided because it makes your code harder to understand (as evidenced by the existence of this thread).


Thanks! Indeed you have a point. I’ve now changed the code to fit better practice.