0

In CoffeeScript, the following statement evaluates to a JavaScript statement that is prefixed by an empty string.

I feel like there is an edge case with regards to type safety, but I can't think of it off the top of my head. In what case does the prefix make a difference?

CoffeeScript:

x = "#{foo} bar"

JavaScript:

x = "" + foo + " bar";
7
  • 2
    I am not 100% certain, but it's worth noting this bit of code I tried: {a:'y'}+" thing" => NaN but ""+{a:'y'}+" thing" => "[object Object] thing". So my guess is that concatenating an object to an empty string calls toString on the object before concatenation Commented Nov 4, 2014 at 2:25
  • 3
    It regards steps 7 and 8 of the + operator's definition and ensures concatenation (7) vs. addition (8). A contrived example is "#{3}#{4}". With the empty string at the start of the expression ("" + 3 + 4), it results in "34". Without it (3 + 4), the result is 7. Commented Nov 4, 2014 at 2:39
  • 2
    @Brennan: No. You fell prey to {a:'y';} being block syntax (see these questions). Try ({a:'y'})+" thing" Commented Nov 4, 2014 at 3:24
  • 1
    @JonathanLonowski, perfect explanation, thanks. Also, Bergi, thanks, great to know Commented Nov 4, 2014 at 3:25
  • 1
    @KaushikShankar Using {} adds some additional complexity since they have 2 uses in JavaScript. When written on its own, {} + " bar" is actually two statements, {}; and +" bar";, with a block and unary +. The parenthesis Bergi mentioned make it an Expression and the {} an Object literal. ({}) + " bar" results in "[object Object] bar". Commented Nov 4, 2014 at 18:18

1 Answer 1

1

It ensures that the expression is always evaluated as a string, preventing e.g. numerical addition instead of concatenation. In the case where a string only contains a single interpolated expression, it also effectively converts that expression to a string. A couple of examples:

x = 2
y = 3

typeof "#{x}" is string   # true since this compiles to "" + x

str2 = "#{x}#{y}" # We want the string "23" here, not the number 5
Sign up to request clarification or add additional context in comments.

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.