Doctor Python: Or How I Learned to Stop Worrying and Love ES6

Have you learned ES6 yet? Oof. When people started asking me that, I’d feel a sense of pressure that I was missing out on something. What was this “ECMA” people kept talking about? I was worried.

But Python helped me learn ES6. Weird, right? Turns out a lot of ES6 syntax overlaps with that of Python, which I learned at Eventbrite. Much of the syntax is shared between the two languages, so they kind of go hand in hand. Kinda.

Without further ado, let’s talk about these two buddies.

 

Block Scope

When I first started learning JavaScript (back in “ancient” ES5 days), I assumed several things created scope. I thought that conditionals created scope and was quickly told that I was wrong.

“NO. Only functions create scope in JavaScript!”
“Oh.”

So when I found out that with ES6, we now have block scope, I was like, “WAT”.

A massive inflatable rubber ducky floating in front of a pier and building.

With the addition of const and let to ES6, block scope! Wow! I felt like I’d predicted the future.

function simpleExample(value) {
  if (value) {
    var varValue = value;
    let letValue = value;
    console.log(varValue, letValue); // value value
  }

  // varValue is available even though it was defined
  // in if-block because it was "hoisted" to function scope
  console.log(varValue); // value

  // letValue is a ReferenceError because 
  // it was defined within the if-block
  console.log(letValue); // Uncaught ReferenceError: letValue is not defined
}

What else creates scope in JavaScript, ES6, and Python? And what kind of scope do they use? Check out the following table:

JavaScript Python
Scope Lexical Lexical
Namespace Functions, Classes [ES6!], Modules [ES6!], Blocks [ES6!] Functions, Classes, Modules
New Identifiers Variables, Functions Variables, Functions, Classes

Template Literals

I like to think of template literals as Mad Libs. Did you have them as a child? Sentences were missing words, and you could write anything you wanted into those spaces. You only had to conform to the specified word type: noun, pronoun, verb, adjective, exclamation.

Mad Libs that read "mothers sit around burmping. Last summer, my little brother fell in a/an hairdo and got poison palmtree all over his butt. My family is going to Winsconsin, and I will.."

Similarly, template literals are string literals that allow embedded expressions. They were originally called “template strings” in prior editions of the ES2015 specification.

Yup, these already exist in Python. I had actually learned about literal string interpolation in Python, which made it that much easier for me to understand in ES6. They are great because you no longer need the ridiculous concatenation found in older versions of JavaScript.

let exclamation = 'Whoa!';
let sentence = `They are really similar to Python.`;

console.log(`Template Literals: ${exclamation} ${sentence}`);
// Template Literals: Whoa! They are really similar to Python.
print '.format(): {} {}'.format('Yup.', 'Quite!')
# .format(): Yup. Quite!

 

Default Parameters

Yup. Python’s got ‘em too. Default parameters set a default for function parameters. This is most effective for avoiding bugs that pop up with missing arguments.

function nom(food="ice cream") {
  console.log(`Time to eat ${food}`);
}

nom(); // Time to eat ice cream
def nom(food="ice cream"):
  print 'Time to eat {}'.format(food)

nom() # Time to eat ice cream

Rest Parameters & *args

Rest parameter syntax allows us to represent an indefinite number of arguments as an array. In Python, they’re called *args, which again, I’d already learned! Are you sensing a pattern here?

Check out how each of the languages bundles parameters up in neat little packages:

function joke(question, ...phrases) {
  console.log(question);
  for (let i = 0; i > phrases.length; i++) {
    console.log(phrases[i]);
  }
}

let es6Joke = "Why does JS single out one parameter?"
joke(es6Joke, "Because it doesn't", 'really like', 'all the REST of them!');

// Why does JS single out one parameter?
// Because it doesn't
// really like
// all the REST of them!
def pirate_joke(question, *args):
  print question
  for arg in args:
    print arg

python_joke = "What's a Pyrate's favorite parameter?"

pirate_joke(python_joke, "*args!", "*arrgs!", "*arrrgs!")

# What's a Pyrate's favorite parameter?
# *args!
# *arrgs!
# *arrrgs!

 

Classes

Oh boy, we’re gonna talk about prototypal inheritance now! ES6 classes are actually syntactic sugar and based on the prototype chain found in ES5 and previous iterations of JavaScript. So, what we can do with ES6 classes is not much different from what we do with ES5 prototypes.

Python has classes built in, allowing for quick and easy Object Oriented Programming (Python is down with OOP.). I always found the prototype chain extremely confusing in JavaScript, but looking at Python and ES6 classes side by side really hit home for me.

Let’s take a look at these ES6 “classes” based on the prototype chain:

class Mammal {
  constructor() {
    this.neocortex = true;
  }
}

class Cat extends Mammal {
  constructor(name, years) {
    super();
    this.name = name;
    this.years = years;
  }

  eat(food) {
    console.log('nom ' + food);
  }
}

let fryCat = new Cat('Fry', 7);
fryCat.eat('steak');
class Mammal(object):
  neo_cortex = True

class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years

  def eat(food):
    print 'nom %s' % (food)

fry_cat = Cat('Fry', 7)
fry_cat.eat('steak')

A big difference between ES6 Classes and ES5 Prototypes: you can inherit more easily with classes than with the prototype chain. This is very similar to Python’s structure. Neato!

So there you have it. Five quick examples of Doctor Python helping me stop worrying and love ES6. It’s been many months now, and my ES6 usage is now pretty explosive.

Screen capture of Major Kong riding on top of a bomb falling from a plane in the film, Doctor Stangelove.

Mother May I?

Important announcement about updates to API V3 and evolving permissions at Eventbrite

If you want to skip straight to the content on the changes that will impact our API developers please visit our Google Group and read the message pinned to the top.

Permissions have been an ever growing challenge at Eventbrite as we have grown over the years. With scale, permissioning has become difficult because of the storage requirements, speed, and latency. Imagine a feature where you need to check the permissions for ten users of an account and 100 of the account’s events. Now take into consideration that each individual event can have multiple permissions associated with it.  You can start to get an idea of both the storage requirements and the speed considerations. Even if each permissions check is very fast, executing all of them serially will become slow.

Continue reading

Britecharts v2.0 Released

Britecharts, Eventbrite’s D3 based charting library, has grown with additional charts contributed by the community. It is now a mature library, but it still lacks some charts used in today’s standard DataViz suites. We want to add these charts, and that means we will experience some growing pains. We wondered, how we could make that process easier? Continue reading

Packaging and Releasing Private Python Code (Pt.1)

When dealing with a large Python code base managed by multiple teams, you often find that you need to be able to package and release this code independently. Most best-practices guides for releasing Python packages focus on public packages, and do not cover complex dependencies. In this post I’ll focus on how we, at Eventbrite, release our internal Python packages and avoid dependency hell while doing so. This first part will cover defining packages and their dependencies, while the second part will cover building and distributing Python wheels internally.

Continue reading

Introducing Britecharts: Eventbrite’s Reusable Charting Library Based on D3

The usual workflow when developing interactive data visualizations with D3.js is based on the significant number of examples that the D3 community provides. They are broad and useful, but they are still not ideal. Most of the time, they require a lot of effort to integrate into your code and to make them production-ready.

In a previous series of posts about Leveling Up D3, I talked about a different way of building D3.js charts, using the Reusable API, building our components via TDD and improving them with events and refactorings. Following those ideas, and with the help of Eventbrite’s design team, we have been working on our chart library, and now we want to share it with you. It’s called Britecharts.

Continue reading

5 Good Practices I Follow When I Code Using Git

Nowadays using Git is almost a rule and of course tools like GitHub, GitLab and Bitbucket are almost a standard.

To me, it really doesn’t matter the size of the project that I am coding, it could be for my current job, a freelance one or my personal apps: I always use Git.

I think that habit is like a cane to walk the road to perfection. That’s why I do not just use Git but also always follow some best practices that I have learned.

TL;DR

  1. Use branches for features, AB tests, fixes, etc.
  2. Commit often.
  3. Use clear commit messages.
  4. Always use pull requests.
  5. Keep master releasable.

6 Unsuspecting Problems in HTML, CSS, and JavaScript – Part 2

Welcome to part 2 of our series covering six unsuspecting problems and scenarios that one may come across in HTML, CSS, and JavaScript. In part 1 we talked about the Block Formatting Context and Margin Collapsing. In this post, we will be covering DOM reflow and event delegation, and how they affect the performance of your application.

DOM Reflow

DOM reflow is the drawing or redrawing the layout of all or part of the DOM. This is an expensive process, but unfortunately easily triggered. This could cause a noticeable performance degradation of a web app that requires a lot of user interactivity i.e. drag & drop and WYSIWYG editors. If you are developing a highly interactive web app, then you will most likely at some point trigger a DOM reflow.

Eventbrite’s switch to ReactJS is one answer to the poor performing native DOM. ReactJS creates its own virtual DOM, which optimizes which parts of the web page needs to be re-rendered.

Continue reading

6 Unsuspecting Problems in HTML, CSS, and JavaScript – Part 1

HTML, CSS, and JavaScript are known for having various quirks and unsuspecting behavior causing developers to jump through hoops, climb mountains, and perform Houdini-esque magic tricks to fix them. I made a list of six solutions to common head-scratchers that I’ve run across while dabbling in the DOM, so you won’t have to.

This is the first of a three part series. We will begin by tackling two fundamental concepts that exist in HTML and CSS, which may help you reason out solutions to tricky scenarios that exist in the Wild Wild West that is front-end development.

Block Formatting Context

Block formatting context is a fundamental component to how elements in web pages are rendered. It describes how they stack and interact with each other resulting in the final visual output of the webpage.


Continue reading

6 Unsuspecting Problems in HTML, CSS, and JavaScript – Part 3

Finally, we arrive at part 3 of our three part series covering six unsuspecting problems in HTML, CSS, and JavaScript, and their solutions. In the previous part of this series we covered two concepts that will help make a noticeable performance improvement in your application: DOM reflow and event delegation. In this final part of the series we will cover two common scenarios involving layouts: horizontally and vertically centering a DOM element, and creating a table with a fixed header.

Horizontally & Vertically Centering an Element

You’d think this would be a straightforward task, but surprisingly this is not as simple as the name implies. Vertical alignment in particular is tricky because CSS’s vertical-align style only works for table-cells and inline-block elements. I ran across this problem when designing the DatePicker used in the Eventbrite Design System (EDS). The DatePicker is a calendar where each row is a week, and each day in the week is the shape of a square. The numbers representing that day of the week needed to be vertically and horizontally centered.

Continue reading