I’ve been programming Javascript a long time, and so it was with some surprise that I came across a piece of syntax that I’d not seen before, despite it having been around since Node 4, which was released in September 2015.
The syntax I am referring to is called Object literal shorthand methods, and it’s a companion to the better known Object literal shorthand properties feature that was introduced at the same time.
Most Javascript programmers know you can do this:
const hello = 'world'
const obj = { hello }console.log(obj.hello === 'world') // ==> true
console.log(Object.keys(obj)) // ==> ['hello']
console.log(typeof obj.hello) // ==> 'string'
And also
const hello = name => {
console.log('hello', name)
}
const obj = { hello }obj.hello('world') // ==> 'hello world'
console.log(Object.keys(obj)) // ==> ['hello']
console.log(typeof obj.hello) // ==> 'function'
But what was new to me, for reasons I really can not fully explain as it seems so obvious, is that you can also do this:
const obj = {
hello(name) {
console.log('hello', name)
}
}obj.hello('world') // ==> 'hello world'
console.log(Object.keys(obj)) // ==> ['hello']
console.log(typeof obj.hello) // ==> 'function'
This means you can define a simple object by writing:
const obj = {
title: 'My useful object',
hello(name) {
return `Hello ${name}.`
}
}
It’s a useful shorthand for when, for example, you want to define a readable Stream
, such as:
const { Readable } = require('stream')const inStream = new Readable({
read(size) {
// invoked when the stream is being read
}
})
Or a writable Stream
:
const { Writable } = require('stream')const outStream = new Writable({
write(chunk, encoding, next) {
console.log(chunk.toString(encoding))
next()
}
})
Sure, you could easily also define that same Stream
by:
const { Writable } = require('stream')function write(chunk, encoding, next) {
console.log(chunk.toString(encoding))
next()
}const outStream = new Writable({ write })
But that’s just a little bit ugly, especially if your write
function is only ever going to be defined once when you set up the Stream
.
Conclusion
The lesson here is that, no matter how long you’ve been using a programming language, there will always be something about that language you’ve never seen before. And once you’ve seen it you’ll wonder how you could possibly have not known that.
Links and related articles
- I came across this syntax while reading Samer Buna’s excellent article Node.js Streams: Everything you need to know. If streams confuse you then his article can help fix that.
- Computed Property Names FTW! — How cool are computed property names?
- See also: Imposter Syndrome. It’s real, and everyone feels like an idiot sometimes.
—
Like this but not a subscriber? You can support the author by joining via davesag.medium.com.