Overview of CoffeeScript

26
Aniruddha Chakrabarti AVP and Solution Lead, Digital Practice, Mphasis [email protected] | linkedin.com/in/ aniruddhac

Transcript of Overview of CoffeeScript

Page 1: Overview of CoffeeScript

Aniruddha ChakrabartiAVP and Solution Lead, Digital Practice, Mphasis

[email protected] | linkedin.com/in/aniruddhac

Page 2: Overview of CoffeeScript

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

Page 3: Overview of CoffeeScript

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

Page 4: Overview of CoffeeScript

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.

Page 5: Overview of CoffeeScript

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.

Page 6: Overview of 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.

Page 7: Overview of CoffeeScript

Syntax / Lexical Structure

• CoffeeScript uses significant whitespace / indentation to delimit blocks of code (similar to Python), instead of curly braces { }.

JavaScript:var x = 10if(x == 10){ console.log("x is 10");}else{ console.log("x is not 10");}

CoffeeScript:x = 10if x == 10 alert "x is 10"else alert "x is not 10"

Python:x = 10if 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 endnum = 2bool = true

Page 8: Overview of CoffeeScript

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 parenthesesalert 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 trueisMale = false # you can also use not, is not, isn’t, off, no as false

Page 9: Overview of CoffeeScript

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 isan example ofmultiline comment ###

Page 10: Overview of CoffeeScript

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 = 10str = "Hello"isFTE = true

Page 11: Overview of CoffeeScript

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 JScities = ['Bangalore',1,true,"Kolkata"]

# multiple line syntax without , however [ ] is requiredcities = [ 'Bangalore' 1 true "Kolkata"]

Page 12: Overview of CoffeeScript

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

Page 13: Overview of CoffeeScript

String interpolation

• CoffeeScript brings Ruby style string interpolation to JavaScript. • Double quotes strings can contain #{} tags, which contain expressions to be

interpolated into the stringvar name = "PQR"var age = 30alert(name + "is " + age + " years old") # PQR is 30 years old

name = "PQR"age = 30alert "#{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

Page 14: Overview of CoffeeScript

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 = trueif isMale # parenthesis not required alert 'Male' # curly brackets not required, line is indentedelse 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');}

Page 15: Overview of CoffeeScript

Chained Comparison

• CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range.

cholesterol = 127healthy = 200 > cholesterol > 60 # same as healthy = (200 > cholesterol && cholesterol > 60);

alert healthy # true

Page 16: Overview of CoffeeScript

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 1for city in cities sayHello city# Option 2sayHello city for city in cities # alternate

Page 17: Overview of CoffeeScript

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

Page 18: Overview of CoffeeScript

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

Page 19: Overview of CoffeeScript

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 * xalert square 5 # 25

add = (x,y) => x + y # accepts x and y as arguments and returns x + yalert add 10, 20 # 30

Page 20: Overview of CoffeeScript

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

Page 21: Overview of CoffeeScript

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 BillsayHello() # Hello user

Page 22: Overview of CoffeeScript

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 Employeeemp.name = "Bill"emp.age = 30alert "#{emp.name} - #{emp.age}" # Bill - 50

Page 23: Overview of CoffeeScript

Class Constructor

• Similar to Ruby’s initialize or Python’s __init__:• @ alias could be used instead of thisclass 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

Page 24: Overview of CoffeeScript

Instance Method

• Declared directly in the class, similar to Instance propertiesclass 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()

Page 25: Overview of CoffeeScript

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

Page 26: Overview of CoffeeScript

Resources

• http://coffeescript.org/• The Little Book on CoffeeScript by Alex MacCaw (Book)• Programming in CoffeeScript by by Mark Bates (Book)