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:
const myFunction = () => {
//...
}
This differs slightly from regular functions:
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:
const myFunction = i => 3 * i
The Spread Operator
To clone an array, you can use the spread operator:
const c = [...a]
You can also add items to an array using the spread operator:
const c = [...a, 2, 'test']
The spread operator can also be used with objects:
const newObj = { ...oldObj } //shallow clone an object
Destructuring Assignments
You can extract specific properties from an object using the following syntax:
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:
const a = [1,2,3,4,5]
[first, second, , , fifth] = a
Template Literals
If you encounter strings enclosed in backticks, they are template literals:
const str = `test`
Within template literals, you can include variables and execute JavaScript code using ${...}
placeholders:
const string = `something ${1 + 2 + 3}`
const string2 = `something ${doSomething() ? 'x' : 'y'}`
Additionally, template literals allow you to span strings over multiple lines:
const string3 = `Hey
this
string
is awesome!`