Discuss CoffeeScript ”; Previous Next CoffeeScript is a lightweight language which transcompiles into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language. Print Page Previous Next Advertisements ”;
Category: coffeescript
CoffeeScript – Overview
CoffeeScript – Overview ”; Previous Next At present, JavaScript is the fastest mainstream dynamic language available, and it is known as the lingua franca of the web. It is developed by Brendan Eich in the year of 1995 in 10 days. Because of its effective features, JavaScript became popular and went global quickly. It was there in lab for a very less time, which was not enough to polish the language. May be for this reason, inspite of its good parts, JavaScript has a bunch of design errors and it bagged a bad reputation of being a quirky language. What is CoffeeScript ? CoffeeScript is a lightweight language based on Ruby and Python which transcompiles (compiles from one source language to another) into JavaScript. It provides better syntax avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language. Advantages of CoffeeScript Following are the advantages of CoffeeScript − Easily understandable − CoffeeScript is a shorthand form of JavaScript, its syntax is pretty simple compared to JavaScript. Using CoffeeScript, we can write clean, clear, and easily understandable codes. Write less do more − For a huge code in JavaScript, we need comparatively very less number of lines of CoffeeScript. Reliable − CoffeeScript is a safe and reliable programming language to write dynamic programs. Readable and maintainable − CoffeeScript provides aliases for most of the operators which makes the code readable. It is also easy to maintain the programs written in CoffeeScript. Class-based inheritance − JavaScript does not have classes. Instead of them, it provides powerful but confusing prototypes. Unlike JavaScript, we can create classes and inherit them in CoffeeScript. In addition to this, it also provides instance and static properties as well as mixins. It uses JavaScript”s native prototype to create classes. No var keyword − There is no need to use the var keyword to create a variable in CoffeeScript, thus we can avoid the accidental or unwanted scope deceleration. Avoids problematic symbols − There is no need to use the problematic semicolons and parenthesis in CoffeeScript. Instead of curly braces, we can use whitespaces to differentiate the block codes like functions, loops, etc. Extensive library support − In CoffeeScript, we can use the libraries of JavaScript and vice versa. Therefore, we have access to a rich set of libraries while working with CoffeeScript. History of CoffeeScript CoffeeScript is developed by Jeremy Ashkenas. It was first committed in Git On December 13, 2009. Originally the compiler of the CoffeeScript was written in Ruby language. In March 2010, the CoffeeScript compiler was replaced; this time instead of Ruby, they used CoffeeScript itself. And in the same year, CoffeeScript 1.0 was released and at the time of release, it was one of the most wanted projects of the Git hub. Limitations of CoffeeScript Sensitive to whitespaces − CoffeeScript is very sensitive to whitespaces, so programmers need to be very careful while providing indentations. If we do not maintain proper indentation, the entire code may go wrong. TutorialsPoint”s CoffeeScript IDE You can compile CoffeeScript files using TutorialsPoint”s CoffeeScript compiler provided in our Coding Ground section https://www.tutorialspoint.com/codingground.htm. Follow the steps given below to use our CoffeeScript compiler. Step 1 Visit the home page of our website by clicking the following link www.tutorialspoint.com. Step 2 Click on the button named CODING GROUND that is located at the top right corner of the homepage as highlighted in the snapshot given below. Step 3 This will lead to our CODING GROUND section which provides online terminals and IDEs for about 135 programming languages. Open CoffeeScript IDE in the Online IDEs section which is shown in the following snapshot. Step 4 If you paste your CoffeeScript code in main.coffee (You can change the file name) and click the Preview button, then you can see the compiled JavaScript in the console as shown in the following snapshot. Print Page Previous Next Advertisements ”;
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 – Date
CoffeeScript – Date ”; Previous Next The Date object is a data-type built into the JavaScript language. Date objects are created as new Date( ). Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time. The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755. Similar to other JavaScript objects we can also use the date object in our CoffeeScript code. Date Methods Following is the list of methods of the Date object of JavaScript. Click on the name of these methods to get an example demonstrating their usage in CoffeeScript. S.No. Method & Description 1 getDate() Returns the day of the month for the specified date according to local time. 2 getDay() Returns the day of the week for the specified date according to local time. 3 getFullYear() Returns the year of the specified date according to local time. 4 getHours() Returns the hour in the specified date according to local time. 5 getMilliseconds() Returns the milliseconds in the specified date according to local time. 6 getMinutes() Returns the minutes in the specified date according to local time. 7 getMonth() Returns the month in the specified date according to local time. 8 getSeconds() Returns the seconds in the specified date according to local time. 9 getTime() Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. 10 getTimezoneOffset() Returns the time-zone offset in minutes for the current locale. 11 getUTCDate() Returns the day (date) of the month in the specified date according to universal time. 12 getUTCDay() Returns the day of the week in the specified date according to universal time. 13 getUTCFullYear() Returns the year in the specified date according to universal time. 14 getUTCHours() Returns the hours in the specified date according to universal time. 15 getUTCMinutes() Returns the milliseconds in the specified date according to universal time. 16 getUTCMilliseconds() Returns the minutes in the specified date according to universal time. 17 getUTCMonth() Returns the month in the specified date according to universal time. 18 getUTCSeconds() Returns the seconds in the specified date according to universal time. 19 getYear() Deprecated – Returns the year in the specified date according to local time. Use getFullYear instead. 20 setDate() Sets the day of the month for a specified date according to local time. 21 setFullYear() Sets the full year for a specified date according to local time. 22 setHours() Sets the hours for a specified date according to local time. 23 setMilliseconds() Sets the milliseconds for a specified date according to local time. 24 setMinutes() Sets the minutes for a specified date according to local time. 25 setMonth() Sets the month for a specified date according to local time. 26 setSeconds() Sets the seconds for a specified date according to local time. 27 setTime() Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. 28 setUTCDate() Sets the day of the month for a specified date according to universal time. 29 setUTCFullYear() Sets the full year for a specified date according to universal time. 30 setUTCHours() Sets the hour for a specified date according to universal time. 31 setUTCMilliseconds() Sets the milliseconds for a specified date according to universal time. 32 setUTCMinutes() Sets the minutes for a specified date according to universal time. 33 setUTCMonth() Sets the month for a specified date according to universal time. 34 setUTCSeconds() Sets the seconds for a specified date according to universal time. 35 setYear() Deprecated – Sets the year for a specified date according to local time. Use setFullYear instead. 36 toDateString() Returns the “date” portion of the Date as a human-readable string. 37 toLocaleDateString() Returns the “date” portion of the Date as a string, using the current locale”s conventions. 38 toLocaleString() Converts a date to a string, using the current locale”s conventions. 39 toLocaleTimeString() Returns the “time” portion of the Date as a string, using the current locale”s conventions. 40 toTimeString() Returns the “time” portion of the Date as a human-readable string. 41 toUTCString() Converts a date to a string, using the universal time convention. Print Page Previous Next Advertisements ”;
CoffeeScript – Objects
CoffeeScript – Objects ”; Previous Next Objects in CoffeeScript are similar to those in JavaScript. These are a collection of the properties, where a property includes a key and a value separated by a semi colon (;). In short, CoffeeScript objects are a collection of key-value pairs. The objects are defined using curly braces, an empty object is represented as {}. Syntax Given below is the syntax of an object in CoffeeScript. In here, we place the key-value pairs of the objects within the curly braces and they are separated using comma (,). object ={key1: value, key2: value,……keyN: value} Example Following is an example of defining an object in CoffeeScript. Save this code in a file with name objects_example.coffee student = {name: “Mohammed”, age: 24, phone: 9848022338 } Open the command prompt and compile the .coffee file as shown below. > coffee -c objects_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var student; student = { name: “Mohammed”, age: 24, phone: 9848022338 }; }).call(this); Just as in arrays, we can remove the commas by specifying the key-value pairs in new lines as shown below. student = { name: “Mohammed” age: 24 phone: 9848022338 } Indentations instead of curly braces Just like other block statements in CoffeeScript, we can use indentations instead of curly braces {} as shown in the following example. Example We can rewrite the above example without curly braces as shown below. student = name: “Mohammed” age: 24 phone: 9848022338 Nested objects In CoffeeScript, we can write objects within objects. Example The following example demonstrates the nested objects in CoffeeScript. Save this code in a file with name nested_objects.coffee contact = personal: email: “[email protected]” phone: 9848022338 professional: email: “[email protected]” phone: 9848033228 Open the command prompt and compile the .coffee file as shown below. > coffee -c nested_objects.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var contact; contact = { personal: { email: “[email protected]”, phone: 9848022338 }, professional: { email: “[email protected]”, phone: 9848033228 } }; }).call(this); Comprehensions over objects To iterate over the contents of an object, we can use comprehensions. Iterating the contents of an object is same as iterating the contents of an array. In objects, since we have to retrive two elements keys and values we will use two variables. Example The following is an example showing how to iterate the contents of an object using comprehensions. Save this code in a file with name object_comprehensions.coffee student = name: “Mohammed” age: 24 phone: 9848022338 console.log key+”::”+value for key,value of student Open the command prompt and compile the .coffee file as shown below. > coffee -c object_comprehensions.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var key, student, value; student = { name: “Mohammed”, age: 24, phone: 9848022338 }; for (key in student) { value = student[key]; console.log(key(+”::” + value)); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. > coffee object_comprehensions.coffee On executing, the CoffeeScript file produces the following output. name::Mohammed age::24 phone::9848022338 Arrays of Objects In CoffeeScript, an array can also contain objects in as shown below. a = [ object1_key1: value object1_key2: value object1_key3: value , object2_key1: value object2_key2: value object2_key3: value ] The following example shows how to define an array of objects. We can just list the key value pairs of the objects we want in an array by separating them using commas (,). students =[ name: “Mohammed” age: 24 phone: 9848022338 , name: “Ram” age: 25 phone: 9800000000 , name: “Ram” age: 25 phone: 9800000000 ] console.log student for student in students Open the command prompt and compile the .coffee file as shown below. c:> coffee -c array_of_objects.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var i, len, student, students; students = [ { name: “Mohammed”, age: 24, phone: 9848022338 }, { name: “Ram”, age: 25, phone: 9800000000 }, { name: “Ram”, age: 25, phone: 9800000000 } ]; for (i = 0, len = students.length; i < len; i++) { student = students[i]; console.log(student); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee array_of_objects.coffee On executing, the CoffeeScript file produces the following output. { name: ”Mohammed”, age: 24, phone: 9848022338 } { name: ”Ram”, age: 25, phone: 9800000000 } { name: ”Ram”, age: 25, phone: 9800000000 } Reserved Keywords JavaScript does not allow reserved keywords as property names of an object, if we want use them, we have to wrap them using double quotes ” “. Example Consider the following example. Here we have created a property with name class, which is a reserved keyword. Save this code in a file with name reserved_keywords.coffee student ={ name: “Mohammed” age: 24 phone: 9848022338 class: “X” } console.log key+”::”+value for key,value of student Open the command prompt and compile the .coffee file as shown below. c:> coffee -c reserved_keywords.coffee On compiling, it gives you the following JavaScript. Here you can observe that the CoffeeScript compiler wrapped the keyword class with double quotes on behalf of us. // Generated by CoffeeScript 1.10.0 (function() { var key, student, value; student = { name: “Mohammed”, age: 24, phone: 9848022338, “class”: “X” }; for (key in student) { value = student[key]; console.log(key + “::” + value); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee array_of_objects.coffee On executing, the CoffeeScript file produces the following output. name::Mohammed age::24 phone::9848022338 class::X Print Page Previous Next Advertisements ”;
CoffeeScript – Classes and Inheritance ”; Previous Next JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using objects and their prototypes. Every object have their own prototype and they inherit functions and properties from their prototypes. Since the prototype is also an object, it also has its own prototype. Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and confusing for novice users. Classes in CoffeeScript Addressing to this problem, CoffeeScript provides a basic structure known as class which is built using the JavaScript”s prototypes. You can define a class in CoffeeScript using the class keyword as shown below. class Class_Name Example Consider the following example, here we have created a class named Student using the keyword class. class Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); Instantiating a class We can instantiate a class using the new operator just like other object oriented programming languages as shown below. new Class_Name You can instantiate the above created (Student) class using the new operator as shown below. class Student new Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); new Student; Defining a Constructor A constructor is a function that is invoked when we instantiate a class, its main purpose is to initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a function with name constructor as shown below. class Student constructor: (name)-> @name = name In here, we have defined a constructor and assigned the local variable name to the instance variable. The @ operator is an alias to the this keyword, it is used to point the instance variables of a class. If we place @ before an argument of the constructor, then it will be set as an instance variable automatically. Therefore, the above code can be written simply as shown below − class Student constructor: (@name)-> Example Here is an example of a constructor in CoffeeScript. Save it in a file with the name constructor_example.coffee #Defining a class class Student constructor: (@name)-> #instantiating a class by passing a string to constructor student = new Student(“Mohammed”); console.log “the name of the student is :”+student.name Compiling the code Open command prompt and compile the above example as shown below. c:>coffee -c constructor_example.coffee On executing the above command it will produce the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { function Student(name) { this.name = name; } return Student; })(); student = new Student(“Mohammed”); console.log(“The name of the student is :”+student.name); }).call(this); Executing the Code Run the above example by executing the following command on the command prompt. coffee constructor_example.coffee On running, the above example gives you the following output. The name of the student is :Mohammed Instance Properties Same as in objects, we can also have properties within a class. And these are known as instance properties. Example Consider the following example. In here, we have created variables (name, age) and a function (message()) within the class and accessed them using its object. Save this example in a file named instance_properties_example.coffee #Defining a class class Student name=”Ravi” age=24 message: -> “Hello “+name+” how are you” #instantiating a class by passing a string to constructor student = new Student(); console.log student.message() On compiling, the above code generates the following output. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { var age, name; function Student() {} name = “Ravi”; age = 24; Student.prototype.message = function() { return “Hello ” + name + ” how are you”; }; return Student; })(); student = new Student(); console.log(student.message()); }).call(this); Static Properties We can define static properties in the class. The scope of the static properties is restricted within the class and we create static functions using the this keyword or its alias @ symbol and we have to access these properties using the class name as Class_Name.property. Example In the following example, we have created a static function named message. and accessed it. Save it in a file with the name static_properties_example.coffee. #Defining a class class Student @message:(name) -> “Hello “+name+” how are you” console.log Student.message(“Raju”) Open the command prompt and compile the above CoffeeScript file using the following command. c:>coffee -c static_properties_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student; Student = (function() { function Student() {} Student.message = function(name) { return “Hello ” + name + ” how are you”; }; return Student; })(); console.log(Student.message(“Raju”)); }).call(this); Execute the above coffeeScript in command prompt as shown below. c:>coffee static_properties_example.coffee On executing, the above example gives you the following output. Hello Raju how are you Inheritance In CoffeeScript, we can inherit the properties of one class in another class using extends keyword. Example Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely Add and My_class. We inherited the properties of class named Add in the class My_class, and accessed them using the extends keyword. #Defining a class class Add a=20;b=30 addition:-> console.log “Sum of the two numbers is :”+(a+b) class My_class extends Add my_class = new My_class() my_class.addition() CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create instances, the parent class”s constructor is invoked until we override it. We can invoke the constructor of the parent class from the subclass, using the super() keyword as shown in the example given below. #Defining a class class Add constructor:(@a,@b) -> addition:=> console.log “Sum of the two numbers is :”+(@a+@b) class Mul extends Add constructor:(@a,@b) -> super(@a,@b) multiplication:-> console.log “Product of the two numbers is :”+(@a*@b) mul = new Mul(10,20) mul.addition() mul.multiplication() Dynamic Classes CoffeeScript uses prototypal inheritance to automatically inherit all the instance properties of a class. This ensures that classes are dynamic;
CoffeeScript – Ajax
CoffeeScript – Ajax ”; Previous Next AJAX is a web development technique for creating interactive web applications. AJAX stands for Asynchronous JavaScript and XML. It is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java Script. Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and JavaScript for dynamic content display. Conventional web applications transmit information to and from the server using synchronous requests. It means you fill out a form, hit submit, and get directed to a new page with new information from the server. With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server. XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background. In general, we use jQuery to work with Ajax. Following is an example of Ajax and jQuery <html> <head> <title>The jQuery Example</title> <script type = “text/javascript” src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script> <script type = “text/javascript” language = “javascript”> $(document).ready(function() { $(“#driver”).click(function(event){ $(”#stage”).load(”/jquery/result.html”); }); }); </script> </head> <body> <p>Click on the button to load /jquery/result.html file −</p> <div id = “stage” style = “background-color:cc0;”> STAGE </div> <input type = “button” id = “driver” value = “Load Data” /> </body> </html> Here load() initiates an Ajax request to the specified URL /coffeescript/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming that our /jquery/result.html file has just one HTML line − <h1>THIS IS RESULT…</h1> When you click the given button, then result.html file gets loaded. CoffeeScript with Ajax We can rewrite the above example using CoffeeScript as shown below. <html> <head> <title>The jQuery Example</title> <script type = “text/javascript” src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script> <script src=”http://coffeescript.org/extras/coffee-script.js”></script> <script type=”text/coffeescript”> $(document).ready -> $(”#driver”).click (event) -> $(”#stage”).load ”/jquery/result.html” return return </script> </head> <body> <p>Click on the button to load /jquery/result.html file -</p> <div id = “stage” style = “background-color:cc0;”> STAGE </div> <input type = “button” id = “driver” value = “Load Data” /> </body> </html> Print Page Previous Next Advertisements ”;
CoffeeScript – Arrays
CoffeeScript – Arrays ”; Previous Next The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Syntax To create an array, we have to instantiate it using the new operator as shown below. array = new (element1, element2,….elementN) The Array() constructor accepts the list of string or integer types. We can also specify the length of the array by passing a single integer to its constructor. We can also define an array by simply providing the list of its elements in the square braces ([ ]) as shown below. array = [element1, element2, ……elementN] Example Following is an example of defining an array in CoffeeScript. Save this code in a file with name array_example.coffee student = [“Rahman”,”Ramu”,”Ravi”,”Robert”] Open the command prompt and compile the .coffee file as shown below. c:> coffee -c array_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var student; student = [“Rahman”, “Ramu”, “Ravi”, “Robert”]; }).call(this); New line instead of comma We can also remove the comma (,) between the elements of an array by creating each element in a new line by maintaining proper indentation as shown below. student = [ “Rahman” “Ramu” “Ravi” “Robert” ] Comprehensions over arrays We can retrieve the values of an array using comprehensions. Example The following example demonstrates the retrieval of elements of an array using comprehensions. Save this code in a file with name array_comprehensions.coffee students = [ “Rahman”, “Ramu”, “Ravi”, “Robert” ] console.log student for student in students Open the command prompt and compile the .coffee file as shown below. c:> coffee -c array_comprehensions.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var i, len, student, students; students = [“Rahman”, “Ramu”, “Ravi”, “Robert”]; for (i = 0, len = students.length; i − len; i++) { student = students[i]; console.log(student); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee array_comprehensions.coffee On executing, the CoffeeScript file produces the following output. Rahman Ramu Ravi Robert Unlike the Arrays in other programming languages the arrays in CoffeeScript can have multiple types of data i.e. both string and numericals. Example Here is an example of a CoffeeScript array holding multiple types of data. students = [ “Rahman”, “Ramu”, “Ravi”, “Robert”,21 ] Print Page Previous Next Advertisements ”;