Introduction to CoffeeScript

52
INTRODUCTION TO COFFEESCRIPT Stalin

description

INTRODUCTION TO COFFEESCRIPTStalinWe will discuss about… CoffeeScript CoffeeScriptin Rails jQuerywith CoffeeScriptCOFFEESCRIPTIt‟s just JavaScriptCoffeeScriptWhat 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…? Coffeescript is a little language that

Transcript of Introduction to CoffeeScript

Page 1: Introduction to CoffeeScript

INTRODUCTION TO COFFEESCRIPT

Stalin

Page 2: Introduction to CoffeeScript

We will discuss about…

CoffeeScript

CoffeeScript in Rails

jQuery with CoffeeScript

Page 3: Introduction to CoffeeScript

COFFEESCRIPTIt’s just JavaScript

Page 4: Introduction to CoffeeScript

CoffeeScript What is CoffeeScript Why CoffeeScript Types, Variables, Operators , Expressions and

Statements Control flow Arrays, Objects and loops Functions Object Orientation Error handling

Page 5: Introduction to CoffeeScript

WHAT IS COFFEESCRIPT….?Introduction to CoffeeScript…

Page 6: 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

Page 7: Introduction to CoffeeScript

WHY COFFEESCRIPT…?Introduction to CoffeeScript…

Page 8: 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

Page 9: Introduction to CoffeeScript

Why CoffeeScript…?

CoffeeScript compiles into JavaScript, Least amount of code to solve problems Readable and Understandable Easy to Maintain

Page 10: Introduction to CoffeeScript

TYPES, VARIABLES, OPERATORS, EXPRESSIONS AND STATEMENTS

Introduction to CoffeeScript…

Page 11: 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

Page 12: Introduction to CoffeeScript

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

Page 13: Introduction to CoffeeScript

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 }.

Page 14: Introduction to CoffeeScript

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’

Page 15: Introduction to CoffeeScript

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’

Page 16: Introduction to CoffeeScript

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(); }

Page 17: Introduction to CoffeeScript

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

Page 18: Introduction to CoffeeScript

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

Page 19: Introduction to CoffeeScript

OperatorsIt supports all the generic arithmetic, logic and unary operators. Apart from that it provides the following new operatorsCoffeeScript JavaScript

==, is ===

!=, isnt !==

not !

and &&

or ||

true, yes, on true

false, no, off false

Page 20: Introduction to CoffeeScript

Operators: Existential OperatorsScenario 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?()

Page 21: Introduction to CoffeeScript

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

Page 22: Introduction to CoffeeScript

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.

Page 23: Introduction to CoffeeScript

CONTROL FLOWSIntroduction to CoffeeScript…

Page 24: 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 switchIn 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’);

}

Page 25: Introduction to CoffeeScript

Control flow

A handy postfix form, with the if or unless at the endEx:

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'

Page 26: Introduction to CoffeeScript

ARRAYS, OBJECTS AND LOOPSIntroduction to CoffeeScript…

Page 27: 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']

Page 28: Introduction to CoffeeScript

Arrays

Commas between elements are optional, whey there are placed in separate linesEx: CS: storeLocations = [ 'Orlando' 'Winter Park' 'Sanford’ ]

Ranges also create arraysEx:

CS: range = [1..4]JS: var range = [1, 2, 3, 4]

Page 29: Introduction to CoffeeScript

Arrays

Numbering array elements starts from 0 SubsetsEx:

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]

Page 30: Introduction to CoffeeScript

Arrays: Loops

forEachEx: CS:storeLocations = ['Orlando', 'Winter Park', 'Sanford']storeLocations.forEach (location, index) -> alert "Location: #{location}“

for .. in .. Ex:for location in storeLocations alert "Location: #{location}"

Page 31: Introduction to CoffeeScript

Arrays: LoopsIn CoffeeScript, loops can be written as expression in shorter form for .. in Ex:storeLocations = ("#{loc}, FL" for loc in storeLocations)

for .. in .. when # like filterEx: geoLocate(loc) for loc in storeLocations when loc isnt 'Sanford‘

for .. in .. byEx: numbers = (number for number in [0..12] by 2)

Page 32: Introduction to CoffeeScript

Objects Objects are list of keys and values ( hash )Ex: cat = { colour: 'grey‘, name: 'Spot‘ }

Curly braces are optionalEx: cat = colour: 'grey‘, name: 'Spot’

Commas optional, when separated by lines Ex: cat =

colour: 'grey‘ name: 'Spot

Page 33: Introduction to CoffeeScript

Objects Must be careful with indenting Ex: CS:

cat = colour: 'grey‘

name: 'Spot‘

JS:cat = { colour: ‘grey’

};({ name: ‘Spot’})

Page 34: Introduction to CoffeeScript

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]}”

Page 35: Introduction to CoffeeScript

FUNCTIONSIntroduction to CoffeeScript…

Page 36: Introduction to CoffeeScript

Functions: JS In JavaScript, we have two ways to create functions

Named functionsEx: function coffee() { return confirm("Ready for some Coffee?"); } Function expressionsEx: var coffee = function() { return confirm("Ready for some Coffee?");}

But both are invoked with “ coffee() “

Page 37: Introduction to CoffeeScript

Functions: CS We use only function expressions 1 tab or 2 space indented -> converts to function(){ Always has the return valueEx:coffee = -> confirm "Ready for some Coffee?"

Page 38: Introduction to CoffeeScript

Functions: CS Function parameters

Function arguments will be placed before ->Ex:show = (message) ->

alert message Optional parameters

Ex: show = (message = ‘Default message’) -> alert message

Page 39: Introduction to CoffeeScript

Functions: CS

Function definition Function calling…

coffee = -> coffee()

coffee = (message) -> coffee(“Test”)

coffee = (message, other) -> coffee(“Test”, 2)

Parenthesis optional coffee “Test”, 2

Page 40: Introduction to CoffeeScript

Functions: CS Splats (For a variable number of arguments)

DefinitionEx: 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...)

Page 41: Introduction to CoffeeScript

OBJECT ORIENTATIONSIntroduction to CoffeeScript…

Page 42: 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.

Page 43: Introduction to CoffeeScript

Classes, Inheritance and SuperCoffeeScript 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;})();

Page 44: Introduction to CoffeeScript

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()

Page 45: Introduction to CoffeeScript

ERROR HANDLINGIntroduction to CoffeeScript…

Page 46: Introduction to CoffeeScript

Try, catch and finally

Try/catch statements are same as JavaScriptEx: try catsAndDogsLivingTogether()catch error print errorfinally cleanUp()

Page 47: Introduction to CoffeeScript

COFFEESCRIPT IN RAILSIntroduction to CoffeeScript…

Page 48: 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

Page 49: Introduction to CoffeeScript

JQUERY WITH COFFEESCRIPTIntroduction to CoffeeScript…

Page 50: Introduction to CoffeeScript

jQuery with CoffeeScriptJavascript 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)

Page 51: Introduction to CoffeeScript

REFERENCESIntroduction to CoffeeScript…