CoffeeScript is a lightweight language that compiles into JavaScript. As compared to JavaScript, it provides simple and easy-to-learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by languages such as JavaScript, YAML, Ruby, Python and has also influenced languages that are LiveScript, MoonScript.
Installation of CoffeeScript:
Install locally for a project, use the following command:
npm install --save-dev coffeescript
To Globally install to execute the .coffee files anywhere, use the following command:
npm install --global coffeescript
What is String interpolation in CoffeeScript?
String interpolation is a programming language feature that allows inserting variables, arithmetic expressions, function calls directly into a string. String interpolation provides more easy and intuitive content-specification and string formatting as compared with string concatenation.
String interpolation in CoffeeScript: CoffeeScript provides the feature of string interpolation being inspired from Ruby language. This feature includes variables in strings and can take multi-line strings without the need of an escape character. CoffeeScript allows multiple expressions inside the interpolation.
String interpolation in CoffeeScript is done using double quotes(“”), a hash tag(#), and a pair of curly braces({}). The string is to be declared inside the double quotes and the variable that is to be interpolated is placed within the curly braces that are after hashtag symbol.
Syntax:
name = "GfG" message = " Hello from #{name} "
The above variable is interpolated only of the string is enclosed within double quotes (“”).
Example 1: On compiling the below example, it generates the following output “Hey Geeks, Welcome to neveropen”. The String interpolation is converted just as concatenation.
Javascript
name = "neveropen" message = "Hey Geeks, Welcome to #{name}" // Printing data console.log(message) |
Output:
Hey Geeks, Welcome to neveropen
Example 2: In this example of String interpolation, we are using a function call that calculates a cube of 10 for us.
Javascript
cube = (x) -> x * x * x message = "The cube of 10 is #{cube 10}" // Printing data console.log(message) |
Output:
The cube of 10 is 1000
Now we have observed that String interpolation looks somewhat similar to String interpolation. Let’s see what makes String interpolation different from String concatenation:
- In String concatenation, complexity to maintain string increases and becomes hard as the string grows large, whereas this complexity can be reduced with String interpolation.
- We can place variables, function calls within String using String Interpolation.
- String Interpolation helps in inserting values into a string literal.
- It makes code compact and more readable and thus easy to maintain.