The More JavaScript Changes...

..the more it stays the same.

It’s clear I love dynamic languages. I like metaprogramming. I like DRY code. I hate repeating myself (at least when I write code—I repeat myself a lot in person). Objective-C and JavaScript are both dynamic languages and those are the two langs I’ve written produced the most open source code with.

I also like reliable and fast languages. That’s why, although they’re dynamic, I don’t favor Ruby or Python. Python is the better of the two, but I still can’t justify creating the type of web services I write in Python.

That was all setup for the following: Just as Swift is less dynamic than Objective-C, new JavaScript is less dynamic than old JavaScript. Examples:

  • import|export syntax vs. CommonJS
  • More types and implementations of type systems

Static analysis in the language itself isn’t the only reason we’ve gotten less dynamic. Build time tools such as Browserify, static analysis via ESLint, type checking via Flow and several other tools have given us greater safety at the expense of the former wild west freedom.

While I strongly dislike giving up dynamism, I have a much stronger dislike for unDRY (WET?) code. There are a couple recent additions to JavaScript that require a little more thought up front but result in DRYer, safer (and after some re-training of your team) more expressive code. I’m talking about object shorthand syntax and computed property names. Technically computed property names have a duality between safety and danger, but that’s why I love JS.

Object shorthand syntax reduces errors and reader’s overhead by taken advantage of that fact keys and the variables assigned to them should be the same anyway. I’ve always done it that way and viewed variance from that as evidence of not having thoroughly evaluated the why and how of semantics in your application. This syntax is especially valuable in React components, where passing props is common:

1
2
3
4
5
({ dimensions, mappings }) =>
<Component
dimensions
mappings
/>

vs.

1
2
3
4
5
({ dimensionz, mappingz }) =>
<Component
dimensions={dimensionz}
mappings={mappingz}
/>

No joke, I’ve seen plenty of code where the variables were just as arbitrarily named differently from the keys.

Computed property names allow one to (dangerous but powerful skill) dynamically create method names on an object while declaring the object or (safe skill) use constants to name your methods while declaring the object. We’ve always been able to do the following:

1
2
3
4
const mappings = { }
mappings[SOME_CONSTANT] = '<3'
mappings['time_' + Date.now()] = new Date
explode(mappings)

but now we can do either of the following

1
2
3
4
explode({
[SOME_CONSTANT] : '<3',
['time_' + Date.now()] : new Date
})

New safety, but also new power depending on which aspect of computed properties you focus on!

The more JavaScript changes, the more it stays the same I guess.