SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
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
 Itprovides 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              alert 'it exists!' if cupsOfCoffee?
variable isn’t defined and isn’t null?


Set a variable                             cupsOfCoffee ?= 0
to Zero unless previously set


Only call function if it exists (in Ruby   vehicle.start_engine?().shift_gear?()
“try()” )
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                         Animal = (function() {
  constructor: (@name) ->              function Animal(name) {
                                         this.name = name;
 move: (meters) ->                     }
  alert “#{@name} moved #{meters}m." 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) {               changeTab = (e) ->
    e.preventDefault();                   e.preventDefault()
    $("#tabs li                           $("#tabs li
a.active").removeClass("active");      a.active").removeClass("active")
   $(this).addClass("active");            $(@).addClass("active")
}                                       $("#tabs ul li a").click(changeTab)
$("#tabs ul li a").click(changeTab);
});
REFERENCES
       Introduction to CoffeeScript…
References


   http://coffeescript.org/
   http://autotelicum.github.com/Smooth-CoffeeScript/

Weitere ähnliche Inhalte

Was ist angesagt?

Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012xSawyer
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with MooseDave Cross
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Jo Cranford
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder RubyNick Sieger
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesBrandon Satrom
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Rolessartak
 
Introduction to Moose
Introduction to MooseIntroduction to Moose
Introduction to Moosethashaa
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)lichtkind
 
Lessons Learnt in 2009
Lessons Learnt in 2009Lessons Learnt in 2009
Lessons Learnt in 2009pratiknaik
 

Was ist angesagt? (20)

Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Moose
MooseMoose
Moose
 
Evolving Software with Moose
Evolving Software with MooseEvolving Software with Moose
Evolving Software with Moose
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012Less ismorewithcoffeescript webdirectionsfeb2012
Less ismorewithcoffeescript webdirectionsfeb2012
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
JRuby @ Boulder Ruby
JRuby @ Boulder RubyJRuby @ Boulder Ruby
JRuby @ Boulder Ruby
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Coffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotesCoffee scriptisforclosers nonotes
Coffee scriptisforclosers nonotes
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Introduction to Moose
Introduction to MooseIntroduction to Moose
Introduction to Moose
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)P6 OO vs Moose (&Moo)
P6 OO vs Moose (&Moo)
 
Lessons Learnt in 2009
Lessons Learnt in 2009Lessons Learnt in 2009
Lessons Learnt in 2009
 

Andere mochten auch

Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...Axway Appcelerator
 
Happy Programming with CoffeeScript
Happy Programming with CoffeeScriptHappy Programming with CoffeeScript
Happy Programming with CoffeeScriptEddie Kao
 
CoffeeScriptってなんぞ?
CoffeeScriptってなんぞ?CoffeeScriptってなんぞ?
CoffeeScriptってなんぞ?Hayato Mizuno
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Web Development with CoffeeScript and Sass
Web Development with CoffeeScript and SassWeb Development with CoffeeScript and Sass
Web Development with CoffeeScript and SassBrian Hogan
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 

Andere mochten auch (11)

Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
Wynn Netherland: Accelerating Titanium Development with CoffeeScript, Compass...
 
Happy Programming with CoffeeScript
Happy Programming with CoffeeScriptHappy Programming with CoffeeScript
Happy Programming with CoffeeScript
 
CoffeeScriptってなんぞ?
CoffeeScriptってなんぞ?CoffeeScriptってなんぞ?
CoffeeScriptってなんぞ?
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Web Development with CoffeeScript and Sass
Web Development with CoffeeScript and SassWeb Development with CoffeeScript and Sass
Web Development with CoffeeScript and Sass
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 

Ähnlich wie Introduction to CoffeeScript

JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6Nitay Neeman
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014Jose Luis Martínez
 
Coffee script
Coffee scriptCoffee script
Coffee scripttimourian
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of JavascriptUniverse41
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 

Ähnlich wie Introduction to CoffeeScript (20)

Coffeescript slides
Coffeescript slidesCoffeescript slides
Coffeescript slides
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
test
testtest
test
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Getting started with ES6
Getting started with ES6Getting started with ES6
Getting started with ES6
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014Building an aws sdk for Perl - Granada Perl Workshop 2014
Building an aws sdk for Perl - Granada Perl Workshop 2014
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 

Kürzlich hochgeladen

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Kürzlich hochgeladen (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Introduction to CoffeeScript

  • 2. We will discuss about…  CoffeeScript  CoffeeScript in Rails  jQuery with CoffeeScript
  • 3. COFFEESCRIPT It’s just JavaScript
  • 4. CoffeeScript  What is CoffeeScript  Why CoffeeScript  Types, Variables, Operators , Expressions and Statements  Control flow  Arrays, Objects and loops  Functions  Object Orientation  Error handling
  • 5. WHAT IS COFFEESCRIPT….? Introduction to CoffeeScript…
  • 6. 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
  • 7. WHY COFFEESCRIPT…? Introduction to CoffeeScript…
  • 8. 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
  • 9. Why CoffeeScript…? CoffeeScript compiles into JavaScript,  Least amount of code to solve problems  Readable and Understandable  Easy to Maintain
  • 10. TYPES, VARIABLES, OPERATORS, EXPRESSIONS AND STATEMENTS Introduction to CoffeeScript…
  • 11. 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
  • 12. 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
  • 13. 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 }.
  • 14. 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’
  • 15. 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’
  • 16. 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(); }
  • 17. Variables  Itprovides 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
  • 18. 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
  • 19. 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
  • 20. Operators: Existential Operators Scenario CoffeeScript How do we check to see that a alert 'it exists!' if cupsOfCoffee? variable isn’t defined and isn’t null? Set a variable cupsOfCoffee ?= 0 to Zero unless previously set Only call function if it exists (in Ruby vehicle.start_engine?().shift_gear?() “try()” )
  • 21. 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
  • 22. 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.
  • 23. CONTROL FLOWS Introduction to CoffeeScript…
  • 24. 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’); }
  • 25. 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'
  • 26. ARRAYS, OBJECTS AND LOOPS Introduction to CoffeeScript…
  • 27. 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']
  • 28. 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]
  • 29. 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]
  • 30. 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}"
  • 31. 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)
  • 32. 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
  • 33. Objects  Must be careful with indenting Ex: CS: cat = colour: 'grey‘ name: 'Spot‘ JS: cat = { colour: ‘grey’ }; ({ name: ‘Spot’ })
  • 34. 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]}”
  • 35. FUNCTIONS Introduction to CoffeeScript…
  • 36. 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() “
  • 37. 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?"
  • 38. Functions: CS  Function parameters  Function arguments will be placed before -> Ex: show = (message) -> alert message  Optional parameters Ex: show = (message = ‘Default message’) -> alert message
  • 39. Functions: CS Function definition Function calling… coffee = -> coffee() coffee = (message) -> coffee(“Test”) coffee = (message, other) -> coffee(“Test”, 2) Parenthesis optional coffee “Test”, 2
  • 40. 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...)
  • 41. OBJECT ORIENTATIONS Introduction to CoffeeScript…
  • 42. 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.
  • 43. Classes, Inheritance and Super CoffeeScript JavaScript class Animal Animal = (function() { constructor: (@name) -> function Animal(name) { this.name = name; move: (meters) -> } alert “#{@name} moved #{meters}m." Animal.prototype.move = function(meters) { return alert(this.name + (" moved " + meters + "m.")); }; return Animal; })();
  • 44. 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()
  • 45. ERROR HANDLING Introduction to CoffeeScript…
  • 46. Try, catch and finally Try/catch statements are same as JavaScript Ex: try catsAndDogsLivingTogether() catch error print error finally cleanUp()
  • 47. COFFEESCRIPT IN RAILS Introduction to CoffeeScript…
  • 48. 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
  • 49. JQUERY WITH COFFEESCRIPT Introduction to CoffeeScript…
  • 50. jQuery with CoffeeScript Javascript CoffeeScript jQuery(function($) { $ -> function changeTab(e) { changeTab = (e) -> e.preventDefault(); e.preventDefault() $("#tabs li $("#tabs li a.active").removeClass("active"); a.active").removeClass("active") $(this).addClass("active"); $(@).addClass("active") } $("#tabs ul li a").click(changeTab) $("#tabs ul li a").click(changeTab); });
  • 51. REFERENCES Introduction to CoffeeScript…
  • 52. References  http://coffeescript.org/  http://autotelicum.github.com/Smooth-CoffeeScript/