The most modern Javascript I know

a micropost by @bwasti


Javascript has changed drastically since I first learned it. I generally love the new (to me) features.

Below is a contrived example of code that uses a bunch of concepts I just learned. I'm not sure any of this is good practice, but here it is:

class Thing {

  constructor(data) {
    this.data_ = data
    this.show_thing = true
    this.display_loop()
  }

  async display_loop() {
    while (this.show_thing) {

      this.display_thing()

      await new Promise((resolve) => {
        requestAnimationFrame(resolve)
      })
    }
  }
  
  display_thing() {
    const canvas = document.querySelector('#output_canvas')
    // ...
  }
  
  get data() {
    return this.data_
  }

}

const d = new Float32Array(128)
d.fill(11) // fill with the number 11
let t = new Thing(d)

No Semicolons

Wait what the heck? I'm not complaining, though. I'd often forget to type them and now I don't need to care. I still do though. Sometimes.

Classes

Not a bad addition. The prototype stuff was awful.

Async methods

Ok so I guess I can call these from non-async methods but I just can't await on them. Are they even guaranteed to be executed?

Promise creation

Is it just me or is this syntax kinda wonky? I can't offer a better alternative though.

requestAnimationFrame

I guess this is better than setTimeout, but I have no idea how long it'll be until the next frame (unless I google it).

Lambdas

These are great. Mostly because there's no more this vs this BS to deal with. I wish anonymous functions worked this way.

document.querySelector

Basically just $ from JQuery. Dope.

Getters and setters

Coming from C++ this is natural to me and I enjoy the syntactic sugar and safety they provide.

Float32Array

Performance! As someone who works in machine learning I love this.

const

Ok this is a bit weird. The name is constant, but not the underlying data. You can mutate it all you want if it's an object. Bleh.

let

Much better than var. I'm glad I can stop using var. I am now very pretentious and judgemental of code that uses var.

Other stuff not shown

There are now a ton of camera, microphone and even gyroscope APIs that can be accessed directly from Javascript. That's awesome.