SlideShare une entreprise Scribd logo
1  sur  26
Aniruddha Chakrabarti
AVP and Solution Lead, Digital Practice, Mphasis
ani.c@outlook.com | linkedin.com/in/aniruddhac
Agenda
• What is CoffeeScript
• Who uses CoffeeScript, History of CoffeeScript
• Syntax & Lexical Structure
• Improvements in Syntax & Lexical Structure over plain JavaScript
• Control Structures (if, for)
• CoffeeScript Functions / Arrow Function, Improvements in Function
• Object related Improvements
• Class
What is CoffeeScript
• CoffeeScript is a little language that compiles into JavaScript.
• CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.
• The golden rule of CoffeeScript is: "It's just JavaScript".
• The code compiles one-to-one into the equivalent JS, and there is no
interpretation at runtime.
• The compiled output is readable and pretty-printed, will work in every JavaScript
runtime, and tends to run as fast or faster than the equivalent handwritten
JavaScript.
• Any existing JavaScript library could be used seamlessly from CoffeeScript (and
vice-versa).
What is CoffeeScript (Cont’d)
• CoffeeScript is a programming language that transcompiles to JavaScript.
• Adds syntactic sugar inspired by Ruby, Python and Haskell in an effort to enhance
JavaScript's brevity and readability.
• Specific additional features include list comprehension, pattern matching, lambda
function/expression, Class statements etc.
• The language has a relatively large following[citation needed] in the Ruby
community. CoffeeScript support is included in Ruby on Rails version 3.1
• EcmaScript 6 (future version of JavaScript) is influenced by CoffeScript and has
borrowed many features.
• In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future
of JavaScript.
• Microsoft introduced TypeScript which is a superset of JavaScript and which
transcompiles to JavaScript in 2012.
Who uses CoffeeScript
• On September 13, 2012, Dropbox announced that their browser-side codebase
has been rewritten from JavaScript to CoffeeScript
• GitHub's internal style guide says "write new JS in CoffeeScript", and their Atom
text editor is also written in the language.
• ECMAScript 6 (ECMAScript 2015 / ECMAScript Harmony) borrows arrow
function, function parameter improvements, class syntax and other features from
CoffeeScript
• In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future
of JavaScript.
• Microsoft’s TypeScript approach is similar to CoffeeScript. TypeScript also
transcompiles to pure JavaScript, similar to CoffeeScript.
History of CoffeeScript
• December 13, 2009 - Jeremy Ashkenas (also the creator of Backbone.js and
Underscore.js JavaScript Library) made the first Git commit of CoffeeScript with
the comment: "initial commit of the mystery language" - The compiler was written
in Ruby.
• December 24, 2009 - Ashkenas made the first tagged and documented release,
0.1.0.
• February 21, 2010 - Ashkenas committed version 0.5, which replaced the Ruby
compiler with a self-hosting version in pure CoffeeScript. By that time the project
had attracted several other contributors on GitHub, and was receiving over 300
page hits per day.
• December 24, 2010 - Ashkenas announced the release of stable 1.0.0 to Hacker
News, the site where the project was announced for the first time.
Syntax / Lexical Structure
• CoffeeScript uses significant whitespace / indentation to delimit blocks of code
(similar to Python), instead of curly braces { }.
JavaScript:
var x = 10
if(x == 10){
console.log("x is 10");
}
else{
console.log("x is not 10");
}
CoffeeScript:
x = 10
if x == 10
alert "x is 10"
else
alert "x is not 10"
Python:
x = 10
if x==10:
print("x is 10")
else:
print("x is not 10")
• No need to use ; to terminate expressions ending the line will do just as well
• although semicolons can still be used to fit multiple expressions onto a single line.
str = "Hello" # no ; and the end
num = 2
bool = true
Syntax / Lexical Structure
• No need to use parentheses to invoke a function if you're passing arguments. The
implicit call wraps forward to the end of the line or block expression.
work() # for functions without parameters parentheses is
# required while invoking
alert "hello from CoffeeScript" # no parentheses
alert Math.pow 5,2 # becomes alert(Math.pow(5, 2)); in JS
• No need to use var keyword to declare variables.
x = 10
city = "Minneapolis"
isActive = true # you can also use is, on, yes as true
isMale = false # you can also use not, is not, isn’t, off, no as false
Comments
• Single line comment - # (same as Ruby #, similar as JavaScript // )
name = "PQR" # this is a single line comment
• Multi line comment ### …. ### (same as JavaScript /* ….. */ )
age = 30
### this is
an example of
multiline comment ###
Variables and Scope
• var keyword is not required in CoffeeScript while declaring variables
• In JavsScript if variables within a function (local variables) are not declared with
var, then it’s given global scope.
• CoffeeScript solves this by simply removing global variables. Behind the scenes,
CoffeeScript wraps up scripts with an anonymous function, keeping the local
context, and automatically prefixes all variable assignments with var.
number = 10
str = "Hello"
isFTE = true
Array
• Similar as JavaScript
• arrays can use white space instead of comma separators, although the square
brackets ([]) are still required
# single line syntax exactly same as JS
cities = ['Bangalore',1,true,"Kolkata"]
# multiple line syntax without , however [ ] is required
cities = [
'Bangalore'
1
true
"Kolkata"]
Array slicing / Array of range
• CoffeeScript takes inspiration from Ruby when it comes to array slicing by using
ranges.
• Ranges are created by two numerical values, the first and last positions in the
range, separated by .. or .... If a range isn’t prefixed by anything, CoffeeScript
expands it out into an array:
numbers = [1..5] # same as numbers = [1,2,3,4,5] , includes last number
numbers = [1…5] # same as numbers = [1,2,3,4] , excludes last number
String interpolation
• CoffeeScript brings Ruby style string interpolation to JavaScript.
• Double quotes strings can contain #{} tags, which contain expressions to be
interpolated into the string
var name = "PQR"
var age = 30
alert(name + "is " + age + " years old") # PQR is 30 years old
name = "PQR"
age = 30
alert "#{name} is #{age} years old" # Ruby: puts "#{name} is #{age} years old"
alert "#{name} is # multiline strings without +
#{age} years
old" # PQR is 30 years old
if else
• If/else statements can be written without the use of parentheses and curly
brackets
• as with functions and other block expressions, multi-line conditionals are delimited
by indentation.
• handy postfix form, with the if or unless at the end.
isMale = true
if isMale # parenthesis not required
alert 'Male' # curly brackets not required, line is indented
else
alert 'Female' # curly brackets not required, line is indented
x = 10
alert 'Hello' if x==10 # if appears at the end of the statement
var isMale = true;
if (isMale) {
alert('Male');
} else {
alert('Female');
}
Chained Comparison
• CoffeeScript borrows chained comparisons from Python — making it easy to test if
a value falls within a certain range.
cholesterol = 127
healthy = 200 > cholesterol > 60 # same as healthy = (200 > cholesterol && cholesterol >
60);
alert healthy # true
for loops
• CoffeeScript borrows for syntax from Python and Ruby.
cities = ['kolkata','Bangalore','Chennai']
for city in cities
alert city
cities = ['kolkata','Bangalore','Chennai']
sayHello = (city) -> alert "Hello #{city}“
# Option 1
for city in cities
sayHello city
# Option 2
sayHello city for city in cities # alternate
Object
• Object literals can be specified exactly like JavaScript. However, like with function
invocation, CoffeeScript makes the braces optional.
• Objects can be created using indentation instead of braces, similar to YAML
JS:
employee = { name:"Satya" , desig:"CEO" } # JS object literal syntax
CoffeeScript:
employee = name:"Satya" , desig:"CEO" # braces are optional and so could be removed
employee =
name:"Aniruddha" # Indentation to indicate fields
designation:"AVP" # Indentation to indicate fields
department:"Digital"
alert employee.name # "Aniruddha"
var employee = {
name: "Aniruddha",
designation: "AVP",
department: "Digital"
};
alert(employee.name);
Object (cont’d)
• Nested level object properties could be defined using multiple levels of indentation
employee =
name:"Aniruddha"
designation:"AVP"
department:"Digital" # first level of Indentation
address: # first level of Indentation
city:"Bangalore" # second level of Indentation
state:"Karnataka" # second level of Indentation
alert employee.name # "Aniruddha"
alert employee.address.city # “Bangalore"
var employee = {
name: "Aniruddha",
designation: "AVP",
department: "Digital",
address: {
city: "Bangalore",
state: "Karnataka"
}
};
alert(employee.name);
alert(employee.address.city);
Functions
• CoffeeScript removes the rather verbose function statement, and replaces it with a
thin arrow -> or fat arrow => (arrow functions in ES6 uses fat arrow =>)
• Functions can be one-liners or indented on multiple lines.
• The last expression in the function is implicitly returned. In other words, you don’t
need to use the return statement unless you want to return earlier inside the
function.
func = -> 'Hello' # returns 'Hello'
sayHello = () => alert 'Hello' # empty paran could be removed sayHello = => alert 'Hello'
sayHello() # prompts Hello
square = (x) => x * x # accepts x as argument and returns x * x
alert square 5 # 25
add = (x,y) => x + y # accepts x and y as arguments and returns x + y
alert add 10, 20 # 30
Multiline Functions
• Functions can be indented on multiple lines.
calculate = (a,b,c) ->
x = a+b
y = a-b
x * y * c # same as return x * y * c
alert calculate 5,3,2
Default Parameters
• Functions can be indented on multiple lines.
sayHello = (name="user") -> # multi line
alert "Hello #{name}"
sayHello = (name="user") -> alert "Hello #{name}" #single line
sayHello("Bill") # Hello Bill
sayHello() # Hello user
Class
• JavaScript does not have class. Objects are created directly
• JavaScript uses prototype based inheritance (not class based intehiritance
followed by Java, C++, C#, Python, Ruby)
• CoffeeScript adds class syntax in JavaScript
• Behind the scenes, CoffeeScript is using JavaScript’s native prototype to create classes
adding a bit of syntactic sugar for static property inheritance and context persistence.
class Employee
name:"" #Instance Property
age:0 #Instance Property
emp = new Employee
emp.name = "Bill"
emp.age = 30
alert "#{emp.name} - #{emp.age}" # Bill - 50
Class Constructor
• Similar to Ruby’s initialize or Python’s __init__:
• @ alias could be used instead of this
class Employee
name:"" #Instance Properties
age:0 #Instance Properties
constructor:(name,age) -> #Class Constructor
@name = name #@ is ‘this’ in CoffeeScript, so @name is this.name
@age = age
emp = new Employee('Bill', 30)
alert "#{emp.name} - #{emp.age}" # Bill - 50
Instance Method
• Declared directly in the class, similar to Instance properties
class Employee
name:"" #Instance Properties
age:0 #Instance Properties
constructor:(name,age) -> # Class Constructor
@name = name
@age = age
display:() -> # Instance Method
alert "#{this.name} - #{this.age}"
emp = new Employee('Bill', 30)
emp.display()
Static Method
• Static methods and properties are declared using @
class Employee
name:"" #Instance Properties
age:0 #Instance Properties
constructor:(name,age) -> # Class Constructor
@name = name
@age = age
display:() -> # Instance Method
alert "#{this.name} - #{this.age}"
@retirement_Age:60 # Static Property
@say_Hello:() -> alert @ @retirement_Age # Static Method
emp = new Employee('Bill', 30)
emp.display()
Employee.say_Hello()
Resources
• http://coffeescript.org/
• The Little Book on CoffeeScript by Alex MacCaw (Book)
• Programming in CoffeeScript by by Mark Bates (Book)

Contenu connexe

Tendances

Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008maximgrp
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoMarcus Denker
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scalaStratio
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!scalaconfjp
 
Elixir and Phoenix for Rubyists
Elixir and Phoenix for RubyistsElixir and Phoenix for Rubyists
Elixir and Phoenix for RubyistsBrooklyn Zelenka
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaSynesso
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdasshinolajla
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersDiego Freniche Brito
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object OrientationMichael Heron
 
A (very brief) into to Functional Programming
A (very brief) into to Functional ProgrammingA (very brief) into to Functional Programming
A (very brief) into to Functional ProgrammingBrooklyn Zelenka
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven Efftinge
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 

Tendances (20)

Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
What’s new in java 8
What’s new in java 8What’s new in java 8
What’s new in java 8
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
Elixir and Phoenix for Rubyists
Elixir and Phoenix for RubyistsElixir and Phoenix for Rubyists
Elixir and Phoenix for Rubyists
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas20160520 what youneedtoknowaboutlambdas
20160520 what youneedtoknowaboutlambdas
 
Functional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented ProgrammersFunctional Programming for Busy Object Oriented Programmers
Functional Programming for Busy Object Oriented Programmers
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
A (very brief) into to Functional Programming
A (very brief) into to Functional ProgrammingA (very brief) into to Functional Programming
A (very brief) into to Functional Programming
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
Use the @types, Luke
Use the @types, LukeUse the @types, Luke
Use the @types, Luke
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 

En vedette

Hideitsu Hino
Hideitsu HinoHideitsu Hino
Hideitsu HinoSuurist
 
Public and private APIs: differences and challenges
Public and private APIs: differences and challengesPublic and private APIs: differences and challenges
Public and private APIs: differences and challengesRestlet
 
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索Ryosuke Goto
 
OpenCVを使ったiQONの画像処理の全容
OpenCVを使ったiQONの画像処理の全容OpenCVを使ったiQONの画像処理の全容
OpenCVを使ったiQONの画像処理の全容Kazuki Matsumoto
 
強化学習の汎用化Ros
強化学習の汎用化Ros強化学習の汎用化Ros
強化学習の汎用化RosMasato Nakai
 
DDS and OPC UA Explained
DDS and OPC UA ExplainedDDS and OPC UA Explained
DDS and OPC UA ExplainedAngelo Corsaro
 
iQONを支えるクローラーの裏側
iQONを支えるクローラーの裏側iQONを支えるクローラーの裏側
iQONを支えるクローラーの裏側Takehiro Shiozaki
 

En vedette (9)

Moj odmor-iz-snova
Moj odmor-iz-snovaMoj odmor-iz-snova
Moj odmor-iz-snova
 
Agile testing coach - Agile Trends Floripa
Agile testing coach - Agile Trends FloripaAgile testing coach - Agile Trends Floripa
Agile testing coach - Agile Trends Floripa
 
Hideitsu Hino
Hideitsu HinoHideitsu Hino
Hideitsu Hino
 
Public and private APIs: differences and challenges
Public and private APIs: differences and challengesPublic and private APIs: differences and challenges
Public and private APIs: differences and challenges
 
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索
「もっと可愛いワンピースないの?」ディープラーニングで実現する、いままでにないアイテム検索
 
OpenCVを使ったiQONの画像処理の全容
OpenCVを使ったiQONの画像処理の全容OpenCVを使ったiQONの画像処理の全容
OpenCVを使ったiQONの画像処理の全容
 
強化学習の汎用化Ros
強化学習の汎用化Ros強化学習の汎用化Ros
強化学習の汎用化Ros
 
DDS and OPC UA Explained
DDS and OPC UA ExplainedDDS and OPC UA Explained
DDS and OPC UA Explained
 
iQONを支えるクローラーの裏側
iQONを支えるクローラーの裏側iQONを支えるクローラーの裏側
iQONを支えるクローラーの裏側
 

Similaire à Overview of CoffeeScript

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)jeffz
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScriptStalin Thangaraj
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...HostedbyConfluent
 
JAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxJAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxAchieversITAravind
 
Full Stack Online Course in Marathahalli| AchieversIT
Full Stack Online Course in Marathahalli| AchieversITFull Stack Online Course in Marathahalli| AchieversIT
Full Stack Online Course in Marathahalli| AchieversITAchieversITAravind
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
End to-End CoffeeScript
End to-End CoffeeScriptEnd to-End CoffeeScript
End to-End CoffeeScriptTrevorBurnham
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra Sencha
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with ScalaMohit Jaggi
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Ran Mizrahi
 
CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013Spyros Ioakeimidis
 

Similaire à Overview of CoffeeScript (20)

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
Building Kafka Connectors with Kotlin: A Step-by-Step Guide to Creation and D...
 
Java script basics
Java script basicsJava script basics
Java script basics
 
JAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptxJAVASCRIPT PPT [Autosaved].pptx
JAVASCRIPT PPT [Autosaved].pptx
 
Full Stack Online Course in Marathahalli| AchieversIT
Full Stack Online Course in Marathahalli| AchieversITFull Stack Online Course in Marathahalli| AchieversIT
Full Stack Online Course in Marathahalli| AchieversIT
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
End to-End CoffeeScript
End to-End CoffeeScriptEnd to-End CoffeeScript
End to-End CoffeeScript
 
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 
Javascript
JavascriptJavascript
Javascript
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Variables
VariablesVariables
Variables
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Building DSLs with Scala
Building DSLs with ScalaBuilding DSLs with Scala
Building DSLs with Scala
 
Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)Intro to node.js - Ran Mizrahi (27/8/2014)
Intro to node.js - Ran Mizrahi (27/8/2014)
 
Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)Intro to node.js - Ran Mizrahi (28/8/14)
Intro to node.js - Ran Mizrahi (28/8/14)
 
CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013CoffeeScript - TechTalk 21/10/2013
CoffeeScript - TechTalk 21/10/2013
 

Plus de Aniruddha Chakrabarti

Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Aniruddha Chakrabarti
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skillsAniruddha Chakrabarti
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsAniruddha Chakrabarti
 
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Aniruddha Chakrabarti
 
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)Aniruddha Chakrabarti
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsAniruddha Chakrabarti
 
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTAniruddha Chakrabarti
 

Plus de Aniruddha Chakrabarti (20)

Pinecone Vector Database.pdf
Pinecone Vector Database.pdfPinecone Vector Database.pdf
Pinecone Vector Database.pdf
 
Mphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdfMphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdf
 
Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...
 
Third era of computing
Third era of computingThird era of computing
Third era of computing
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skills
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflows
 
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
 
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows Platforms
 
CoAP - Web Protocol for IoT
CoAP - Web Protocol for IoTCoAP - Web Protocol for IoT
CoAP - Web Protocol for IoT
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
 
Level DB - Quick Cheat Sheet
Level DB - Quick Cheat SheetLevel DB - Quick Cheat Sheet
Level DB - Quick Cheat Sheet
 
Lisp
LispLisp
Lisp
 
memcached Distributed Cache
memcached Distributed Cachememcached Distributed Cache
memcached Distributed Cache
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 
MS-Misys Opics Plus.PDF
MS-Misys Opics Plus.PDFMS-Misys Opics Plus.PDF
MS-Misys Opics Plus.PDF
 

Dernier

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 

Dernier (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 

Overview of CoffeeScript

  • 1. Aniruddha Chakrabarti AVP and Solution Lead, Digital Practice, Mphasis ani.c@outlook.com | linkedin.com/in/aniruddhac
  • 2. Agenda • What is CoffeeScript • Who uses CoffeeScript, History of CoffeeScript • Syntax & Lexical Structure • Improvements in Syntax & Lexical Structure over plain JavaScript • Control Structures (if, for) • CoffeeScript Functions / Arrow Function, Improvements in Function • Object related Improvements • Class
  • 3. What is CoffeeScript • CoffeeScript is a little language that compiles into JavaScript. • CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. • The golden rule of CoffeeScript is: "It's just JavaScript". • The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. • The compiled output is readable and pretty-printed, will work in every JavaScript runtime, and tends to run as fast or faster than the equivalent handwritten JavaScript. • Any existing JavaScript library could be used seamlessly from CoffeeScript (and vice-versa).
  • 4. What is CoffeeScript (Cont’d) • CoffeeScript is a programming language that transcompiles to JavaScript. • Adds syntactic sugar inspired by Ruby, Python and Haskell in an effort to enhance JavaScript's brevity and readability. • Specific additional features include list comprehension, pattern matching, lambda function/expression, Class statements etc. • The language has a relatively large following[citation needed] in the Ruby community. CoffeeScript support is included in Ruby on Rails version 3.1 • EcmaScript 6 (future version of JavaScript) is influenced by CoffeScript and has borrowed many features. • In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future of JavaScript. • Microsoft introduced TypeScript which is a superset of JavaScript and which transcompiles to JavaScript in 2012.
  • 5. Who uses CoffeeScript • On September 13, 2012, Dropbox announced that their browser-side codebase has been rewritten from JavaScript to CoffeeScript • GitHub's internal style guide says "write new JS in CoffeeScript", and their Atom text editor is also written in the language. • ECMAScript 6 (ECMAScript 2015 / ECMAScript Harmony) borrows arrow function, function parameter improvements, class syntax and other features from CoffeeScript • In 2011, Brendan Eich referenced CoffeeScript as an influence on his thoughts about the future of JavaScript. • Microsoft’s TypeScript approach is similar to CoffeeScript. TypeScript also transcompiles to pure JavaScript, similar to CoffeeScript.
  • 6. History of CoffeeScript • December 13, 2009 - Jeremy Ashkenas (also the creator of Backbone.js and Underscore.js JavaScript Library) made the first Git commit of CoffeeScript with the comment: "initial commit of the mystery language" - The compiler was written in Ruby. • December 24, 2009 - Ashkenas made the first tagged and documented release, 0.1.0. • February 21, 2010 - Ashkenas committed version 0.5, which replaced the Ruby compiler with a self-hosting version in pure CoffeeScript. By that time the project had attracted several other contributors on GitHub, and was receiving over 300 page hits per day. • December 24, 2010 - Ashkenas announced the release of stable 1.0.0 to Hacker News, the site where the project was announced for the first time.
  • 7. Syntax / Lexical Structure • CoffeeScript uses significant whitespace / indentation to delimit blocks of code (similar to Python), instead of curly braces { }. JavaScript: var x = 10 if(x == 10){ console.log("x is 10"); } else{ console.log("x is not 10"); } CoffeeScript: x = 10 if x == 10 alert "x is 10" else alert "x is not 10" Python: x = 10 if x==10: print("x is 10") else: print("x is not 10") • No need to use ; to terminate expressions ending the line will do just as well • although semicolons can still be used to fit multiple expressions onto a single line. str = "Hello" # no ; and the end num = 2 bool = true
  • 8. Syntax / Lexical Structure • No need to use parentheses to invoke a function if you're passing arguments. The implicit call wraps forward to the end of the line or block expression. work() # for functions without parameters parentheses is # required while invoking alert "hello from CoffeeScript" # no parentheses alert Math.pow 5,2 # becomes alert(Math.pow(5, 2)); in JS • No need to use var keyword to declare variables. x = 10 city = "Minneapolis" isActive = true # you can also use is, on, yes as true isMale = false # you can also use not, is not, isn’t, off, no as false
  • 9. Comments • Single line comment - # (same as Ruby #, similar as JavaScript // ) name = "PQR" # this is a single line comment • Multi line comment ### …. ### (same as JavaScript /* ….. */ ) age = 30 ### this is an example of multiline comment ###
  • 10. Variables and Scope • var keyword is not required in CoffeeScript while declaring variables • In JavsScript if variables within a function (local variables) are not declared with var, then it’s given global scope. • CoffeeScript solves this by simply removing global variables. Behind the scenes, CoffeeScript wraps up scripts with an anonymous function, keeping the local context, and automatically prefixes all variable assignments with var. number = 10 str = "Hello" isFTE = true
  • 11. Array • Similar as JavaScript • arrays can use white space instead of comma separators, although the square brackets ([]) are still required # single line syntax exactly same as JS cities = ['Bangalore',1,true,"Kolkata"] # multiple line syntax without , however [ ] is required cities = [ 'Bangalore' 1 true "Kolkata"]
  • 12. Array slicing / Array of range • CoffeeScript takes inspiration from Ruby when it comes to array slicing by using ranges. • Ranges are created by two numerical values, the first and last positions in the range, separated by .. or .... If a range isn’t prefixed by anything, CoffeeScript expands it out into an array: numbers = [1..5] # same as numbers = [1,2,3,4,5] , includes last number numbers = [1…5] # same as numbers = [1,2,3,4] , excludes last number
  • 13. String interpolation • CoffeeScript brings Ruby style string interpolation to JavaScript. • Double quotes strings can contain #{} tags, which contain expressions to be interpolated into the string var name = "PQR" var age = 30 alert(name + "is " + age + " years old") # PQR is 30 years old name = "PQR" age = 30 alert "#{name} is #{age} years old" # Ruby: puts "#{name} is #{age} years old" alert "#{name} is # multiline strings without + #{age} years old" # PQR is 30 years old
  • 14. if else • If/else statements can be written without the use of parentheses and curly brackets • as with functions and other block expressions, multi-line conditionals are delimited by indentation. • handy postfix form, with the if or unless at the end. isMale = true if isMale # parenthesis not required alert 'Male' # curly brackets not required, line is indented else alert 'Female' # curly brackets not required, line is indented x = 10 alert 'Hello' if x==10 # if appears at the end of the statement var isMale = true; if (isMale) { alert('Male'); } else { alert('Female'); }
  • 15. Chained Comparison • CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range. cholesterol = 127 healthy = 200 > cholesterol > 60 # same as healthy = (200 > cholesterol && cholesterol > 60); alert healthy # true
  • 16. for loops • CoffeeScript borrows for syntax from Python and Ruby. cities = ['kolkata','Bangalore','Chennai'] for city in cities alert city cities = ['kolkata','Bangalore','Chennai'] sayHello = (city) -> alert "Hello #{city}“ # Option 1 for city in cities sayHello city # Option 2 sayHello city for city in cities # alternate
  • 17. Object • Object literals can be specified exactly like JavaScript. However, like with function invocation, CoffeeScript makes the braces optional. • Objects can be created using indentation instead of braces, similar to YAML JS: employee = { name:"Satya" , desig:"CEO" } # JS object literal syntax CoffeeScript: employee = name:"Satya" , desig:"CEO" # braces are optional and so could be removed employee = name:"Aniruddha" # Indentation to indicate fields designation:"AVP" # Indentation to indicate fields department:"Digital" alert employee.name # "Aniruddha" var employee = { name: "Aniruddha", designation: "AVP", department: "Digital" }; alert(employee.name);
  • 18. Object (cont’d) • Nested level object properties could be defined using multiple levels of indentation employee = name:"Aniruddha" designation:"AVP" department:"Digital" # first level of Indentation address: # first level of Indentation city:"Bangalore" # second level of Indentation state:"Karnataka" # second level of Indentation alert employee.name # "Aniruddha" alert employee.address.city # “Bangalore" var employee = { name: "Aniruddha", designation: "AVP", department: "Digital", address: { city: "Bangalore", state: "Karnataka" } }; alert(employee.name); alert(employee.address.city);
  • 19. Functions • CoffeeScript removes the rather verbose function statement, and replaces it with a thin arrow -> or fat arrow => (arrow functions in ES6 uses fat arrow =>) • Functions can be one-liners or indented on multiple lines. • The last expression in the function is implicitly returned. In other words, you don’t need to use the return statement unless you want to return earlier inside the function. func = -> 'Hello' # returns 'Hello' sayHello = () => alert 'Hello' # empty paran could be removed sayHello = => alert 'Hello' sayHello() # prompts Hello square = (x) => x * x # accepts x as argument and returns x * x alert square 5 # 25 add = (x,y) => x + y # accepts x and y as arguments and returns x + y alert add 10, 20 # 30
  • 20. Multiline Functions • Functions can be indented on multiple lines. calculate = (a,b,c) -> x = a+b y = a-b x * y * c # same as return x * y * c alert calculate 5,3,2
  • 21. Default Parameters • Functions can be indented on multiple lines. sayHello = (name="user") -> # multi line alert "Hello #{name}" sayHello = (name="user") -> alert "Hello #{name}" #single line sayHello("Bill") # Hello Bill sayHello() # Hello user
  • 22. Class • JavaScript does not have class. Objects are created directly • JavaScript uses prototype based inheritance (not class based intehiritance followed by Java, C++, C#, Python, Ruby) • CoffeeScript adds class syntax in JavaScript • Behind the scenes, CoffeeScript is using JavaScript’s native prototype to create classes adding a bit of syntactic sugar for static property inheritance and context persistence. class Employee name:"" #Instance Property age:0 #Instance Property emp = new Employee emp.name = "Bill" emp.age = 30 alert "#{emp.name} - #{emp.age}" # Bill - 50
  • 23. Class Constructor • Similar to Ruby’s initialize or Python’s __init__: • @ alias could be used instead of this class Employee name:"" #Instance Properties age:0 #Instance Properties constructor:(name,age) -> #Class Constructor @name = name #@ is ‘this’ in CoffeeScript, so @name is this.name @age = age emp = new Employee('Bill', 30) alert "#{emp.name} - #{emp.age}" # Bill - 50
  • 24. Instance Method • Declared directly in the class, similar to Instance properties class Employee name:"" #Instance Properties age:0 #Instance Properties constructor:(name,age) -> # Class Constructor @name = name @age = age display:() -> # Instance Method alert "#{this.name} - #{this.age}" emp = new Employee('Bill', 30) emp.display()
  • 25. Static Method • Static methods and properties are declared using @ class Employee name:"" #Instance Properties age:0 #Instance Properties constructor:(name,age) -> # Class Constructor @name = name @age = age display:() -> # Instance Method alert "#{this.name} - #{this.age}" @retirement_Age:60 # Static Property @say_Hello:() -> alert @ @retirement_Age # Static Method emp = new Employee('Bill', 30) emp.display() Employee.say_Hello()
  • 26. Resources • http://coffeescript.org/ • The Little Book on CoffeeScript by Alex MacCaw (Book) • Programming in CoffeeScript by by Mark Bates (Book)