JavaScript – Slightly more like Ruby – Fat Arrows



JavaScript – Slightly more like Ruby – Fat Arrows

0 0


javascript-is-like-ruby

Talk about how JavaScript is becoming more like Ruby

On Github treyhunner / javascript-is-like-ruby

JavaScript

Slightly more like Ruby

Trey Hunner / @treyhunner

My name is Trey. I do front-end web development and I only know enough Ruby to be dangerous. I'm going to show you some new JavaScript features that you can start using today to make your JavaScript code a little more readable.

ECMAScript History

Edition Release Date Browser Support a.k.a. 3 Dec. 1999 All ES3 5 Dec. 2009 IE 9, FF 4, Chrome 7 ES5 6 June 2015 Not supported yet ES2015 ECMAScript is the language specification that JavaScript is based on. In this presentation I'm going to show off features that were added in ECMAScript 6, also known as ECMAScript 2015. I will be going a little quickly, so you probably won't catch everything but hopefully you'll learn something new. ECMAScript 6 isn't supported by browsers, but you **can** start using it today...

Use next generation JavaScript, today.

You just need to use Babel. Babel allows you to compile your ES6 code down to ES5 code, which is understood by all modern web browsers. This is a pre-compilation process, which is kind of like the pre-compilation step necessary for using something like CoffeeScript.

Fat Arrows

people.each do |person|
  puts person.name
end
            

people.forEach(person => {
  console.log(person.name);
});
            

Our first new feature is fat arrows. Fat arrows are a new shortened function syntax. Here, as you can see, we've lost the parenthesis around our single argument and we've lost the word function.

Fat Arrows

  users.select {|u| u.is_active}.map(&:name).sort
            

  users.filter(u => u.isActive).map(u => u.name).sort();
            

Fat arrow functions have an even shorter syntax. Here in addition to losing the parenthesis and the word function, we've also lost the curly braces and the return statement. In addition to being easier on the eyes, fat arrow functions inherit the "this" binding of their outer scope. For anyone who has wrestled with JavaScript function binding, that's a really big deal.

Template Strings

date = Time.now
puts "The year is #{date.year}"
            
let date = new Date();
console.log(`The year is ${date.getFullYear()}`);
            

With Template strings you can now do string interpolation in JavaScript. You create template strings using backticks and they act kind of like Ruby's double-quoted strings. Remember that these backticks notate strings. This is not executing commands like backticks do in Ruby.

Template Strings

poem = 'Programming is fun
Except for syntax errors
Missing curly brace'
            
let poem = `Programming is fun
Except for syntax errors
Missing curly brace`;
            

Template strings also allow you to make multi-line strings, the same way all strings work in Ruby.

Classes

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end
  def to_s
    "(#{@x}, #{@y})"
  end
end
            

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return `(${this.x}, ${this.y})`;
  }
}
            

JavaScript now has a class notation which is somewhat similar to the one used by CoffeeScript. Of course no class implementation is complete without a good foot gun. So JavaScript also supports...

Subclasses

class ColorPoint < Point
  def initialize(x, y, color)
    super(x, y)
    @color = color
  end
  def to_s
    "#{super()} in #{@color}"
  end
end
            

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y);
    this.color = color;
  }
  toString() {
    return `${super.toString()} in ${this.color}`;
  }
}
            

Inheritance! So we can use extends to inherit classes and super to call methods in a parent class. Under the hood, this is equivalent to the prototype inheritance which is already supported by JavaScript.

Rest

def say(phrase, *folks)
  folks.each{|folk| puts "#{folk} said \"#{phrase}\""}
end
            

function say(phrase, ...folks) {
  folks.forEach(folk => console.log(`${folk} said "${phrase}"`));
}
            

The *rest* operator is kind of like Ruby's splat operator. When defining a function, we can use the rest operator (notated by three dots) to capture the rest of our function arguments.

Spread

people = ["Bigelow", "Quil", "Trady Blix", "Lara"]
shout("hello world", *people)
            

people = ["Bigelow", "Quil", "Trady Blix", "Lara"];
shout("hello world", ...people);
            

The spread operator is also like the splat operator. When calling a function, we can use the spread operator to place an array of items into *separate* arguments in a function call.

Combine Arrays

first = [1, 2]
second = [3, 4]
combined = first + second
            
var first = [1, 2];
var second = [3, 4];
var combined = [...first, ...second];
            

You can also use the spread operator to unpack one array inside of another array. This allows us to combine arrays easily. So in this example `combined` would be the array `[1, 2, 3, 4]`.

Default Arguments

def greet(name = 'there')
  puts "Hello #{name}!"
end
          

function greet(name='there') {
  console.log(`Hello ${name}!`);
}
          

JavaScript functions can now have default argument values. This **does not** mean JavaScript has keyword arguments. It doesn't. These are just default values for positional arguments.

Array Destructuring

x, y = [1, 2]
            

[x, y] = [1, 2];
            

With array destructuring, you can unpack arrays into multiple variables. You can also use this for multiple assignment and for swapping variables.

Object Destructuring

emoji = {category: "people", char: "😁", name: "smile"}
character, name = emoji.values_at(:char, :name)
            

let emoji = {category: "people", char: "😁", name: "smile"};
let {name, char: character} = emoji;
            

There's also an object destructuring syntax. This is a little bit awkward in Ruby but this is probably also considered to be a code smell in the Ruby world. Temporary variables are probably a little more common JavaScript, so this can actually be a pretty useful feature.

Go Forth and Babel

Learn ES2015: https://babeljs.io/docs/learn-es2015/

Try it out: http://babeljs.io/repl

If you write JavaScript and you're not already sold on a JavaScript pre-processor like CoffeeScript, I think you should seriously consider Babel. If you're interested in learning more about Babel or trying it out right from your web browser, you should really check out the Babel website.

Final

Trey Hunner / @treyhunner

Web consultant available for hire http://truthful.technology

Any questions?