List

CoffeeScript for the Rubyist

CoffeeScript for the Rubyist

by Mark Bates

In the presentation titled "CoffeeScript for the Rubyist," Mark Bates discusses CoffeeScript, a programming language that provides a Ruby-like abstraction on top of JavaScript, particularly within the Rails ecosystem. The talk aims to alleviate fears associated with CoffeeScript and promote its advantages as a front-end coding language that can be as enjoyable as Ruby is for back-end programming.

Key points discussed in the talk include:

  • Introduction to CoffeeScript: Mark introduces CoffeeScript as a small language that compiles down to JavaScript, allowing seamless integration with existing JavaScript environments.
  • Comparison with JavaScript: The differences between CoffeeScript and JavaScript are illustrated through examples, highlighting the enhanced readability and reduced boilerplate.
  • Syntax Differences: CoffeeScript employs an easier and cleaner syntax with no semicolons, fewer parentheses, and a focus on whitespace to define code blocks, which contrasts with JavaScript's more complex structure.
  • Ruby-like Features: Bates emphasizes CoffeeScript’s alignment with Ruby principles, showcasing features such as lambdas, default arguments, and ranges, making CoffeeScript familiar to Ruby developers.
  • Practical Coding Examples: Throughout the talk, several coding examples illustrate the simplicity of CoffeeScript syntax compared to JavaScript. For instance:
    • The use of succinct function definitions with the "stabby arrow".
    • Demonstrations of conditionals and object creation without excessive syntax.
    • The use of ranges and string interpolation akin to Ruby.
  • Enhanced Readability: The discussion emphasizes how CoffeeScript's concise syntax improves code readability and maintainability, making it easier for developers to manage.
  • Object-Oriented Features: Mark explains how CoffeeScript simplifies object-oriented programming, allowing for inheritance and easier class definitions compared to the verbose nature of JavaScript.
  • Context Binding: A clear explanation of how CoffeeScript handles context binding in callbacks is presented, which resolves common issues faced in JavaScript.

In conclusion, Mark Bates advocates for CoffeeScript as an evolution of JavaScript that enhances the developer experience by making code easier to write, read, and maintain, ultimately encouraging developers to embrace this new tool in their programming arsenal. He invites attendees to explore CoffeeScript as a valuable addition to their programming toolkit, especially for those already familiar with Ruby.

CoffeeScript is taking the world, and particularly the Rails eco system, by storm. This little language has provided an almost Ruby like abstraction onto of JavaScript. CoffeeScript is trying to make writing front end code as much fun as Ruby makes writing backend code.

In this talk we start with the basic concepts of CoffeeScript and move on to the more powerful and fun features of the language. While we're looking at CoffeeScript we'll see how it relates to the Ruby code we write everyday. What do Ruby 1.9 lambdas and CoffeeScript functions have in common? Which of the two languages supports splats, default arguments, and ranges? The answers may surprise you.

Rails Conf 2012

00:00:05.920 do
00:00:25.359 today we're going to talk a little bit about coffeescript i know dhh mentioned it earlier today as one of those things that a lot of people fear i'm hoping we
00:00:32.320 can take some of that fud away today and replace the fud with fun it's an awful pun but we're going to try
00:00:38.719 to do it anyway my name is mark bates i'm a consultant up in boston
00:00:43.760 i'm the author of distributed programming with ruby which came out a few years ago if you don't own it you should
00:00:50.320 because it's a really out of date tech book and who doesn't want one of those i'm also the author of programming in
00:00:56.640 coffeescript which is a really up-to-date tech book and everybody should own one of those um you get both these available on
00:01:02.160 book.markbaits.com um available this is available for pre-order it is available as a rough cut
00:01:07.520 on safari today so feel free and it's coming out being published in about a month's time
00:01:12.560 so before we get started with coffeescript let's have a very very brief history lesson on javascript
00:01:18.400 itself and and kind of how it came into being because its birth is kind of interesting and explains a lot about the quirks
00:01:25.119 that are the language of javascript so meet brandon brennan was a developer for mozilla back
00:01:30.799 in 1995 and he had a little mission he needed to create a little language that would run inside the browser that would
00:01:36.880 allow developers and more in particular himself to change elements on the page interact
00:01:42.720 with the user what have you and he decided he was gonna make this really cool lisp style language
00:01:48.399 and he did he wrote this really cool with style language that no one has ever seen and the reason no one has ever seen
00:01:53.759 it is this man all right this man came into brendan's office one day and said look java is
00:02:00.880 getting really really popular right so we need you to change this cool list language which no one's using anymore
00:02:07.119 into java we need to make it look more like java we're going to give it a stupid name like javascript so people
00:02:12.480 think they're somehow related and become the bane of every developer's existence from that point on oh and we need it in
00:02:18.160 a week and because that require that last those those last couple requirements it needs
00:02:23.760 to look like java sound like java and we need it in a week we end up with this this is javascript
00:02:29.280 this is actually a backbone model in javascript um it looks very similar to java for those who've ever done java
00:02:35.280 it's not a bad language it's cool it's got a little extra verboseness to it that i'm
00:02:40.720 not a particularly big fan of um but it works and it does what we needed to we've all lived with it all these years
00:02:46.239 um but it's time times change things move on so if we fast forward about 15
00:02:52.000 years we meet jeremy jeremy is a developer at a document
00:02:57.200 cloud he's also the lead developer a little project called backbone for those of you just in sarah's talk you know what backbone's all about he also
00:03:03.680 develops the underscore library which is kind of like active support for javascript right and jeremy is sick and
00:03:09.120 tired of writing his backbone models like this he thinks there has to be a better way
00:03:14.239 and there is so he decided he took it under his hands decided he would write coffee script
00:03:20.319 so that same backbone model now looks like this in coffeescript jeremy is a happy man and now i am a happy man and i
00:03:26.720 hope everybody here becomes happy both men and women so what is coffeescript
00:03:33.040 right well copyscript is a little language that compiles down to javascript that's what the website says
00:03:38.080 um it's an accurate description it's not the most interesting description but it's accurate
00:03:43.120 it easily integrates with your current javascript environment and the reason it easily integrates with the current javascript environment is that statement
00:03:49.920 before it compiles down to javascript so if you've thought about using copyskip thought about trying it not sure if
00:03:56.159 you're going to like it you can try it and if you don't like it which you will you can take that compiled javascript
00:04:02.959 and just use that there is zero loss here right you're not losing anything it's not like you say
00:04:08.319 i'm gonna write my api server in node and if i don't like it then i have to rewrite it in ruby right you could
00:04:14.560 say i'm going to try to write my front end and copy script and if i don't like it i can just use the javascript
00:04:19.919 right it's easier to read write maintain refactor these are all wonderful selling
00:04:25.120 points of developers so i'm always a bit interesting why there's so much fun around this
00:04:30.960 right it's a hybrid of ruby and python i'm sure everybody in this room likes ruby i'm not sure everybody in this room
00:04:36.960 likes python but that's okay they only took a little bit of python and a whole lot of ruby to
00:04:42.479 do this and it's incredibly helpful and i'll show what i mean by helpful over the course of these slides
00:04:48.560 so what coffeescript is not it is not magic and it can't do things that javascript
00:04:53.919 can't already do and the big example i always give to about this is method missing right everybody in this room
00:04:59.520 knows what method missing does in ruby i should hope right it's basically how rails works
00:05:05.120 is the core of core of all of rails is built around method missing you can't do method missing in javascript i wish you could but you
00:05:11.520 can't so you can't do method missing in coffeescript it's just impossible um
00:05:17.199 it is limited by what javascript does so this is what dhh was talking about now he actually stole the next two
00:05:22.960 minutes of my speech today and i'm kind of annoyed but he because he did it so much better than i did this march of progress that he
00:05:29.520 talked about people say this to me all the time well i'm happy writing javascript it's fine it works for me why do i need another
00:05:35.199 learn learn another language right and that's fine with me if you really want to be that way personally i think it's
00:05:41.360 kind of a closed-minded opinion a close-minded way to go through life that's what dhh was talking about this morning right that conservative versus
00:05:47.759 kind of liberal attitude towards learning new things right so
00:05:53.039 let's take another quick little history lesson and again dhh stole a little bit of from me here today
00:05:58.720 does anybody in the room know what this is and i'll give you a hint it's not cobalt
00:06:03.759 do you know what it is what is it it's assembly right okay great do you know what this code actually does
00:06:10.160 no i don't know what it does either i stole it from a website and i think it spits out fibonacci numbers
00:06:16.400 um so but don't quote me on that but for a while programs were actually written like this they were also punched in a
00:06:21.680 punch cards and fed into big machines to do it um and people thought this was okay this seemed like a reasonable way
00:06:28.240 to work for the longest time and someone eventually said that's friggin ridiculous
00:06:33.360 so they came up with c i'm skipping a whole generation of languages here by the way um just to make a point but
00:06:39.199 anyways let's see i'm not a c guy i've done a little bit of c but i can look at this and i know what's going on here this is spin out fibonacci numbers
00:06:45.759 much easier to write than this right we can easily write this and this is great and a lot of great programs are
00:06:52.000 written like this today everybody has a phone or computer in this room that has some code like this
00:06:58.240 on their computer or on their phone or some device in their house right and after a while the things went along
00:07:04.000 great and then someone said you know c is nice and all it's got a lot of problems i hate having to write header files it's not really properly
00:07:10.880 object oriented um i can't run it on all these different devices i have to recompile different ways
00:07:16.400 so java was born all right so here's the fibonacci sequence in java
00:07:21.680 you know it's a little more succinct but java itself is also a very verbose language
00:07:27.759 but you can write it once and run it nowhere as the saying goes and this is where i came into the
00:07:33.199 picture in 1998 i learned how to i learned how to write java and i spent many many years writing java too many
00:07:40.319 years writing java and in 2005 i was doing what most good developers do i was drinking with some
00:07:46.240 friends and a friend of mine said have you checked out ruby he said never heard of it what is it he
00:07:52.639 goes well it's a programming language and there's this little framework that's kind of bubbling up the service called rails which looks pretty sweet and i was
00:07:59.280 like well you know i i i know java i've got my jsps my servlets my struts my
00:08:05.199 hibernate my ant builds i've got my ide working i've got hundreds of thousands lines of xml configuration what do i
00:08:11.120 need to learn something new for right it all works it's fantastic this is what
00:08:16.240 dhh was talking and then i looked at ruby and i saw this and i was like well that looks nice
00:08:23.440 damn it what the hell was i thinking and then i wrote my first rails app and it was amazing it sucked but it was
00:08:30.879 amazing um and i was like this really is revolutionary i don't have to write all these xml files i don't have to deal
00:08:36.959 with build scripts everything just works of course back then i had to deal with deploying fcgi
00:08:42.000 but you know it kind of worked most of the time but it was it was much better it was it was a significant
00:08:47.040 uh improvement so back then i could write an app just as well in java as i
00:08:52.160 can a ruby and that excuse me nowadays i couldn't write an app in java to save my life because i've done nothing but ruby since
00:08:58.240 2005. but damn it if ruby doesn't look nicer to work with it's easier to read it's
00:09:03.519 cleaner it's simpler i can debug it easier i can maintain it easier people coming out to a project can look at it
00:09:09.279 know what it's doing easier right it's easier refactor it's just overall a general better way of being
00:09:17.120 and the same goes for coffeescript it's just an evolution of what javascript is it's taking java to ruby
00:09:24.240 and javascript to coffeescript it's just transforming the way you look at these languages it's it's it really is
00:09:30.959 wonderful it's a new way of writing bytecode at the end of the day right so let's actually jump in and start
00:09:36.320 looking at some coffee scripts and uh there's gonna be a lot of code over the next 30 minutes
00:09:42.160 so i will post all these slides later if you can't see all the code but hopefully um the font will be big enough and it'll
00:09:47.600 work so let's start with the sequ the syntax which is the big thing everybody talks about with copyscript and everybody thinks that syntax is copy
00:09:54.560 script and kavascript is a lot more than just syntax but here's an example of a side-by-side
00:09:59.839 comparison of the exact same code right on the left over here we have our javascript ajax jquery function which
00:10:07.040 everybody should be very well familiar with i would imagine in this room and on the right we have the exact same coffeescript equivalent
00:10:13.440 no semicolons no curly braces very few parentheses
00:10:18.800 nice white space so the white space is evident in our javascript and we'll get to that in a minute no extra keywords like functions
00:10:26.160 um overall it's a little simpler a little easier to focus on i look at this code on the right this copy script code
00:10:32.000 my eye is drawn immediately to the actual code and not to all the semicolons and curly braces that are
00:10:37.519 surrounding my code all right so the syntax rules are very simple or pretty much very simple
00:10:44.000 there's no semicolons ever right there's no debate in the coffeescript world as
00:10:49.120 to whether you should have semicolons whether you should not um there's no big long blog posts and hacker news articles
00:10:54.720 and people screaming at each other you put a semicolon in the compiler's gonna kick it out and yell at you and say what
00:10:59.839 the right no curly braces there's a little asterisk nice to that because there are occasional times to use curly braces but
00:11:06.720 when talking about syntax and talked about defining closures and functions curly braces are gone
00:11:13.120 no more function keyword don't need it there's actually a couple other keywords that are gone for example the with keyword is also
00:11:19.519 gone you can't do with which is a horrible thing to do in javascript anyway there's relaxed parentheses rules very
00:11:26.320 similar to ruby's relaxed parentheses rules and it is white space significant formatting and we will get to that in a
00:11:33.519 minute so let's look a little bit at these parentheses rules i said they're relaxed
00:11:39.360 and on the left here we have three different types of functions we're creating and in coffeescript and i'll
00:11:45.279 talk about functions a little more detail in a few minutes but the function in coffeescript is defined with
00:11:50.800 the stabby arrow the dash arrow there so here i'm creating no arg1 it's a function that takes no arguments no arg2
00:11:57.839 is a function that also takes no arguments and with arg down the bottom takes one argument uh into the function
00:12:04.000 so when you're defining a function that has no arguments you need no parentheses it's as simple as that if you're
00:12:09.839 defining a function that needs arguments it requires parentheses pretty simple rules when defining functions the rules
00:12:17.120 when calling functions however get a little messy if you're calling a function that has no
00:12:22.320 arguments you need parentheses if you're calling a function that has arguments you don't need parentheses
00:12:28.959 um i err on the side of parentheses i think just it's a little cleaner i'm anti-seattle-style ruby code
00:12:36.240 so i'm style coffee script code um and it saves a lot of hassle down the line
00:12:41.519 because it's easy to trick the compiler and you're thinking you were doing something you didn't mean to do because you didn't put parentheses in right so
00:12:48.240 if we look at this little code example oh that's the javascript in case you're wondering um here's an example where the
00:12:54.160 parentheses rules got me in trouble right i want to call i want to find a particular dom element in jquery and
00:13:00.240 call the text function on it right if i do the first time if i don't put the parentheses there it's actually going to call the
00:13:06.079 text function on the string as opposed to the jquery object right so in this case the parentheses
00:13:12.720 are kind of required for the order of precedence for the compiler to know what you're supposed to be doing so if you're confused if you're
00:13:19.519 not if you're not sure what to do just put the parentheses in no one's going to yell at you
00:13:25.040 white space i get white space the white space argument a lot for some reason and i don't know why people complain to me
00:13:31.760 they're like i don't want to do significant white space i think it's stupid i don't understand it and to them
00:13:37.120 i ask this question do you write your code like this or like this because if you do you're kind of a
00:13:43.120 douche bag and honestly i don't want to work with you
00:13:48.399 because this is almost impossible to read i mean you can read it but god damn it is so hard and you know
00:13:54.639 and now i want to refactor it and well which thing is part of the block and which one is it's not and where do these
00:14:00.079 curly braces end and i just have no idea what's going on this is not good code
00:14:06.079 it's well written code in that it works but it's not well format it's not nice code and you shouldn't do this to your
00:14:12.240 fellow developers if you're writing your code like this take a minute indent it properly right and when you do indent it
00:14:18.320 properly it's going to look like this and it's going to look nicer to read easier to manage and then if you're going to write this what's wrong with
00:14:24.880 this right this is nicely formatted code as well so copy script is kind of trying to impose
00:14:31.199 a nice development style on you too it's trying to say hey be a better developer be a nicer person in your community
00:14:37.440 make sure you're writing your code in a nicely formatted way and so much so we're going to build it into the language just like python did
00:14:44.800 right so that translates into this just for those who are curious
00:14:50.480 i personally think coffeescript might have been should have been called rubyscript and at some point i think it might have that probably crossed
00:14:55.920 people's minds because it really does looks look and feels so much like ruby that's the point
00:15:01.040 where i've accidentally written languages written stuff in both languages that was incorrect
00:15:08.240 and we'll look at some of these things right first kind of conditionals right so here's
00:15:14.079 how you do conditionals and coffeescript there's no end keyword to it we use just using the uh the signature white space
00:15:21.120 to define when that block of code is is over with we can do inline conditionals just like
00:15:26.240 we can in ruby so do something if true and do something unless true the less key word is there as well and
00:15:32.639 at the end of the day i mean that's just getting compiled down to a bang that unless you know if bang true just like
00:15:37.680 it does in ruby but it's nice to have that it just makes your code a little more readable i think
00:15:43.199 objects and hashes so here's a case where there's that asterisk on my curly braces
00:15:48.399 is coming true so here's a few ways that i can define an object and coffee script right the first is kind of the single
00:15:54.160 line one and i need curly braces there just to eliminate that object or i can do the nice multi-line one
00:16:00.639 which is the second version i have here which is the one i do pretty much all the time
00:16:06.399 because i think it reads nice it's easier to expand and with that you don't need curly braces and you don't need commas
00:16:13.120 right because it's going to use the new lines and the indentation to know what belongs in that object and where it belongs to the object and this is great
00:16:19.680 so that if you're cutting and pasting or you're adding new stuff you don't have to worry about that extra comma
00:16:25.120 at the end or oops i forgot to add a comment to the last line and i've added something underneath it right it's going
00:16:30.160 to stop you from making those kind of very simple boneheaded mistakes that you only realize when you go back to the browser hit refresh
00:16:36.480 and the console starts blowing up right you can also do if statements while building this object right in line so
00:16:43.199 you have to kind of build the object and then do an if statement below it to add something in you can do it as part of that list as you're going down uh
00:16:50.000 vertically here right and then when i'm passing some an object into a function i can do the ruby style of not needing
00:16:56.160 curly braces right i can just kind of pass in the key value pairs as i go i would need curly braces if i wanted
00:17:02.240 multiple sets of objects being passed in just like in ruby and here's the
00:17:08.240 javascript output that you'd expect you see they both both styles the first two styles all look
00:17:13.439 both look identical at the end of the day so it's really how you like to do like i said i like the multi-line object syntax i think it looks really nice
00:17:19.760 really clean saves you a lot of hassle ranges we all know what ranges are in
00:17:25.520 ruby um you can do them in coffee script so on the left you have the coffee script on the right it's
00:17:31.039 javascript output something interesting to note here so i've got a equals a range of one through
00:17:37.520 five and a or b is a range one two five and it builds the appropriate array for
00:17:43.280 me in the javascript but when i do 1 to 100 it actually does an array because it's not going to build
00:17:49.760 this giant each you know this big giant piece of javascript that's going to pump in all the numbers up to a thousand or 100 or whatever it is
00:17:56.160 and for those of you curious as to what number that that that crossover happens when it goes from the a b kind of style
00:18:02.160 to the cd style it's 22. i don't know why i tested it one day
00:18:10.240 why not 42 it's a great question i and i was like well maybe it's the number of characters in the code for the for loop
00:18:15.840 and i was like no now that's a lot more than 22. i have no idea um it just boggles the mind i guess someone
00:18:22.240 arbitrarily picked that number um string interpolation it's not very exciting but it's very very useful in
00:18:28.960 javascript um it gets more interesting a second here and it follows the exact same rules as
00:18:35.360 ruby where the double strings are interpolated and the single strings are literal in the exact same syntax for doing it as
00:18:41.200 well right hair docs great for building large
00:18:46.720 pieces of code or text what have you in this case i'm building a bunch of html
00:18:52.240 and i'm using the triple and to do hairdresser hairdressers either triple double quotes or triple single quotes to
00:18:57.280 do it and then the same style of interpolation there so this is great if you ever built and everybody
00:19:03.200 has done it raise your hand if you've ever built an input tag in javascript okay people have done it now raise your
00:19:09.200 hand if you've ever forgot to escape the single or double quote when you went to concatenate
00:19:15.440 thing yeah exactly what a pain in the ass you don't have to do that anymore this solves that problem so you no longer
00:19:21.360 have to do single quote double quote plus var name plus double quotes single quote et cetera et cetera you can just
00:19:28.160 kind of build a nice little string right in there uh and it saves so much time and this gets output into this
00:19:34.240 rather disgusting mix of html that i would never want to write with all those escapes and the pluses
00:19:39.440 and stuff like that so functions i said we talked a little bit about functions here this is an
00:19:44.720 example of a function uh and coffeescript see we've we're defining a variable p
00:19:50.559 we're setting it equal to this function it's going to take an argument of name and that dash arrow it defines this everything that follows
00:19:57.039 after this it's indented is going to be part of my function so here we're just going to do a console.log and log out
00:20:03.039 hello hello railsconf 2012. um and down here i could have omitted the parentheses when
00:20:09.280 i called that function uh again i put them in because i think for the most part they look nice except for my
00:20:14.640 console.log i never do that for some reason i don't know same thing with put s and ruby never put parentheses around
00:20:19.679 it don't know why here's the javascript output of that so you can see what's happening
00:20:25.760 now when i first started using coffeescript this syntax kind of messed with my mind a little bit and i couldn't figure out
00:20:31.360 i don't know something about it just seemed weird and i was like eventually i came it's like okay well the arrow is pointing at the code that's
00:20:38.400 doing this for me right and then i realized it seemed also seemed very familiar at the exact same time i've seen this
00:20:44.960 syntax somewhere before i couldn't remember where i'd seen the syntax before and then one day it dawned on me
00:20:50.640 it's the ruby one nine syntax for lambdas um just with the the argument list
00:20:56.320 reversed so if you're using the syntax in ruby one nine then you know how to do the syntax and
00:21:02.159 coffee script matter of fact the ruby version is actually more verbose than the coffee script version because you need those extra curly
00:21:08.320 braces in the ruby version right so give me the copy script version anytime
00:21:14.720 default arguments right we love default arguments in ruby everybody uses them rails uses them all
00:21:21.039 over the place we can now use them in coffeescript so here i've got a create element
00:21:26.240 function takes a name and an optional list of attributes and uh it's gonna be set to an empty hash
00:21:32.559 it's pretty pretty nice here's what that javascript ends up looking like it's not rocket science to
00:21:38.400 do that you know that build that if attributes equals null then set the attributes equal to an empty hash it's
00:21:43.520 not rocket science it's just a lot of boilerplate code why would you want to write that when you can write this
00:21:49.360 right make your life better this is all about progress and just moving on
00:21:54.720 splats we can do splats and coffeescript right and uh splatterconf actually use a
00:22:00.080 much nicer syntax it uses the ellipsis so you do first second others or you can
00:22:05.360 do first second etc which just looks really nice to read in your code
00:22:10.880 and then your first and your second parameter is going to come in as expected and the others parameter here
00:22:16.159 is going to be an array containing everything that comes after those first and second arguments just like in in ruby and again javascript doesn't do
00:22:23.280 this for you by default you have to write all of this boilerplate to make that happen
00:22:29.280 right that's a lot of code to do that and it's and that is very difficult to
00:22:35.679 read you talk about bringing on new developers and people say to me well i bring new developers on and they don't
00:22:41.120 know coffeescript how are they going to read that a new developer should be able to read this
00:22:46.960 a new developer might not be able to read this right what is more daunting you know
00:22:52.559 we'll show you this is this more daunting or is this more daunting i think i know which one the four-line
00:22:58.559 one myself i think is easier to read so loops and comprehensions
00:23:04.080 right moving on to some kind of fun little tricks that coffeescript will let you play um
00:23:09.760 this here there's two types of loops in coffeescript there's the four uh the array loop and the object loop
00:23:15.600 um so in copyscript you do four some name in some array and then a bunch of code that gets executed
00:23:21.360 underneath it very similar to a for loop in ruby and for an object you could do four key
00:23:27.440 value of some object and then loop through you know the key value pairs and print them out and if we
00:23:34.240 look at the code that gets produced there this is a very efficient for loop and in javascript and that's the way you're
00:23:39.600 supposed to write your for loops if you're using jqueries each or underscores for each they're not as
00:23:45.200 efficient in what they do than this so i recommend you should use
00:23:50.559 this even if you're writing javascript this style it's just it's a lot of work and this is what i used to have to write in java back in the day and i hated
00:23:57.120 every minute of it and i'd love the each function in uh in ruby and i wish i wish coverscript kind of took that same
00:24:03.200 approach but it doesn't so anyway loops and comprehension so we can do
00:24:09.600 that same kind of if state by the same loop statement on one line by putting whatever it is we want to do
00:24:16.000 before the four call this is this starts getting a little weird like this can get a little tricky it can be cool but also
00:24:23.039 kind of hard to read if you don't do it right so here we're going to log out the number for the number in numbers
00:24:29.760 word number is there a lot but that's the equivalent of what we had in the previous slide so if we look at
00:24:35.840 the javascript that gets outputted here we're just going to loop through all the elements in the numbers and then print
00:24:41.120 them out just we can do it on one line but comprehensions don't stop there they actually let us do
00:24:47.440 kind of conditionals on that same line so here we can say only print out the number when the number is less than or equal to
00:24:53.919 three for the numbers for each number in this number right so now we if we ran
00:24:59.279 this we would get you know one two three printed out to the screen and all this is doing is breaking down
00:25:04.320 that same for loop this time putting a conditional in the middle of the for loop around our code
00:25:10.400 we can also capture the output of that for loop into another object so in this
00:25:16.000 case here i want to say for every number that's less than or equal to three in this array
00:25:21.600 times it by two shove it all into an array and give me back that array as a variable called low numbers
00:25:28.080 all in one line of code all right then i can log it out and that gets put into there so here now it's looping
00:25:34.799 through each one it's created an array called underscore results to hold all this stuff it's doing that check that if
00:25:40.880 check to make sure it validates our condition and if it does it's time to get by two putting it into that results array and then returning that array at
00:25:47.120 the very end um again i find this to be i mean i understand this but i find it to be more
00:25:52.320 daunting than just looking at this classes
00:25:58.240 right now this is where if you went to sarah's talk about backbone things start getting really nice because you can wrap
00:26:04.240 all the stuff she was talking about in really simple easy to use classes and coffeescript
00:26:10.480 these three lines are valid coffeescript the first line being a valid coffeescript class definition
00:26:16.400 with one line i've created a class called employee then another line i create a new instance of that employee and i can
00:26:22.559 start setting attributes on that instance of that class and i'm going to create as many employee classes as i want
00:26:28.320 now javascript doesn't have proper classes it does have the ability for us to create new instances of functions
00:26:35.760 and that's what coffeescript is doing for us it's taking all that boilerplate remember this is that one line of code
00:26:41.919 and it's you know exploded it out into five or six lines of code because that's what you need to do in javascript to do
00:26:48.000 that same thing to mimic that behavior so coffeescript is kind of taking care
00:26:53.919 of all that for us right and we can add some functions on our coffeescript constructor function which will get
00:26:59.919 called every single time you initialize a new object here i got a salary function for a very
00:27:06.400 very well paid developer if there are any recruiters in the room that is the starting number i would take
00:27:12.720 um for a month and then we go from there um but this actually so this slide actually contains
00:27:18.640 one of my favorite one character pieces of job of coffee script there are uh in my mind i think there's like three
00:27:24.720 pieces three single character three single characters you can use in coffee script that make it worth it alone and
00:27:30.880 i'm going to show you the first one uh first of three and it's on this constructor line so this constructor is
00:27:36.320 taking an option an optional options hash right which we've already looked at default arguments we know what
00:27:41.360 that does but this has an at sign in front of it now in ruby we all know what the at sign does right it's an instance
00:27:46.640 variable and in coffeescript it's doing the same thing it's actually replacing me this dot syntax of javascript right so if we
00:27:53.760 look at our salary function we see we're doing at options.salary so it's equivalent of saying this.salary
00:27:59.279 this.options.salary but when we pass it in as part of a function call
00:28:05.360 as part of our argument list when we say at options instead of just options we're actually saying a copy script is set
00:28:11.279 this argument equal to this dot options so in ruby we've all done this we've
00:28:16.880 said you know in our initializer it takes you know attributes hash right and then right below we'll say you know at
00:28:23.440 attributes equals attributes right this is doing that all in one character
00:28:28.880 so if we look at the javascript here um it's a little hard to read because i wanted to get it all on the page for you
00:28:35.200 but what it's doing is this dot options equals options unless the options is null and if the options is null then set
00:28:40.880 it equal to an empty option an empty hash force right so it's actually doing quite a lot of work with that little bit
00:28:46.720 of code but that at that at sign where you pass it in as an argument that in your argument list is so powerful it's the
00:28:52.960 equivalent of doing this dot options equals options really nice way to work there's also another thing on the slide
00:28:58.960 a little operator here this question mark equals which is one of many operators a
00:29:04.080 coffeescript gives you i'm not going to go into operators too much here because there's just so much to talk about but this operator here is going to say
00:29:10.559 if salary does not exist if it's undefined or it's null on the options or sorry if it's just if
00:29:17.279 it's just null on the options hash then set it equal to this value of 250 000
00:29:23.360 right and you would see that when you when you go and look at the slides later you'll see it but it's this big long line right here that's doing all of that
00:29:31.679 we can extend classes so now we have inheritance in our javascript all of a sudden when we use copyscript right so
00:29:38.159 here i've got a manager class that extends employee right i get a constructor and in the case of constructor i'm going
00:29:44.240 to call super the super's got the same exact um rules as ruby does so if i call super
00:29:50.880 it's going to pass in any arguments that are passed into that function by default or i can pass in my own set of arguments
00:29:57.679 to that super call as well and here in the constructor i'm going to set the manager salary to a default to
00:30:03.120 500 000 so now if i just did a manager create a new manager and ran his salary i would
00:30:08.880 see five hundred thousand dollars and here's what that javascript code looks like the font size by the way if you ever
00:30:15.039 notice is shrinking and shrinking on these javascript because they're getting bigger and bigger and bigger
00:30:20.320 so here's a case of i'm going to override the salary you know this is kind of showing that super again where i
00:30:25.679 override the salary function and i call the super salary of you know get the 500 000
00:30:31.200 and then add a 10k bonus to it and that's what that looks like okay bound functions this is one that a
00:30:38.320 lot of new developers to copy script don't quite get um but is my second favorite single character
00:30:46.000 change that that you can make so i'm assuming people here have used ajax
00:30:51.840 before right raise your hand if you've done ajax calls okay great so now ajax is loaded with
00:30:58.080 callbacks right and how many times have you had this you pass in something you make ajax call you pass on a callback
00:31:04.480 and you expect it to you know and then you do this dot blah blah blah and you get back an undefined error does that
00:31:10.480 happen to people before yes it does it's because javascript loses the scope of this and it's a whole
00:31:16.159 big thing uh read yehuda katz's article on it he wrote it last summer fantastic explaining the whole this
00:31:22.880 context i'm not going to get into it because you could do a 45 minute talk on this alone
00:31:28.559 and this is incredibly hard to talk about because you have to keep saying this with quotes every time you do it so
00:31:33.600 people know what the hell this is so in this case in this case we've got a
00:31:39.360 user class here so it's a very simple example user takes a name when you create a new
00:31:44.720 user and we have a say hi function he says hi to that name very simple all right so we're going to create a bob and a mary and we have this log function
00:31:52.000 here and all that does is take a call back and for those of you back in the room it just takes a call back and we're going to log out they're about to
00:31:58.080 execute the callback we run the callback and then we print out that we've executed the callback and then finally
00:32:04.640 we pass in bob's say hi function we pass in mary's say hi function right now what we expect to see is about to execute
00:32:11.200 callback hi hello bob execute a callback um you know hello mary what have you
00:32:16.480 what we actually get is hello undefined for that same reason coffee javascript
00:32:22.240 has lost the context of this when we said hello this dot name it doesn't know what this
00:32:28.720 is anymore it thinks this is that log function um so we gotta we gotta set it
00:32:34.000 right we gotta tell it where to go here so keep your eye on our save function a say hi function here
00:32:39.840 right this is this is where the magic happens this is the problem this is the function we're having problems with this is where we're losing our our context
00:32:46.399 with one single character change booyah we have our context back i'll do that
00:32:52.080 one more time for you as you didn't see it look at the dash arrow
00:32:57.120 it is now a hash rocket or an equal rocket i don't know how you want to describe it in coffeescript a fat arrow
00:33:02.320 is how we how it's actually defined and now if we run that call back we are actually we actually know bob and
00:33:08.559 we know mary and to make this a little cleaner here's that same example just without all the
00:33:14.720 log stuff going on and here's that javascript output and what we can actually see here is it's
00:33:20.799 doing a bunch of fun javascript magic to bind the context of any function that gets passed into
00:33:27.120 this underscore underscore bind function so when when we create a new instance of user it's actually down here it's
00:33:33.120 redefining the say hi function on our user and passing that into and getting
00:33:38.720 that bound version through this underscore underscore bind function it's it's a little bit of magic and a little bit of craziness but
00:33:46.240 you can imagine how nice this gets when all of a sudden these context bugs start disappearing from your code when we were
00:33:51.600 looking at the backbone code that sarah was showing she had a line where she was binding the render function to this
00:33:58.799 um on that class on that on that on her view class and you don't need to do that anymore instead when you're creating the
00:34:04.080 render function you just use a fat arrow and that binding just happens for you automatically
00:34:09.839 so finally one of my one of my favorite features this is the last of the three
00:34:15.280 um single character bits of code that i'm going to show you today
00:34:21.119 is the existential operator it's all very zen let me tell you
00:34:26.800 all right why are we here well that's what the essential operator solves right so here we have if foo question mark
00:34:33.200 right and it's single line firm you know log log foo if foo right so what is that
00:34:38.480 actually doing for us if we look at the javascript output it's actually very simple um it's checking that foo
00:34:43.679 exists it's not undefined and if it is defined it's not null and then it executes what we want to do right this
00:34:50.240 can save your ass on so many levels and makes your code so nice to kind of
00:34:55.839 read and look at and we do it all time in ruby with these question marks but it gets better
00:35:01.599 all right i'm going to pose a question here and i'm sure everybody has done this before who has used the console.log
00:35:06.720 statement before in their code pretty much everybody okay now who has accidentally left the
00:35:14.240 console.log statement in their code on ie okay and what happens when you do that
00:35:21.119 it stops executing it just blows up it doesn't work anymore coffeescript's got your back you can do
00:35:26.800 this console.questionmark.log foo and that is going to check the existence
00:35:32.480 of console first and then call it
00:35:37.520 now don't tell me that's not worth the price for admission right there that's why i love this it's fantastic i've overridden my editor so whenever i do a
00:35:43.280 console.log it always puts a question mark in there for me right and it's all assuming it's just checking the console
00:35:48.400 making sure it exists and then calling it it's going to solve that problem but it gets better
00:35:53.839 it gets better than that we can chain them together we can do all sorts of craziness with this question this one question mark so
00:36:00.400 here if there's a current user and that current user has a first name and that first name is not null
00:36:06.800 then print it out to the screen we can do this all day long we can say if current user question mark mark.firstnamequestionmark.trim
00:36:13.440 isn't an empty string then do this right so now we can deal with these you know objects as if they might exist
00:36:20.320 if they don't don't worry about it copyscript's got our back and here's the code that's generates to do all that
00:36:26.000 it's kind of like the try function that active support offers except i think nicer because it's like try
00:36:32.320 everywhere you put question marks so with that said i'm kind of winding down here a little bit some things i
00:36:38.560 didn't cover i didn't cover scoping security strict mode copy script automatically
00:36:45.599 now when it compiles your code compiles it you strict mode on so you get all sorts of early debugging information and
00:36:52.640 errors right then and there it fixes common mistakes like using triple equals and when you should be
00:36:58.880 using triple equals when people are usually using double equals um operators got also great operators like
00:37:04.960 that question mark equal one i showed you the existential operator there's more the do keyword for when you're doing
00:37:10.240 asynchronous loops it helps keep that context right there for you and there's more there's a whole
00:37:16.160 shitload more and if you're interested i recommend you buy my book programming
00:37:21.359 and coffeescript and follow me on twitter mark bates and that's it here any questions
00:37:29.200 thank you
00:38:27.280 you