A quick reference guide to Modern JavaScript Syntax
By Flavio Copes
A quick reference to modern JavaScript syntax like arrow functions, the spread operator, and destructuring, so you can tell JS apart from framework features.
Many times, code samples use modern JavaScript syntax.
Sometimes those features can be hard to distinguish from framework features. It happens a lot with React for example, which leans on a very “modern” JavaScript style.
This post is a quick recognition guide for syntax you will see in samples. I am not going deep into each feature. I just want you to spot what is regular JavaScript, and what belongs to a framework. For more depth, follow the links.
Arrow functions
Arrow functions have this syntax:
const myFunction = () => {
//...
}
A bit different than regular functions:
const myFunction = function() {
//...
}
The () can host parameters, just like in regular functions. Sometimes the brackets are removed entirely when there’s just one statement in the function, and that’s an implicit return value (no return keyword needed):
const myFunction = i => 3 * i
The spread operator
If you see
const c = [...a]
This statement copies an array.
You can add items to an array as well, using
const c = [...a, 2, 'test']
The ... is called spread operator. You can use it on objects as well:
const newObj = { ...oldObj } //shallow clone an object
Destructuring assignments
You can extract just some properties from an object using this syntax:
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 54 //made up
}
const { firstName: name, age } = person
You will now have two const values name and age.
The syntax also works on arrays:
const a = [1,2,3,4,5]
[first, second, , , fifth] = a
Template literals
If you see strings enclosed in backticks, it’s a template literal:
const str = `test`
Inside this, you can put variables and execute javascript, using ${...} snippets:
const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y'}`
And also, you can span a string over multiple lines:
const string3 = `Hey
this
string
is awesome!`
Optional chaining
If you see ?., that is optional chaining. It stops and returns undefined when the value before it is null or undefined, instead of throwing:
user.address?.city
Nullish coalescing
?? picks the right-hand side only when the left-hand side is null or undefined. Unlike ||, a valid 0 or '' on the left is kept:
const count = value ?? 0
You may also see ??=, which assigns only when the left side is nullish.
Async / await
async functions return a promise. Inside them, await pauses until that promise settles:
const data = await fetch(url)
import / export
ES modules use import and export at the top level of a file:
import { hello } from './hello.js'
export const answer = 42
That is standard JavaScript module syntax, not a framework feature.
Want me to talk about your product? You can sponsor this site.
Related posts about js: