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 ”;

CoffeeScript – Loops

CoffeeScript – Loops ”; Previous Next While coding, you may encounter a situation where you need to execute a block of code over and over again. In such situations, you can use loop statements. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages JavaScript provides while, for and for..in loops. The loops in CoffeeScript are similar to those in JavaScript. while loop and its variants are the only loop constructs in CoffeeScript. Instead of the commonly used for loop, CoffeeScript provides you Comprehensions which are discussed in detail in later chapters. The while loop in CoffeeScript The while loop is the only low-level loop that CoffeeScript provides. It contains a Boolean expression and a block of statements. The while loop executes the specified block of statements repeatedly as long as the given Boolean expression is true. Once the expression becomes false, the loop terminates. Syntax Following is the syntax of the while loop in CoffeeScript. Here, there is no need of the parenthesis to specify the Boolean expression and we have to indent the body of the loop using (consistent number of) whitespaces instead of wrapping it with curly braces. while expression statements to be executed Example The following example demonstrates the usage of while loop in CoffeeScript. Save this code in a file with name while_loop_example.coffee console.log “Starting Loop ” count = 0 while count < 10 console.log “Current Count : ” + count count++; console.log “Set the variable to different value and then try” Open the command prompt and compile the .coffee file as shown below. c:> coffee -c while_loop_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var count; console.log(“Starting Loop “); count = 0; while (count < 10) { console.log(“Current Count : ” + count); count++; } console.log(“Set the variable to different value and then try”); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee while_loop_example.coffee On executing, the CoffeeScript file produces the following output. Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Set the variable to different value and then try Variants of while The While loop in CoffeeScript have two variants namely the until variant and the loop variant. S.No. Loop Type & Description 1 until variant of while The until variant of the while loop contains a Boolean expression and a block of code. The code block of this loop is executed as long as the given Boolean expression is false. 2 loop variant of while The loop variant is equivalent to the while loop with true value (while true). The statements in this loop will be executed repeatedly until we exit the loop using the Break statement. Print Page Previous Next Advertisements ”;

CoffeeScript – Syntax

CoffeeScript – Syntax ”; Previous Next In the previous chapter, we have seen how to install CoffeeScript. In this chapter, let us check out the syntax of CoffeeScript. The syntax of CoffeeScript is more graceful when compared to the syntax of JavaScript. It avoids the troublesome features like curly braces, semicolons, and variable decelerations. CoffeeScript Statements Unlike many other programming languages like C, C&plus;&plus;, and Java, the statements in CoffeeScript do not end with semicolons (;). Instead of that, every new line is considered as a separate statement by the CoffeeScript compiler. Example Here is an example of a CoffeeScript statement. name = “Javed” age = 26 In the same way, we can write two statements in a single line by separating them using semicolon as shown below. name = “Javed”;age = 26 CoffeeScript Variables (No var Keyword) In JavaScript, we declare a variable using the var keyword before creating it, as shown below. var name = “Javed” var age = 20 While creating variables in CoffeeScript, there is no need to declare them using the var keyword. We can directly create a variable just by assigning a value to it as shown below. name = “Javed” age = 20 No Parentheses In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below. myfunction = -> alert “Hello” Still, we have to use parentheses in certain scenarios. While calling functions without parameters, we will use parentheses. For example, if we have a function named my_function in CoffeeScript, then we have to call it as shown below. my_function() In the same way, we can also separate the ambiguous code using parentheses. If you observe the following example, without braces, the result is 2233 and with braces, it will be 45. alert “The result is “+(22+33) No Curly Braces In JavaScript, for the block codes such as functions, loops, and conditional statements, we use curly braces. In CoffeeScript, there is no need to use curly braces. Instead, we have to maintain proper indentations (white spaces) within the body. This is the feature which is inspired from the Python language. Following is an example of a function in CoffeeScript. Here you can observe that instead of curly braces, we have used three whitespaces as indentation to separate the body of the function. myfunction = -> name = “John” alert “Hello”+name CoffeeScript Comments In any programming language, we use comments to write description about the code we have written. These comments are not considered as the part of the programs. The comments in CoffeeScript are similar to the comments of Ruby language. CoffeeScript provides two types of comments as follows − Single-line Comments Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below. # This is the single line comment in CoffeeScript Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments. Multiline Comments Whenever we want to comment more than one line in CoffeeScript (multiple lines), we can do that by wrapping those lines within a pair of triple hash tags as shown below. ### These are the multi line comments in CoffeeScript We can write as many number of lines as we want within the pair of triple hash tags. ### CoffeeScript Reserved keywords A list of all the reserved words in CoffeeScript are given in the following table. They cannot be used as CoffeeScript variables, functions, methods, loop labels, or any object names. case default function var void with const let enum export import native __hasProp __extends __slice __bind __indexOf implements else interface package private protected public static yield true false null this new delete typeof in arguments eval instanceof return throw break continue debugger if else switch for while do try catch finally class extends super undefined then unless until loop of by when and or is isnt not yes no on off Print Page Previous Next Advertisements ”;

CoffeeScript – Comprehensions

CoffeeScript – Comprehensions ”; Previous Next In the previous chapter, we have learnt various loops provided by CoffeeScript, while and its variants. In addition to those, CoffeeScript provides additional loop structures known as comprehensions. These comprehensions replace the for loop in other programming languages, if we add the optional guard clauses and the value of the current array index explicitly. Using comprehensions, we can iterate arrays as well as objects and the comprehensions that iterate arrays are expressions, and we can return them in a function or assign to a variable. S.No. Statement & Description 1 for..in comprehensions The for..in comprehension is the basic form of comprehension in CoffeeScript using this we can iterate the elements of a list or array. 2 for..of comprehensions Just like Arrays CoffeeScriptScript provides a containers to store key-value pairs known as objects. We can iterate objects using the for..of comprehensions provided by CoffeeScript. 3 list comprehensions The list comprehensions in CoffeeScript are used to map an array of objects to another array. Index of comprehensions The list/array of elements have an index which can be used in comprehensions. You can use it in comprehensions using a variable as shown below. for student,i in [element1, element2, element3] Example The following example demonstrates the usage of index of the for…in comprehension in CoffeeScript. Save this code in a file with name for_in_index.coffee for student,i in [”Ram”, ”Mohammed”, ”John”] console.log “The name of the student with id “+i+” is: “+student Open the command prompt and compile the .coffee file as shown below. c:> coffee -c for_in_index.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var i, j, len, ref, student; ref = [”Ram”, ”Mohammed”, ”John”]; for (i = j = 0, len = ref.length; j < len; i = ++j) { student = ref[i]; console.log(“The name of the student with id ” + i + ” is: ” + student); } }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee for_in_index.coffee On executing, the CoffeeScript file produces the following output. The name of the student with id 0 is: Ram The name of the student with id 1 is: Mohammed The name of the student with id 2 is: John Postfix form of comprehensions Just like postfix if and unless, CoffeeScript provides the postfix form of the Comprehensions which comes handy while writing the code. Using this, we can write the for..in comprehension in a single line as shown below. #Postfix for..in comprehension console.log student for student in [”Ram”, ”Mohammed”, ”John”] #postfix for..of comprehension console.log key+”::”+value for key,value of { name: “Mohammed”, age: 24, phone: 9848022338} show example Assigning to a variable The comprehension we use to iterate arrays can be assigned to a variable and also returned by a function. Example Consider the example given below. Here you can observe that we have retrieved the elements of an array using for..in comprehension and assigned this to a variable named names. And we also have a function which returns a comprehension explicitly using the return keyword. Save this code in a file with name example.coffee my_function =-> student = [”Ram”, ”Mohammed”, ”John”] #Assigning comprehension to a variable names = (x for x in student ) console.log “The contents of the variable names are ::”+names #Returning the comprehension return x for x in student console.log “The value returned by the function is “+my_function() Open the command prompt and compile the .coffee file as shown below. c:> coffee -c example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var my_function; my_function = function() { var i, len, names, student, x; student = [”Ram”, ”Mohammed”, ”John”]; names = (function() { var i, len, results; results = []; for (i = 0, len = student.length; i < len; i++) { x = student[i]; results.push(x); } return results; })(); console.log(“The contents of the variable names are ::” + names); for (i = 0, len = student.length; i < len; i++) { x = student[i]; return x; } }; console.log(“The value returned by the function is ” + my_function()); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee example.coffee On executing, the CoffeeScript file produces the following output. The contents of the variable names are ::Ram,Mohammed,John The value returned by the function is Ram The by keyword CoffeeScript provides ranges to define a list of elements. For example, the range [1..10] is equivalent to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] where, every element is incremented by 1. We can also change this increment using the by keyword of comprehensions. Example The following example demonstrates the usage of the by keyword of the for..in comprehension provided by CoffeeScript. Save this code in a file with name by_keyword_example.coffee array = (num for num in [1..10] by 2) console.log array Open the command prompt and compile the .coffee file as shown below. c:> coffee -c by_keyword_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var array, num; array = (function() { var i, results; results = []; for (num = i = 1; i <= 10; num = i += 2) { results.push(num); } return results; })(); console.log(array); }).call(this); Now, open the command prompt again and run the CoffeeScript file as shown below. c:> coffee by_keyword_example.coffee On executing, the CoffeeScript file produces the following output. [ 1, 3, 5, 7, 9 ] Print Page Previous Next Advertisements ”;

CoffeeScript – jQuery

CoffeeScript – jQuery ”; Previous Next jQuery is a fast and concise library/framework built using JavaScript created by John Resig in 2006 with a nice motto − Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. Visit our jQuery tutorial to know about jQuery. We can also use CoffeeScript to work with jQuery. This chapter teaches you how to use CoffeeScript to work with jQuery. Using CoffeeScript with jQuery Though jQuery solves the browser issues, using it with JavaScript which have some bad parts is a bit problematic. Using CoffeeScript instead of JavaScript is a better idea. Keep the following points in mind while converting the to be while using jQuery with CoffeeScript. The $ symbol indicates the jQuery code in our application. Use this to separate the jQuery code from the scripting language as shown below. $(document).ready There is no need of using braces in in CoffeeScript except while calling the functions with parameters and dealing with the ambiguous code and we have to replace the function definition function() with an arrow mark as shown below. $(document).ready -> Remove the unnecessary return statements, since CoffeeScript implicitly returns the tailing statements of a function. Example Following is an JavaScript code where <div> elements are being inserted just before the clicked element − <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() { $(“div”).click(function () { $(this).before(”<div class=”div”></div>” ); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below:</p> <span id = “result”> </span> <div class = “div” style = “background-color:blue;”></div> <div class = “div” style = “background-color:green;”></div> <div class = “div” style = “background-color:red;”></div> </body> </html> Now, we can convert the above code into CoffeeScript code 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 -> $(”div”).click -> $(this).before ”<div class=”div”></div>” return return </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below:</p> <span id = “result”> </span> <div class = “div” style = “background-color:blue;”></div> <div class = “div” style = “background-color:green;”></div> <div class = “div” style = “background-color:red;”></div> </body> </html> On executing, this gives you the following output. What is Callback? Callback is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. For example, a function to read a file may start reading file and return the control to execution environment immidiately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result. Blocking Code Example Create a text file named input.txt having following content Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js which has the following code − var fs = require(“fs”); var data = fs.readFileSync(”input.txt”); console.log(data.toString()); console.log(“Program Ended”); Now run the main.js to see the result − $ node main.js Verify the Output. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Program Ended Non-Blocking Code Example Create a text file named input.txt having following content Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Update main.js file to have following code − var fs = require(“fs”); fs.readFile(”input.txt”, function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); console.log(“Program Ended”); Now run the main.js to see the result − $ node main.js Verify the Output. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! These two examples explain the concept of blocking and non-blocking calls. The first example shows that the program blocks until it reads the file and then only, it proceeds to end the program, whereas in the second example, the program does not wait for file reading but it just proceeded to print “Program Ended”. Thus, a blocking program executes very much in sequence. From programming point of view, its easier to implement the logic but non-blocking programs do not execute in sequence. In case a program needs to use any data to be processed, it should be kept within the same block to make it sequential execution. 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

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 ”;