With the latest versions of JavaScript, the language has introduced more syntactic sugar. In this article, we’ll look at handy shortcuts that are easy to read from versions of JavaScript new and old. With them, it’ll save us time and make our code easier to read.
In this article, we’ll look at template strings, destructuring assignment, spread operator, exponentials, finding elements in arrays and dynamic keys in objects.
Template Literals
With ES6, we finally have string interpolation and multi-line strings with JavaScript that’s easy to use.
Template strings let us define strings that can have expressions inside and they can have as many lines as we want.
For example, we can write:
const name = 'Joe';
const greeting = `Hi ${name}.`;
Then we can embed the value of name
in our string.
It also works with expressions:
const likeApple = true;
const greeting = `I like ${likeApple ? 'Apple' : 'Orange'}.`;
As we can see, we added the likeApple ? ‘Apple’ : ‘Orange’
expression into our string with the ${}
characters wrapped around the expression.
They can also be multi-line:
const multiLine = `
Foo
Bar
`;
Destructuring Assignment
We can decompose arrays and objects properties easily with the destructuring assignment shorthand.
To destructure arrays, we can write:
const fruits = ['apple', 'orange', 'banana'];
const [apple, orange, banana] = fruits;
To assign 'apple'
to apple
, 'orange'
to orange
and 'banana'
to banana
.
We don’t have to assign every entry to a variable:
const fruits = ['apple', 'orange', 'banana'];
const [apple, orange] = fruits;
In this case, we assign 'apple'
to apple
and 'orange'
to orange
.
We can do the same for objects. For example, we can write:
const obj = {
foo: 1,
bar: 2
};
const {
foo,
bar
} = obj;
To decompose the properties of obj
into variables with the same names as the property names.
To assign them to different variable names, we can write:
const obj = {
foo: 1,
bar: 2
};
const {
foo: a,
bar: b
} = obj;
Then obj.foo
will be assigned to a
and obj.bar
will be assigned to b
.
Spread Operator
We can use the spread operator to merge arrays and objects.
For example, we can write:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
It’s the same as using the concat
method:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = arr1.concat(arr2);
It’s also good for cloning arrays:
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
It can be used anywhere in the array:
const arr1 = [1, 2, 3];
const arr2 = [4, ...arr1, 5, 6];
Since ES2018, we can use it on objects as well:
const {
foo,
bar,
...z
} = {
foo: 1,
bar: 2,
c: 3,
d: 4
};
We’ll get that foo
is 1 and bar
is 2 and z
is {c: 3, d: 4}
.
Check for Mandatory Parameters
Thanks to the default parameter value syntax, we can assign anything to parameters, including dynamic code.
This means that we can call a function to check if the value is passed in and throws an error if it isn’t.
For example, we can write:
const checkValue = () => {
throw new Error('Missing parameter');
}const foo = (val = checkValue()) => val;
Then checkValue
will run when foo
is run.
Array.find
We can use the find
method to search for the first entry that meets the condition that we specify.
For example, we can write:
const people = [{
name: 'Joe',
age: 10
},
{
name: 'Joe',
age: 11
},
{
name: 'Mary',
age: 13
},
]
const joe = people.find(p => p.name === 'Joe');
Then we get that the value of joe
is:
{name: "Joe", age: 10}
which is the first 'Joe'
in the people
array.
Dynamic Object Keys
We can write: obj.foo
as obj['foo']
. This is handy for handling objects with dynamic keys.
It also works with object keys that are invalid as identifier names. For example, we can write:
obj['Jane Smith']
Since Jane Smith
has a space inside it, it’s an invalid identifier, but we can still have a property name with spaces if we use a string.
With ES6 or later, we can define objects with dynamic property names:
const prop = 'prop';
const obj = {
[prop]: 'foo'
}
Property names can be strings or Symbols. Symbols are objects which its own use if for identifiers for functions.
For example, we can write:
const fn = Symbol('fn');
const obj = {
[fn]() {
return 'foo';
}
}
Exponential Operator
Latest versions of JavaScript has the exponential operator denoted by **
.
For example:
2**3
is the same as:
Math.pow(2,3);
The left operand is the base and the right one is the exponent.
ES6 or later has template strings, which lets us interpolate dynamic expressions and create multi-line strings.
We can create dynamic string or Symbols as object keys, which is handy for creating dynamic objects.
To check for mandatory parameters, we can run a function in the default parameter assignment code which throws an error.
The spread operator can be used to clone and combine arrays. Also, we can find the first entry that meets a condition with the Array.find
method.