Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Overview of CoffeeScript

452 views

Published on

Overview of CoffeeScript

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Overview of CoffeeScript

  1. 1. Aniruddha Chakrabarti AVP and Solution Lead, Digital Practice, Mphasis ani.c@outlook.com | linkedin.com/in/aniruddhac
  2. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 26. Resources • http://coffeescript.org/ • The Little Book on CoffeeScript by Alex MacCaw (Book) • Programming in CoffeeScript by by Mark Bates (Book)

×