When JavaScript Goes ‘Splat’

As a Ruby back-end developer new to JavaScript, I find myself comparing the two languages. JavaScript is a powerful language once you learn to harness it. Ruby can at times seem more intuitive.

Wonky, difficult syntax in a programming language is dreadful. At times, it seems Ruby is less so than JavaScript. Is that the case?

Languages like Ruby abstract away complexity. They allow a developer to think at the logical level and not so much on the syntax. Thereby Ruby’s ‘syntactical sugar’.

Image for post
Image for post
Photo by Patrick Tomasso on Unsplash

A Clever Tool

One of the features of Ruby’s sugar is the splat operator: *. Splat
allows array values to be referenced as a comma separated list. All of the elements in an array can be passed to a method call as individual arguments versus passing in the array itself as a single argument.

When Would I Need This in JavaScript?

When working with Ruby, you can call methods like Array#maxto return the max value of an array.

The max function in JavaScript will also give you the maximum value of an argument list. max is available to Math.It won't, however, return a max value of a single array argument passed (as a Ruby dev might like).

Ok, at least it’s there. What to do, then, to get the maximum value of an array?

Beginning to see why I'd like to splat something.


As happenstance would have it, JavaScript does have a splat operator. I found this after investigating somewhat more verbose ways of passing Math.maxthe elements of an array (i.e. Array.prototype.apply() and Array.prototype.reduce()) But why conform to the Ruby way of naming things? It’s 'spread' in JavaScript.

The syntax is…

Well, it’s that: …. Let’s pass our array identifier to Math.max prepending :

This will give us our max value from the array.

Let’s Wrap

So, max is not a convenient method I can call on an array object.

Truth is, a developer has to get used to doing the same slightly different ways.

Am I ok with that?

Ehh… Guess I have to be :-)

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store