Chris Zetter

Three Small Things you can do in Javascript

I recently started a new job as a platform engineer at Farewill. I knew I would be writing more Javascript than I had done in my last role so wanted to remind myself of the less-used parts of the language that I had forgotten about or just never knew.

I decided to go through The Modern JavaScript Tutorial after finding their section on promises a useful reference. I liked that it thoroughly covered modern Javascript and was written in a way to cover both client and server environments.

Calling Functions on Numbers with Two Dots

In Javascript, you can write the numeric literal 12 in a few ways including 12, 12.0 and even 12. (with a trailing dot).

When reading about numbers I found that 12.toString() is actually a syntax error. The Javascript parser will assume the ‘.’ belongs to the number rather than the function call.

You can instead call a function on a numeric literal by putting brackets around the number or by using two dots after the number.

12.toString() // Throws: SyntaxError: No identifiers allowed directly after numeric literal

(12).toString() // Returns: "12"
12..toString() // Returns: "12"

Using Dynamic Property Names when Defining New Objects

I knew you could use object[keyName] = value to add a dynamic property to an object. What I didn’t know was that you could also set dynamic properties when creating an object by using square brackets.

In this example I’m using a dynamic key to internationalise the key ‘name’.

const getName = (language, name) => {
  const nameKey = language === 'fr' ? 'nom' : 'name'
  return {
    [nameKey]: name
  }
}

This is called computed properties and you can put any expression between the square brackets, not just the name of a variable.

Truncating Arrays by Assigning to Length

Did you know that the length property of arrays is writable? You can use it to truncate an array.

const letters = ['a', 'b', 'c', 'd']
letters.length = 2 // letters is now ['a', 'b']

This feels less special when you know that property setters can be added to your own objects to call functions when a property is changed.

This method of truncation doesn’t work with strings even though they also have a length property. I prefer the slice function rather than setting length since I feel it’s more intention revealing and is defined on strings too.

Excited to be Writing Javascript Again

I get a nice feeling each time I make use of import, arrow functions, string interpolation or anything else that wasn’t available 5 years ago. Without all of these improvements to the language I think I would find Javascript frustrating to use every day.

If you’re learning Javascript or want a refresher The Modern JavaScript Tutorial is a good place to start.

Read more by me, follow me on twitter or subscribe.