JavaScript is Becoming Pythonic

ECMAScript 2015 and Beyond

Trey Hunner / @treyhunner

Multi-Line Strings


poem = """Programming is fun
Except for syntax errors
Missing curly brace"""
          

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

String Interpolation


from datetime import datetime
date = datetime.now()
print("The year is {date.year}".format(date=date))
          

var date = new Date();
console.log(`The year is ${date.getFullYear()}`);
          

Arrow Function Syntax


numbers = [1, 2, 3, 4]
squares = map(lambda x: x * x, numbers)
          

var numbers = [1, 2, 3, 4];
var squares = numbers.map(x => x * x);
          

Iterable Unpacking


coordinate = (1, 4, 2)
x, y, z = coordinate
						

var coordinate = [1, 4, 2];
var [x, y, z] = coordinate;
						

Spread Operator


import datetime
date_fields = (2015, 6, 12);
date = datetime.date(*date_fields)
						

var dateFields = [2015, 5, 12];
var date = new Date(...dateFields);
						

Capture Remaining Values


numbers = [1, 2, 3, 4]
first, *remaining = numbers
						

var numbers = [1, 2, 3, 4];
var [first, ...remaining] = numbers;
						

Combine Arrays


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

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

Rest Operator


from functools import reduce
def product(*numbers):
    return reduce(lambda x, y: x * y, numbers)
print(product(1, 2, 3, 4))
          

function product(...numbers) {
    return numbers.reduce((x, y) => x * y);
}
console.log(product(1, 2, 3, 4));
          

Default Parameters


from math import pow
def power(number, exponent=2):
    return pow(number, exponent)
					 

function power(number, exponent=2) {
    return Math.power(number, exponent);
}
						

Evaluated at Call-time!


from math import pow
from random import random
# This doesn't work like you'd expect!!
def power(number, exponent=random()):
    return pow(number, exponent)
					 

function power(number, exponent=Math.random()) {
    return Math.power(number, exponent);
}
						

Classes


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return "({x}, {y})".format(x=self.x, y=self.y)
						

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

Sub-Classes


class ColorPoint(Point):
    def __init__(self, x, y, color):
        super().__init__(x, y)
        self.color = color
    def __str__(self):
        return "{super} in color {color}".format(
            super=super().__str__(),
            color=self.color
        )
						

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

Getters & Setters


from math import sqrt
class SmartPoint(Point):
    @property
    def hypotenuse(self):
        return sqrt(self.x ** 2 + self.y ** 2)
    @hypotenuse.setter
    def hypotenuse(self, z):
        # Sily setter example
        self.y = sqrt(z ** 2 - self.x ** 2)
						

class SmartPoint extends Point {
    get hypotenuse() {
        return Math.sqrt(this.x ** 2 + this.y ** 2);
    }
    set hypotenuse(z) {
        // Silly setter example
        this.y = Math.sqrt(z ** 2 - this.x ** 2);
    }
}
						

Using Getters & Setters


point = SmartPoint(3, 4)
print(point.hypotenuse)	# Prints 5.0
point.hypotenuse = 6
print(point)	# Prints (3, 5.196152422706632)
						

var point = new SmartPoint(3, 4);
console.log(point.hypotenuse);	// Prints 5
point.hypotenuse = 6;
console.log(point.toString());	// Prints (3, 5.196152422706632)
						

Decorators


@memoize
def get_divisors(number):
    return big_computation(number)
          

@memoize
function getDivisors(number) {
    return bigComputation(number);
}
          

Modules


import urls
from utils import jsonify, memoize
         

import urls from 'urls.js';
import {jsonify, memoize} from 'utils.js';
          

Browser Compatibility

Use next generation JavaScript, today.

Final

Trey Hunner / @treyhunner

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