Upload
stalin-thangaraj
View
613
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Introduction to CoffeeScript
Citation preview
INTRODUCTION TO COFFEESCRIPT
Stalin
We will discuss about…
CoffeeScript
CoffeeScript in Rails
jQuery with CoffeeScript
COFFEESCRIPT
It’s just JavaScript
CoffeeScript
What is CoffeeScript
Why CoffeeScript
Types, Variables, Operators , Expressions and Statements
Control flow
Arrays, Objects and loops
Functions
Object Orientation
Error handling
WHAT IS COFFEESCRIPT….?
Introduction to CoffeeScript…
What is CoffeeScript…?
Coffee script is a little language that compiles to
JavaScript
The golden rule of the CoffeeScript is: "it is just a
JavaScript".
The code compiles one-to-one into the equivalent
There is no interpretation at run time
WHY COFFEESCRIPT…?
Introduction to CoffeeScript…
Why CoffeeScript…?
CoffeeScript repairs many of the confusing and
cumbersome aspects of JavaScript, while keeping its
underlying flexibility and beauty
It is an attempt to expose the good part of the JavaScript
in a simple way
It won't bother about semicolons and braces
Why CoffeeScript…?
CoffeeScript compiles into JavaScript,
Least amount of code to solve problems
Readable and Understandable
Easy to Maintain
TYPES, VARIABLES, OPERATORS,
EXPRESSIONS AND STATEMENTS
Introduction to CoffeeScript…
Types
In CoffeeScript , every value has a type, which determines the kind of role it can play. There are six basic type of values:
Numbers
Strings
Booleans
Objects
Functions
Undefined values
Basic Types: Numbers
Value of the type number are, numeric values like 123
Fractional numbers are written by using a dot. 9.81
Also supports 'scientific' notation by adding an e,
followed by the exponent of the number: 2.998e8
Basic Types: Strings
Strings are used to represent the text.
Strings are written by enclosing their content in quotes
CoffeeScript implements both single and double quoted
strings.
Double quoted strings can contain interpolated values,
small snippets of code between #{ and }.
Basic Types: Strings
A lengthy string can be folded into multiple lines in the
program but the lines breaks will not be shown in the
output.
Ex:
CS: ‘The string is folded
to more than one line‘
JS: ‘The string is folded to more than one line’
Basic Types: Strings
CoffeeScript has triple quoted strings known as 'heredoc'
to have multiple line strings with line breaks and
alignments.
Ex:
CS: ’’’The string is folded
to more than one line’’’
JS: ‘The string is folded \n to more than one line’
Basic Types: Boolean
In Boolean type we have two values 'true' and 'false‘
'true' can be written as 'on' or 'yes'.
'false' as 'no' or 'off'.
This aliases make the program more easier to read.
Ex:
CS: if paid() and coffee() is on then pour()
JS: if (paid() && coffee() === true) {
pour();
}
Variables
It provides a thing called 'variable' to retrieve and store the value
A variable has a name and it pointing to a value
Assigning a value to a variable name with = operator creates a variable
Declaration is not needed. ‘var’ a is reserved word
Variables
Limitations on variable name:
Name can be a word, but it can't have spaces
Can’t start with digits
$ and _ can be used in names
$_$ is a valid variable name
Operators
It supports all the generic arithmetic, logic and unary operators. Apart
from that it provides the following new operators
CoffeeScript JavaScript
==, is ===
!=, isnt !==
not !
and &&
or ||
true, yes, on true
false, no, off false
Operators: Existential Operators
Scenario CoffeeScript
How do we check to see that a
variable isn’t defined and isn’t null?
alert 'it exists!' if cupsOfCoffee?
Set a variable
to Zero unless previously set
cupsOfCoffee ?= 0
Only call function if it exists (in Ruby
“try()” )
vehicle.start_engine?().shift_gear?()
Expression
In CoffeeScript program, a piece of code that produces a
value is called Expression. Every value is an expression (
such as 12, 'apple').
Ex: i = i + 2
Statements
A program is formed by a sequence of one or more statements.
A statement will have internal components (e.g., expressions).
In CoffeeScript,
Most of the statements end with new line
Also can end with semicolon
If we want to have multiple statements in a same line, we can use semicolons to separate statements.
CONTROL FLOWS
Introduction to CoffeeScript…
Control flow
The control-flow of a language specify the order in which computations are performed.
Already we know the most common control-flow constructions such as if, if/else, unless and switch
In CoffeeScript,
Conditional statements can be written without the parenthesis and brackets
Multi-line conditionals are delimited by indentation. Ex:
CS: if a is 10 and
b is 20
alert ‘condition true’
JS: if(a === 10 && b === 20) {
alert(‘condition true’);
}
Control flow
A handy postfix form, with the if or unless at the end
Ex:
CS:
addCaffeine() if not Decaf()
addCaffeine() unless Decaf()
There is no explicit ternary statement in CoffeeScript. But we can imitate using if then else..
Ex:
CS:
if age < 18 then alert 'Under age' else alert 'of age'
ARRAYS, OBJECTS AND LOOPS
Introduction to CoffeeScript…
Arrays
CoffeeScript provides a special kind of object called
‘Array’. It has a collection of data in it
‘length’ property contains the amount of values in the
array
New arrays can be created using brackets ([ and ])
Ex: storeLocations = ['Orlando', 'Winter Park', 'Sanford']
Arrays
Commas between elements are optional, whey there are placed in separate lines
Ex:
CS: storeLocations = [
'Orlando'
'Winter Park'
'Sanford’
]
Ranges also create arrays
Ex:
CS: range = [1..4]
JS: var range = [1, 2, 3, 4]
Arrays
Numbering array elements starts from 0
Subsets
Ex:
range = [1..4] # => [1, 2, 3, 4]
range[0..2] # => [1, 2, 3]
range[1…range.length] # => [2, 3,4]
range[1..-1] # => [2, 3, 4]
Arrays: Loops
forEach
Ex: CS:
storeLocations = ['Orlando', 'Winter Park', 'Sanford']
storeLocations.forEach (location, index) ->
alert "Location: #{location}“
for .. in ..
Ex:
for location in storeLocations
alert "Location: #{location}"
Arrays: Loops
In CoffeeScript, loops can be written as expression in shorter form
for .. in
Ex:
storeLocations = ("#{loc}, FL" for loc in storeLocations)
for .. in .. when # like filter
Ex: geoLocate(loc) for loc in storeLocations when loc isnt 'Sanford‘
for .. in .. by
Ex: numbers = (number for number in [0..12] by 2)
Objects
Objects are list of keys and values ( hash )
Ex: cat = { colour: 'grey‘, name: 'Spot‘ }
Curly braces are optional
Ex: cat = colour: 'grey‘, name: 'Spot’
Commas optional, when separated by lines
Ex: cat =
colour: 'grey‘
name: 'Spot
Objects Must be careful with indenting
Ex: CS:
cat =
colour: 'grey‘
name: 'Spot‘
JS:
cat = {
colour: ‘grey’
};
({
name: ‘Spot’
})
Objects: Loops for .. of ..
Ex: CS:
mailArchive =
0: ‘(mail number 1)'
1: '(mail number 2)'
2: '(mail number 3)'
for current of mailArchive
alert “Processing e-mail ‘#{current } - #{mailArchive[current]}”
FUNCTIONS
Introduction to CoffeeScript…
Functions: JS
In JavaScript, we have two ways to create functions
Named functions
Ex:
function coffee() {
return confirm("Ready for some Coffee?");
}
Function expressions
Ex:
var coffee = function() {
return confirm("Ready for some Coffee?");
}
But both are invoked with “ coffee() “
Functions: CS
We use only function expressions
1 tab or 2 space indented
-> converts to function(){
Always has the return value
Ex:
coffee = ->
confirm "Ready for some Coffee?"
Functions: CS
Function parameters
Function arguments will be placed before ->
Ex:
show = (message) ->
alert message
Optional parameters
Ex: show = (message = ‘Default message’) ->
alert message
Functions: CS
Function definition Function calling…
coffee = -> coffee()
coffee = (message) -> coffee(“Test”)
coffee = (message, other) ->
coffee(“Test”, 2)
Parenthesis optional coffee “Test”, 2
Functions: CS
Splats (For a variable number of arguments)
Definition
Ex: searchLocations = (brand, cities...) ->
"looking for #{brand} in #{cities.join(',')}"
Invoking
Ex:
a) searchLocations 'Starducks', 'Orlando‘
b) searchLocations 'Starducks', 'Orlando', 'Winter Park‘
c) params = ['Starducks', 'Orlando', 'Winter Park']
searchLocations(params...)
OBJECT ORIENTATIONS
Introduction to CoffeeScript…
Classes, Inheritance and Super
CoffeeScript provides a basic class structure that
allows us to name our class, set the superclass, assign
properties, and define the constructor.
Classes, Inheritance and Super
CoffeeScript JavaScript
class Animal
constructor: (@name) ->
move: (meters) ->
alert “#{@name} moved #{meters}m."
Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.move =
function(meters) {
return alert(this.name + (" moved " +
meters + "m."));
};
return Animal;
})();
Classes, Inheritance and Super The extends operator helps with proper prototype setup, and can be used to create an inheritance chain between any pair of constructor functions.
Ex:
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
horse = new Horse(‘Tommy’)
horse.move()
ERROR HANDLING
Introduction to CoffeeScript…
Try, catch and finally
Try/catch statements are same as JavaScript
Ex:
try
catsAndDogsLivingTogether()
catch error
print error
finally
cleanUp()
COFFEESCRIPT IN RAILS
Introduction to CoffeeScript…
CoffeeScript in Rails
It has been included in Rails 3.1
To change a JavaScript file to a CoffeeScript one
we just have to append .coffee to the file name.
When a CoffeeScript file is requested, it is
processed by the processor provided by
CoffeeScript
JQUERY WITH COFFEESCRIPT
Introduction to CoffeeScript…
jQuery with CoffeeScript
Javascript CoffeeScript
jQuery(function($) {
function changeTab(e) {
e.preventDefault();
$("#tabs li
a.active").removeClass("active");
$(this).addClass("active");
}
$("#tabs ul li a").click(changeTab);
});
$ ->
changeTab = (e) ->
e.preventDefault()
$("#tabs li
a.active").removeClass("active")
$(@).addClass("active")
$("#tabs ul li a").click(changeTab)
REFERENCES
Introduction to CoffeeScript…
References
http://coffeescript.org/
http://autotelicum.github.com/Smooth-CoffeeScript/