8

I come to this question:

 f = (param) ->
      console.info '#{param}'
 f(1)

The outcome is #{param}

When I enclose the string with double quotation marks, this just print 1. I have also tested it in Ruby, its behaviour is the same. But that just contradicts the rule in CoffeeScript.org:

The golden rule of CoffeeScript is: "It's just JavaScript".

Because I think in Javascript, single quotes and double quotes are treated equally. And I do not use Ruby often. Can anyone explain why?

Thanks a lot.

1
  • 1
    It's only a golden rule in that it ends up being JavaScript, that doesn't mean it acts list JavaScript at the CoffeeScript source level. There's magic all over the place. Commented Aug 23, 2012 at 2:37

2 Answers 2

15

From the CoffeeScript documentation:

Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.

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

1 Comment

Except that single-quoted strings are not really literal as they are in Ruby. In Javascript, single quoted strings act like double quoted strings and interpret and treat the backslash as an escape character for \n, etc, requiring actual backslashes to be escaped. Coffeescript perpetuates this behavior for reasons that are not clear to me.
11

"It's just javascript" means it fundamentally compiles to ordinary JavaScript and doesn't attempt to take a radically different programming paradigm and compile it to JavaScript. CoffeeScript is primarily concerned with avoiding "the bad parts", boilerplate, and unnecessary syntax as opposed to introducing radically different basic constructs such as data types, etc.

JavaScript has no string interpolation. CoffeeScript brings this over from Ruby as a convenience. Disabling it for single quotes just gives you a clean way to get a string without the interpolation interpreted.

Don't take It's just JavaScript to mean It IS JavaScript. It's a flavor/variant/sibling.

2 Comments

Unlike ruby interpolation of a string (double-quotes) vs literal strings (single-quote) compile to JavaScript as a string. Therefore there is no runtime overhead. There maybe a compile time overhead. However, as in ruby the performance difference is so negligible that the use of single vs double is more personal style / preference then performance.
"JavaScript has no string interpolation". It finally does in es6 developer.mozilla.org/en/docs/Web/JavaScript/Reference/… :)

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.