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
npm install --save-dev coffeescript
To globally install to execute the .coffee files anywhere
npm install --global coffeescript
Splat in CoffeeScript: In general, we can pass a fixed number of arguments to a function in CoffeeScript but what about if need to pass variable arguments to the functions.
Splats are the features provided by CoffeeScript that allows passing multiple arguments to functions. We can use splats in function just by placing three dots after the name of the argument.
Syntax:
functionName = ( argument1 , argument2...) -> ...
Example: This example shows how to accept multiple arguments within a function using splats in CoffeeScript. We have defined a function named lang_type() using splat. We have called this function multiple times with different numbers of arguments passed. Since we have used splats in defining the function, each time we call the function it accepts the variable number of arguments.
Javascript
lang_type = (first, second, others...) -> FirstType = first SecondType = second OtherType = others console.log "First Type: " +FirstType console.log "Second Type: " +SecondType console.log "Other types: " +OtherType // Passing 2 arguments console.log "############## Two types of languages ############" lang_type "Monolithic" , "Procedural" // Passing 4 arguments console.log "############## Four types of languages ############" lang_type "Monolithic" , "Procedural" , "Functional" , "Object Oriented" |
On compiling, it gives the following result:
Javascript
( function () { var lang_type; lang_type = function (first, second, ...others) { var FirstType, OtherType, SecondType; FirstType = first; SecondType = second; OtherType = others; console.log( "First Type: " + FirstType); console.log( "Second Type: " + SecondType); return console.log( "Other types: " + OtherType); }; // Passing 2 arguments console.log( "############## Two types of languages ############" ); lang_type( "Monolithic" , "Procedural" ); // Passing 4 arguments console.log( "############## Four types of languages ############" ); lang_type( "Monolithic" , "Procedural" , "Functional" , "Object Oriented" ); }).call( this ); |
Output :