Introduction to CoffeeScript

  • 517 views
Uploaded on

Introduction to CoffeeScript

Introduction to CoffeeScript

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
517
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
9
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. INTRODUCTION TO COFFEESCRIPT Stalin
  • 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 wont 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: NumbersValue 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: StringsStrings 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. VariablesLimitations on variable name: Name can be a word, but it cant 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 operatorsCoffeeScript JavaScript==, is ===!=, isnt !==not !and &&or ||true, yes, on truefalse, no, off false
  • 20. Operators: Existential OperatorsScenario CoffeeScriptHow do we check to see that a alert it exists! if cupsOfCoffee?variable isn’t defined and isn’t null?Set a variable cupsOfCoffee ?= 0to Zero unless previously setOnly call function if it exists (in Ruby vehicle.start_engine?().shift_gear?()“try()” )
  • 21. ExpressionIn 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 switchIn CoffeeScript, Conditional statements can be written without the parenthesis and brackets Multi-line conditionals are delimited by indentation. Ex:CS: if a is 10 and b is 20 alert ‘condition true’JS: if(a === 10 && b === 20) { alert(‘condition true’);}
  • 25. Control flow A handy postfix form, with the if or unless at the endEx: CS: addCaffeine() if not Decaf() addCaffeine() unless Decaf() There is no explicit ternary statement in CoffeeScript. But we can imitate using if then else..Ex: CS: if age < 18 then alert Under age else alert of age
  • 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 linesEx: CS: storeLocations = [ Orlando Winter Park Sanford’ ] Ranges also create arraysEx: CS: range = [1..4] JS: var range = [1, 2, 3, 4]
  • 29. Arrays Numbering array elements starts from 0 SubsetsEx: range = [1..4] # => [1, 2, 3, 4] range[0..2] # => [1, 2, 3] range[1…range.length] # => [2, 3,4] range[1..-1] # => [2, 3, 4]
  • 30. Arrays: Loops forEachEx: CS:storeLocations = [Orlando, Winter Park, Sanford]storeLocations.forEach (location, index) -> alert "Location: #{location}“ for .. in ..Ex:for location in storeLocations alert "Location: #{location}"
  • 31. Arrays: LoopsIn CoffeeScript, loops can be written as expression in shorter form for .. inEx:storeLocations = ("#{loc}, FL" for loc in storeLocations) for .. in .. when # like filterEx: geoLocate(loc) for loc in storeLocations when loc isnt Sanford‘ for .. in .. byEx: numbers = (number for number in [0..12] by 2)
  • 32. Objects Objects are list of keys and values ( hash )Ex: cat = { colour: grey‘, name: Spot‘ } Curly braces are optionalEx: cat = colour: grey‘, name: Spot’ Commas optional, when separated by linesEx: cat = colour: grey‘ name: Spot
  • 33. Objects Must be careful with indentingEx: 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 valueEx: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: CSFunction 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 thatallows us to name our class, set the superclass, assignproperties, and define the constructor.
  • 43. Classes, Inheritance and SuperCoffeeScript JavaScriptclass 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 anypair 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 finallyTry/catch statements are same as JavaScriptEx:try catsAndDogsLivingTogether()catch error print errorfinally 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 CoffeeScriptJavascript CoffeeScriptjQuery(function($) { $ -> function changeTab(e) { changeTab = (e) -> e.preventDefault(); e.preventDefault() $("#tabs li $("#tabs lia.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/