CoffeeScript – Environment ”; Previous Next The Compiler of the latest versions of CoffeeScript is written in CoffeeScript itself. To run CoffeeScript files in your system without a browser, you need a JavaScript runtime. Node.js Node.js is a JavaScript framework which is used to develop network server applications. It also acts as a bridge between JavaScript and the Operating System. The command-line version of CoffeeScript is distributed as a Node.js package. Therefore, to install CoffeeScript (command-line) in your system, you first need to install node.js. Installing Node.js Here are the steps to download and install Node.js in your system. Step 1 Visit the nodejs homepage and download its stable version for windows by clicking on the button hilighted in the snapshot given below. Step 2 On clicking, a .msc file named node-v5.50-x64 will be downloaded into your system, run the downloaded file to start the Node.js set-up. Here is the snapshot of the Welcome page of Node.js set-up wizard. Step 3 Click on the Next button in the Welcome page of the Node.js set-up wizard which will lead you to the End-user License Agreement page. Accept the license agreement and click on the Next button as shown below. Step 4 On the next page, you need to set the destination folder to the path where you want to install Node.js. Change the path to the required folder and click on the Next button. Step 5 In the Custom setup page, select the Node.js runtime to install node.exe file and click Next. Step 6 Finally, click on the Install button which will start the Node.js installation. Click on the Finish button of the Node.js set-up wizard as shown below to complete the Node.js installation. Installing CoffeeScript Node.js provides you a command prompt (Node.js command prompt). You can install CoffeeScript globally by entering the following command in it. c:> npm install -g coffeescript On executing the the above command, CoffeeScript will be installed in your system by producing the following output. Verification You can verify the installation of the CoffeeScript by typing the following command. c:> coffee -v On successful installation, this command gives you the version of CoffeeScript as shown below. Print Page Previous Next Advertisements ”;
Category: coffeescript
CoffeeScript – Exception Handling ”; Previous Next An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs, the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled. An exception can occur for many different reasons. Here are some scenarios where an exception occurs. A user has entered invalid data. A file that needs to be opened cannot be found. Exceptions in CoffeeScript CoffeeScripts supports exception/error handling using the try catch and finally blocks. The functionalities of these blocks are same as in JavaScript, the try block holds the exceptional statements, the catch block has the action to be performed when an exception occurs, and the finally block is used to execute the statements unconditionally. Following are the syntaxes of try catch and finally blocks in CoffeeScript. try // Code to run catch ( e ) // Code to run if an exception occurs finally // Code that is always executed regardless of // an exception occurring The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch. Example The following example demonstrates the Exception handling using try and catch blocks in CoffeeScript. In here, we are trying to use an undefined symbol in CoffeeScript operation and we handled the error occurred using the try and catch blocks. Save this code in a file with the name Exception_handling.coffee try x = y+20 console.log “The value of x is :” +x catch e console.log “exception/error occurred” console.log “The STACKTRACE for the exception/error occurred is ::” console.log e.stack Open the command prompt and compile the .coffee file as shown below. c:> coffee -c Exception_handling.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var e, error, x; try { x = y + 20; console.log(“The value of x is :” + x); } catch (error) { e = error; console.log(“exception/error occurred”); console.log(“The STACKTRACE for the exception/error occurred is ::”); console.log(e.stack); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee Exception_handling.coffee On executing, the CoffeeScript file produces the following output. exception/error occurred The STACKTRACE for the exception/error occurred is :: ReferenceError: y is not defined at Object.<anonymous> (C:Examplesstrings_exceptionsException_handling.coffee:3:7) at Object.<anonymous> (C:Examplesstrings_exceptionsException_handling.coffee:2:1) at Module._compile (module.js:413:34) at Object.exports.run (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcoffee-script.js:134:23) at compileScript (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:224:29) at compilePath (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:174:14) at Object.exports.run (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:98:20) at Object.<anonymous> (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptbincoffee:7:41) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) at Module.load (module.js:357:32) at Function.Module._load (module.js:314:12) at Function.Module.runMain (module.js:447:10) at startup (node.js:139:18) at node.js:999:3 The finally block We can also rewrite the above example using finally block. If we do so, the contents of this block are executed unconditionally after try and catch. Save this code in a file with the name Exception_handling_finally.coffee try x = y+20 console.log “The value of x is :” +x catch e console.log “exception/error occurred” console.log “The STACKTRACE for the exception/error occurred is ::” console.log e.stack finally console.log “This is the statement of finally block” Open the command prompt and compile the .coffee file as shown below. c:> coffee -c Exception_handling_finally.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var e, error, x; try { x = y + 20; console.log(“The value of x is :” + x); } catch (error) { e = error; console.log(“exception/error occurred”); console.log(“The STACKTRACE for the exception/error occurred is ::”); console.log(e.stack); } finally { console.log(“This is the statement of finally block”); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee Exception_handling_finally.coffee On executing, the CoffeeScript file produces the following output. exception/error occurred The STACKTRACE for the exception/error occurred is :: ReferenceError: y is not defined at Object.<anonymous> (C:Examplesstrings_exceptionsException_handling.coffee:3:7) at Object.<anonymous> (C:Examplesstrings_exceptionsException_handling.coffee:2:1) at Module._compile (module.js:413:34) at Object.exports.run (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcoffee-script.js:134:23) at compileScript (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:224:29) at compilePath (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:174:14) at Object.exports.run (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptlibcoffee-scriptcommand.js:98:20) at Object.<anonymous> (C:UsersTutorialspointAppDataRoamingnpmnode_modulescoffee-scriptbincoffee:7:41) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) at Module.load (module.js:357:32) at Function.Module._load (module.js:314:12) at Function.Module.runMain (module.js:447:10) at startup (node.js:139:18) at node.js:999:3 This is the statement of finally block The throw Statement CoffeeScript also supports the throw statement. You can use throw statement to raise your builtin exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action. Example The following example demonstrates the usage of the throw statement in CoffeeScript. Save this code in a file with name throw_example.coffee myFunc = -> a = 100 b = 0 try if b == 0 throw (“Divided by zero error.”) else c = a / b catch e console.log “Error: ” + e myFunc() Open the command prompt and compile the .coffee file as shown below. c:> coffee -c throw_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var myFunc; myFunc = function() { var a, b, c, e, error; a = 100; b = 0; try { if (b === 0) { throw “Divided by zero error.”; } else { return c = a / b; } } catch (error) { e = error; return console.log(“Error: ” + e); } }; myFunc(); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee throw_example.coffee On executing, the CoffeeScript file produces the following output. Divided by zero error. Print Page Previous Next Advertisements ”;
CoffeeScript – SQLite
CoffeeScript – SQLite ”; Previous Next SQLite is a lightweight, schema-based relational database engine. It is a popular choice as embedded database software for local storage in web browsers. Unlike many other database management systems, SQLite is not a client–server database engine. For more information read our SQLite Tutorial In this chapter you will learn how to communicate with SQLite database using CoffeeScript. Installation The SQLite3 database can be integrated with CoffeeScript using node-sqlite3 module. This module works with Node.js v0.10.x, v0.12.x, v4.x, and v5.x. This module caters various functions to communicate with SQLite3 using CoffeeScript, in addition to this it also provides an Straightforward query and parameter binding interface, and an Query serialization API. You can install the node-sqlite3 module using npm as shown below. npm install sqlite3 To use sqlite3 module, you must first create a connection object that represents the database and this object will help you in executing all the SQL statements. Connecting to Database In order to connect to SQLite database first of all create its package by invoking the require() function of the node-sqlite3 module and pass the string sqlite3 as a parameter to it. Then connect to a database by passing the name of the database to sqlite3.Database() construct. Following CoffeeScript code shows how to connect to an existing database. If database does not exist, then it will be created with the given name test.db, opened and finally the database object will be returned. #Creating sqlite3 package sqlite3 = require(”sqlite3”) #Creating a Database instance db = new (sqlite3.Database)(”test.db”) console.log “Database opened successfully.” We can also supply :memory: to create an anonymous in-memory database and, an empty string to create anonymous disk-based database, instead of test.db. Save the above code in a file with name create_db.coffee and execute it as shown below. If the database is successfully created, then it will produce the following message − c:> coffee create_db.coffee Successfully connected Creating a Table You can create a table in SQLite database through CoffeeScript using the run() function. Pass the query to create a table to this function in String format. The following CoffeeScript program will be used to create a table in previously test.db database − #Creating sqlite3 package sqlite3 = require(”sqlite3”) #Creating a Database instance db = new (sqlite3.Database)(”test.db”) console.log “Successfully connected” db.serialize -> db.run ”CREATE TABLE STUDENT (name TEXT, age INTEGER, city TEXT)” console.log “Table created successfully” return db.close() The serialize() function sets the database in serialized mode. In this mode when ever a callback encounters, it will be called immediately. The queries in that callback are executes serially. Soon the function returns The database will be set to normal mode again. After completing the transaction we need to close the connection using close() function. Save the above code in a file with name create_table.coffee and execute it as shown below. This will create a table named STUDENT in the database test.db displaying the following messages. C:> coffee create_table.coffee Successfully connected Table created successfully Inserting / Creating Data You can insert data into SQLite database through CoffeeScript code by executing the insert statement. To do so we can use the prepare() function which prepares SQL statements. It also accepts query with bind variables (?), values to these variables can be attached using run() function. You can insert multiple records using prepared statement, and after inserting all the records, you need to finalize the prepared statement using finalize() function. The following CoffeeScript program shows how to insert records in the table named STUDENT created in previous example. #Creating sqlite3 package sqlite3 = require(”sqlite3”).verbose() #Creating a Database instance db = new (sqlite3.Database)(”test.db”) console.log “Successfully connected” db.serialize -> stmt = db.prepare(”INSERT INTO STUDENT VALUES (?,?,?)”) stmt.run ”Ram”,24,”Hyderabad” stmt.run ”Robert”,25,”Mumbai” stmt.run ”Rahim”,26,”Bangalore” stmt.finalize() console.log “Data inserted successfully” return db.close() Save the above code in a file with name insert_data.coffee and execute it as shown below. This will populate the table named STUDENT displaying the following messages. C:> coffee insert_data.coffee Successfully connected Data inserted successfully Reading / Retrieving Data You can get the data from an SQLite table using the each() function. This function accepts an optional callback function which will be called on each row. The following CoffeeScript program shows how we can fetch and display records from the table named STUDENT created in the previous example #Creating sqlite3 package sqlite3 = require(”sqlite3”).verbose() #Creating a Database instance db = new (sqlite3.Database)(”test.db”) console.log “Successfully connected” db.serialize -> console.log “The contents of the table STUDENT are ::” db.each ”SELECT rowid AS id, name,age,city FROM STUDENT”, (err, row) -> console.log row.id + ”: ” +row.name+”, ”+ row.age+”, ”+ row.city return return db.close() Save the above code in a file with name retrive_data.coffee and execute it as shown below. This retrieves all the records in the table named STUDENT and displays on the console as follows. C:> coffee retrive_data.coffee Successfully connected The contents of the table STUDENT are :: 1: Ram, 24, Hyderabad 2: Robert, 25, Mumbai 3: Rahim, 26, Bangalore Updating Data The following CoffeeScript code shows how we can use UPDATE statement to update any record and then fetch and display updated records in the table named STUDENT #Creating sqlite3 package sqlite3 = require(”sqlite3”).verbose() #Creating a Database instance db = new (sqlite3.Database)(”test.db”) console.log “Successfully connected” db.serialize -> #Updating data stmt = db.prepare(”UPDATE STUDENT SET city = ? where name = ?”) stmt.run ”Delhi”,”Ram” console.log “Table updated” stmt.finalize() #Retrieving data after update operation console.log “The contents of the table STUDENT after update operation are ::” db.each ”SELECT rowid AS id, name, city FROM STUDENT”, (err, row) -> console.log row.id + ”: ” +row.name+”, ”+ row.city return return db.close() Save the above code in a file with name update_data.coffee and execute it as shown below. This updates the city of the student named Ram and displays all the records in the table after update operation as follows. C:> coffee update_data.coffee Successfully connected Table updated The contents of the table STUDENT after update operation are :: 1: Ram, Delhi 2: Robert, Mumbai 3: Rahim, Bangalore Deleting
CoffeeScript – Strings
CoffeeScript – Strings ”; Previous Next The String object lets you work with a series of characters. As in most of the programming languages, the Strings in CoffeeScript are declared using quotes as − my_string = “Hello how are you” console.log my_string On compiling, it will generate the following JavaScript code. // Generated by CoffeeScript 1.10.0 (function() { var my_string; my_string = “Hello how are you”; console.log(my_string); }).call(this); String Concatenation We can concatenate two strings using the “+” symbol as shown below. new_string = “Hello how are you “+”Welcome to Tutorialspoint” console.log new_String On compiling, it will generate the following JavaScript code. // Generated by CoffeeScript 1.10.0 (function() { var new_string; new_string = “Hello how are you ” + “Welcome to Tutorialspoint”; console.log(new_String); }).call(this); If you execute the above example, you can observe the concatenated String as shown below. Hello how are you Welcome to Tutorialspoint String Interpolation CoffeeScript also provides a feature known as String interpolation to include variables in stings. This feature of CoffeeScript was inspired from Ruby language. String interpolation was done using the double quotes “”, a hash tag # and a pair of curly braces { }. The String is declared in double quotes and the variable that is to be interpolated is wrapped within the curly braces which are prefixed by a hash tag as shown below. name = “Raju” age = 26 message =”Hello #{name} your age is #{age}” console.log message On compiling the above example, it generates the following JavaScript. Here you can observe the String interpolation is converted into normal concatenation using the + symbol. // Generated by CoffeeScript 1.10.0 (function() { var age, message, name; name = “Raju”; age = 26; message = “Hello ” + name + ” your age is ” + age; console.log(message); }).call(this); If you execute the above CoffeeScript code, it gives you the following output. Hello Raju your age is 26 The variable that is passed as #{variable} is interpolated only if the string is enclosed between double quotes ” “. Using single quotes ” ” instead of double quotes produces the line as it is without interpolation. Consider the following example. name = “Raju” age = 26 message =”Hello #{name} your age is #{age}” console.log message If we use single quotes instead of double quotes in interpolation, you will get the following output. Hello #{name} your age is #{age} CoffeeScript allows multiple lines in Strings without concatenating them as shown below. my_string = “hello how are you Welcome to tutorialspoint Have a nice day.” console.log my_string It generates the following output. hello how are you Welcome to tutorialspoint Have a nice day. JavaScript String Object The String object of JavaScript lets you work with a series of characters. This object provides you a lot of methods to perform various operations on Stings. Since we can use JavaScript libraries in our CoffeeScript code, we can use all those methods in our CoffeeScript programs. String Methods Following is the list of methods of the String object of JavaScript. Click on the name of these methods to get an example demonstrating their usage in CoffeeScript. S.No. Method & Description 1 charAt() Returns the character at the specified index. 2 charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 3 concat() Combines the text of two strings and returns a new string. 4 indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 5 lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 6 localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. 7 match() Used to match a regular expression against a string. 8 search() Executes the search for a match between a regular expression and a specified string. 9 slice() Extracts a section of a string and returns a new string. 10 split() Splits a String object into an array of strings by separating the string into substrings. 11 substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 12 toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale. 13 toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale. 14 toLowerCase() Returns the calling string value converted to lower case. 15 toUpperCase() Returns the calling string value converted to uppercase. Print Page Previous Next Advertisements ”;
CoffeeScript – Useful Resources ”; Previous Next The following resources contain additional information on CoffeeScript. Please use them to get more in-depth knowledge on this. Useful Video Courses Online Business V2: Sales Scripts for Every Sales Funnel 27 Lectures 3 hours Zach Miller More Detail Google Apps Script Beginners Course 18 Lectures 1 hours Laurence Svekis More Detail Google Apps Script Coding Complete Course 18 Lectures 1 hours Laurence Svekis More Detail Google Apps Script Course with PDF uploader Project 18 Lectures 1.5 hours Laurence Svekis More Detail Google Apps Script Make Images HTML5 Canvas save to Gdrive 15 Lectures 1 hours Laurence Svekis More Detail Apps Script Web App FUN API and JSON Data Spreadsheet 17 Lectures 1 hours Laurence Svekis More Detail Print Page Previous Next Advertisements ”;
CoffeeScript – Operators and Aliases ”; Previous Next CoffeeScript Operators An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is called the operator. The operators provided by CoffeeScript are same as in JavaScript except a few differences. There are some problematic operators in JavaScript. CoffeeScript either removed them or modified their functionality and it also introduced some new operators. Following is the list of operators supported by CoffeeScript. Arithmetic Operators Comparison Operators Logical (or Relational) Operators Assignment Operators CoffeeScript Aliases In addition to operators, CoffeeScript also provides aliases. CoffeeScript provides aliases to various operators and symbols in order to make your CoffeeScript code readable and more user friendly. Let us have a look at all the operators and aliases of CoffeeScript one by one. Arithmetic Operators CoffeeScript supports the following arithmetic operators. Assume variable A holds 10 and variable B holds 20, then − Show Examples S.No Operator and Description Example 1 + (Addition) Adds two operands A + B = 30 2 − (Subtraction) Subtracts the second operand from the first A – B = -10 3 * (Multiplication) Multiply both operands A * B = 200 4 / (Division) Divide the numerator by the denominator B / A = 2 5 % (Modulus) Outputs the remainder of an integer division B % A = 0 6 ++ (Increment) Increases an integer value by one A++ = 11 7 — (Decrement) Decreases an integer value by one A– = 9 Comparison Operators JavaScript supports the following comparison operators. Assume variable A holds 10 and variable B holds 20, then − Show Examples S.No Operator and Description Example 1 = = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true. (A == B) is not true. 2 != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true. (A != B) is true. 3 > (Greater than) Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true. (A > B) is not true. 4 < (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true. (A < B) is true. 5 >= (Greater than or Equal to) Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true. (A >= B) is not true. 6 <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true. (A <= B) is true. Following table shows the aliases for few of the Comparison operators. Suppose A holds 20 and variable B holds 20. Show Examples Operator Alias Example = = (Equal) is A is B gives you true. != = (Not Equal) isnt A isnt B gives you false. Logical Operators CoffeeScript supports the following logical operators. Assume variable A holds 10 and variable B holds 20, then − Show Examples S.No Operator and Description Example 1 && (Logical AND) If both the operands are non-zero, then the condition becomes true. (A && B) is true. 2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes true. (A || B) is true. 3 ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. ! (A && B) is false. The following table shows the aliases for some of the logical operators. Suppose X holds true and variable Y holds false. Show Examples Operator Alias Example && (Logical AND) and X and Y gives you false || (Logical OR) or X or Y gives you true ! (not x) not not X gives you false Bitwise Operators CoffeeScript supports the following bitwise operators. Assume variable A holds 2 and variable B holds 3, then − Show Examples S.No Operator and Description Example 1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. (A & B) is 2. 2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. (A | B) is 3. 3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (A ^ B) is 1. 4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. (~B) is -4. 5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. (A << 1) is 4. 6 >> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. (A >> 1) is 1. Assignment Operators CoffeeScript supports the following assignment operators − Show Examples S.No Operator and Description Example 1 = (Simple Assignment ) Assigns values from the right side operand to the left side operand C = A + B will assign the value of A + B into C 2 += (Add and Assignment) It adds the right operand to the left operand and assigns the result to
CoffeeScript – Conditionals
CoffeeScript – Conditionals ”; Previous Next While programming, we encounter some scenarios where we have to choose a path from a given set of paths. In such situations, we need conditional statements. Conditional statements help us take decisions and perform right actions. Following is the general form of a typical decision-making structure found in most of the programming languages. JavaScript supports the if statement (including its variants) and switch statement. In addition to the conditionals available in JavaScript, CoffeeScript includes the unless statement, the negation of if, and even more. Following are the conditional statements provided by CoffeeScript. S.No. Statement & Description 1 if statement An if statement consists of a Boolean expression followed by one or more statements. These statements execute when the given Boolean expression is true. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 unless statement An unless statement is similar to if with a Boolean expression followed by one or more statements except. These statements execute when a given Boolean expression is false. 4 unless…else statement An unless statement can be followed by an optional else statement, which executes when a Boolean expression is true. 5 switch statement A switch statement allows a variable to be tested for equality against a list of values. The then Keyword in CoffeeScript The if and unless statements are block statements that are written in multiple lines. CoffeeScript provides the then keyword using which we can write the if and the unless statements in a single line. Following are the statements in CoffeeScript that are written using then keyword. S.No. Statement & Description 1 if-then statement Using the if-then statement we can write the if statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is true. 2 if-then…else statement The if-then statement can be followed by an optional else statement, which executes when the Boolean expression is false. Using if-then…else statement, we can write the if…else statement in a single line. 3 unless-then statement Using the unless-then statement, we can write the unless statement of CoffeeScript in a single line. It consists of a Boolean expression followed by then keyword, which is followed by one or more statements. These statements execute when the given Boolean expression is false. 4 unless…then else statement The unless-then statement can be followed by an optional else statement, which executes when the Boolean expression is true. Using unless-then…else statement, we can write the unless…else statement in a single line. postfix if and postfix unless Statements In CoffeeScript, you can also write the if and unless statements having a code block first followed by if or unless keyword as shown below. This is the postfix form of those statements. It comes handy while writing programs in CoffeeScript. #Postfix if Statements to be executed if expression #Postfix unless Statements to be executed unless expression show example Print Page Previous Next Advertisements ”;
CoffeeScript – Command-line utility ”; Previous Next On installing CoffeeScript on Node.js, we can access the coffee-command line utility. In here, the coffee command is the key command. Using various options of this command, we can compile and execute the CoffeeScript files. You can see the list of options of the coffee command using its -h or –help option. Open the Node.js command prompt and execute the following command in it. c:>coffee -help This command gives you the list of various options of the coffee, along with the description of the operation performed by each of them as shown below. Compiling the CoffeeScript Code The CoffeeScript files are saved with the extension .coffee. You can compile these files using the -c or –compile option of the coffee command as shown below. c:>coffee -c filename.coffee Example Suppose there is a file in your system with the following CoffeeScript code which prints a message on the console. name = “Raju” console.log “Hello”+name+” Welcome to Tutorialspoint” Note − The console.log() function prints the given string on the console. To compile the above code, save it in a file with the name sample.coffee. Open the Node.js command prompt. Browse through the path where you have saved the file and compile it using the -c option of the coffee command of the coffee command-line utility as shown below. c:> coffee -c sample.coffee On executing the above command, the CoffeeScript compiler compiles the given file (sample.coffee) and saves it in the current location with a name sample.js as shown below. If you open the sample.js file, you can observe the generated JavaScript as shown below. // Generated by CoffeeScript 1.10.0 (function() { var name; name = “Raju”; console.log(“Hello ” + name + ” Welcome to Tutorialspoint”); }).call(this); Executing the CoffeeScript code You can execute a CoffeeScript file by simply passing the file name to the coffee command in the Node.js command prompt as follows. c:> coffee sample.coffee Example For example, let us execute the sample.coffee file. For this, open the Node.js command prompt. Browse through the path where you have saved the file and execute the file by directly passing its name to the coffee command as shown below. Watch and Compile In some scenarios, there is a chance that we do a lot of changes to our scripts. Using the –w option of the coffee command, you watch your scripts for changes. You can watch and compile a file simultaneously using the -wc option as shown below. When we use this option, the file will be recompiled each time you make changes in your script. c:>coffee -wc file_name Example Suppose we have compiled a file named sample.coffee using the -wc option and we modified the script thrice. Each time we change the script, the .coffee file is recompiled leaving the Node.js command prompt as shown below. Setting the Output Directory Using the -o option, we can set the output directory to place the compiled JavaScript files as shown below. c:>coffee -o “Required path where we want our .js files” file_name Example Let us save the JavaScript code of the sample.coffee file in a folder named data in the E drive using the -o option by executing the following command in the command prompt. c:>coffee -o E://data sample.coffee Following is the snapshot of the given folder after executing the above command. Here you can observe the JavaScript file of the sample.coffee Print the Compiled JavaScript If we want to print the compiled javascript on the console itself, we have to use the -p option of the coffee command as shown below. c:>coffee -p file_name Example For example, you can print the compiled JavaScript code of the sample.coffee file on the console using the -p option as shown below. The REPL (Read Evaluate Print Loop) CoffeeScript provides you an REPL-interactive shell. This shell is used to evaluate the CoffeeScript expressions. You can type any CoffeeScript code in this shell and get the result immediately. You can open REPL by executing the coffee command without any options as shown below. Using this shell, we can assign values to variables, create functions, and evaluate results. As shown in the following screenshot, if we call functions in REPL, it prints the value of the function. If we give an expression to it, it evaluates and prints the result of the expression. And if we simply type the statements in it, it prints the value of the last statement. In REPL, you can access multiple line mode by pressing ctrl+v where you can evaluate the code with multiple lines (like functions) and you can get back to REPL mode from it by pressing ctrl+v again. Here is an example usage of the multi line mode. Running CoffeeScript through Browser We can run CoffeeScript using the <script> tag of the HTML just like JavaScript as shown below. <script src=”http://jashkenas.github.com/coffee-script/extras/coffee-script.js” type=”text/javascript” charset=”utf-8″></script> <script type=”text/coffeescript”> # Some CoffeeScript </script> But for this, we have to import the library in each application and the CoffeeScript code will be interpreted line by line before the output is shown. This will slow down your applications, therefore this approach is not recommended. Therefore, to use CoffeeScript in your applications, you need to pre-compile them using the Coffee command-line utility and then you can use the generated JavaScript in your applications. Print Page Previous Next Advertisements ”;
CoffeeScript – Functions
CoffeeScript – Functions ”; Previous Next A function is a block of reusable code that can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions. In general, using JavaScript, we can define two types of functions – named functions, the regular functions with function name body and, Function expressions. Using function expressions, we can assign functions to variables. //named function function sayHello(){ return(“Hello there”); } //function expressions var message = function sayHello(){ return(“Hello there”); } Functions in CoffeeScript The syntax of function in CoffeeScript is simpler as compared to JavaScript. In CoffeeScript, we define only function expressions. The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript. Every function in CoffeeScript returns the last statement in the function automatically. If we want to return to the calling function or return a value before we reach the end of the function, then we can use the return keyword. In addition to in-line functions (functions that are in single line), we can also define multiline functions in CoffeeScript. Since the curly braces are eliminated, we can do it by maintaining proper indentations. Defining a Function Following is the syntax of defining a function in CoffeeScript. function_name = -> function_body Example Given below is an example of a function in CoffeeScript. In here, we have created a function named greet. This function automatically returns the statement in it. Save it in a file with the name function_example.coffee greet = -> “This is an example of a function” Compile it by executing the following command in the command prompt. c:>coffee -c function_example.coffee On compiling, it generates the following JavaScript code. Here you can observe that the CoffeeScript compiler automatically returned the string value in the function named greet(). // Generated by CoffeeScript 1.10.0 (function() { var greet; greet = function() { return “This is an example of a function”; }; }).call(this); Multi-line Functions We can also define a function with multiple lines by maintaining indentations instead of curly braces. But we have to be consistent with the indentation we follow for a line throughout a function. greet = -> console.log “Hello how are you” On compiling, the above CoffeeScript gives you the following JavaScript code. The CoffeeScript compiler grabs the body of the function that we have separated using indentations and placed within the curly braces. // Generated by CoffeeScript 1.10.0 (function() { var greet; greet = function() { return console.log(“Hello how are you”); }; }).call(this); Functions with Arguments We can also specify arguments in a function using parenthesis as shown below. add =(a,b) -> c=a+b console.log “Sum of the two numbers is: “+c On compiling the above CoffeeScript file, it will generate the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var add; add = function(a, b) { var c; c = a + b; return console.log(“Sum of the two numbers is: ” + c); }; }).call(this); Invoking a Function After defining a function, we need to invoke that function. You can simply invoke a function by placing parenthesis after its name as shown in the following example. add = -> a=20;b=30 c=a+b console.log “Sum of the two numbers is: “+c add() On compiling, the above example gives you the following JavaScript // Generated by CoffeeScript 1.10.0 (function() { var add; add = function() { var a, b, c; a = 20; b = 30; c = a + b; return console.log(“Sum of the two numbers is: ” + c); }; add(); }).call(this); On executing the above CoffeeScript code, it generates the following output. Sum of the two numbers is: 50 Invoking Functions with Arguments In the same way, we can invoke a function with arguments by passing them to it as shown below. my_function argument_1,argument_2 or my_function (argument_1,argument_2) Note − While invoking a function by passing arguments to it, the usage of parenthesis is optional. In the following example, we have created a function named add() that accepts two parameters and we have invoked it. add =(a,b) -> c=a+b console.log “Sum of the two numbers is: “+c add 10,20 On compiling, the above example gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var add; add = function(a, b) { var c; c = a + b; return console.log(“Sum of the two numbers is: ” + c); }; add(10, 20); }).call(this); On executing, the above CoffeeScript code it generates the following output. Sum of the two numbers is: 30 Default Arguments CoffeeScript supports default arguments too. We can assign default values to the arguments of a function, as shown in the following example. add =(a = 1, b = 2) -> c=a+b console.log “Sum of the two numbers is: “+c add 10,20 #Calling the function with default arguments add() On compiling, the above CoffeeScript generates the following JavaScript file. // Generated by CoffeeScript 1.10.0 (function() { var add; add = function(a, b) { var c; if (a == null) { a = 1; } if (b == null) { b = 2; } c = a + b; return console.log(“Sum of the two numbers is: ” + c); }; add(10, 20); add() }).call(this); On executing the above CoffeeScript code, it generates the following output. Sum of the two numbers is: 30 Sum of the two numbers is: 3 Print Page Previous Next Advertisements ”;
CoffeeScript – Variables
CoffeeScript – Variables ”; Previous Next Variables are nothing but named containers. You can place data into these containers and then refer to the data using the name of its container. CoffeeScript Variables In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below. name = variable name Example In the following CoffeeScript code, we have defined two variables name and age, of string and number data types respectively. Save it in a file with the name variable_example.coffee. name = “Javed” age = 25 Compiling the code Compile the above CoffeeScript code by executing the following command in the command prompt. c:> compile -c variable_example.coffee On compiling, a JavaScript file named variable_example.js will be generated with the following content. Here you can observe that the compiler declared the variables (age and name) using the var keyword on behalf of us. // Generated by CoffeeScript 1.10.0 (function() { var age, name; name = “Javed”; age = 25; }).call(this); Variable Scope The scope of a variable is the region of your program in which it is defined. JavaScript and CoffeeScript variables have only two scopes. Global Variables − A global variable has global scope which means it can be used anywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. The Problem with Variables in JavaScript In JavaScript, whenever we define a variable without using the var keyword, it is created with global scope. This causes a lot of problems. Consider the following example − <script type = “text/javascript”> var i = 10; document.write(“The value of global variable i is “+ i); document.write(“<br>”); test(); function test() { i = 20; document.write(“The value of local variable i is “+i); document.write(“<br>”); } document.write(“The value of global variable i is “+i); </script> On executing, the above JavaScript gives you the following output − The value of global variable i is 10 The value of local variable i is 20 The value of global variable i is 20 In the above example, we have created a variable named i in the global space and assigned the value 10 to it. And within the function, on an attempt to create a local variable with the same name, we have declared as i=20; without var keyword. Since we missed the var keyword, the value of global variable i is reassigned to 20. For this reason, it is recommended to declare variables using the var keyword. Variable Scope in CoffeeScript Whenever we compile a CoffeeScript file, the CoffeeScript compiler creates an anonymous function, and within that function, it transcompiles the CoffeeScript code in to JavaScript line by line. (If we want, we can remove the top level function wrapper using the -b or –bare option of the compile command) Every variable that we create is declared using the var keyword within the anonymous function and thus, by default, every variable is local in CoffeeScript. (function() { var age, name; name = “javed”; age = 20; }).call(this); Anyway, if we want, we can declare a variable with global namespace. We can do it explicitly as shown below. obj = this obj.age = 30 CoffeeScript Variable Names (Literals) While naming your variables in CoffeeScript, keep the following rules in mind. You should not use any of the CoffeeScript reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or Boolean variable names are not valid. CoffeeScript variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one. CoffeeScript variable names are case-sensitive. For example, Name and name are two different variables. Print Page Previous Next Advertisements ”;