/

A Quick Reference Guide to Modern JavaScript Syntax

A Quick Reference Guide to Modern JavaScript Syntax

Code samples often showcase the latest JavaScript features that may sometimes be mistaken for framework-specific features. This is particularly common with frameworks like React, which emphasize a modern approach to JavaScript.

This blog post aims to provide clarity regarding these features, especially for those transitioning from pre-ES6 JavaScript or starting from scratch. The goal is to help you identify which constructs are inherent to JavaScript and which ones are specific to a framework. Rather than delving into detailed explanations, I will provide pointers for those who wish to learn more.

Arrow Functions

Arrow functions have the following syntax:

1
2
3
const myFunction = () => {
//...
}

This differs slightly from regular functions:

1
2
3
const myFunction = function() {
//...
}

The parentheses can hold parameters, just like regular functions. Sometimes, the brackets are omitted entirely when the function contains just one statement. This results in an implicit return value, eliminating the need for the “return” keyword:

1
const myFunction = i => 3 * i

More on Arrow Functions

The Spread Operator

To clone an array, you can use the spread operator:

1
const c = [...a]

You can also add items to an array using the spread operator:

1
const c = [...a, 2, 'test']

The spread operator can also be used with objects:

1
const newObj = { ...oldObj } //shallow clone an object

More on the Spread Operator

Destructuring Assignments

You can extract specific properties from an object using the following syntax:

1
2
3
4
5
6
7
8
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 54 //made up
}

const { firstName: name, age } = person

Now, you will have two constant values: name and age.

This syntax also works with arrays:

1
2
const a = [1,2,3,4,5]
[first, second, , , fifth] = a

Template Literals

If you encounter strings enclosed in backticks, they are template literals:

1
const str = `test`

Within template literals, you can include variables and execute JavaScript code using ${...} placeholders:

1
2
const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y'}`

Additionally, template literals allow you to span strings over multiple lines:

1
2
3
4
5
const string3 = `Hey
this

string
is awesome!`

tags: [“JavaScript”, “modern JavaScript”, “arrow functions”, “spread operator”, “destructuring assignments”, “template literals”]