Categories
Modern JavaScript

Best of Modern JavaScript — Destructuring and Defaults

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript destructuring.

Array Patterns Work with Iterable Object

We can use array patterns like the rest operator with iterable objects.

For example, we can write:

const [x, ...y] = 'foo';

The x is 'f' and y is ['o', 'o'] .

Since strings are iterable, we can destructure them.

Destructuring also works with string code points.

For example, we can write:

const [x, y, z] = 'auD83DuDCA9c';

The x is 'a' , b is 'uD83DuDCA9' and z is 'c' .

Default Values

We can set default values when destructuring.

For example, we can write:

const [x = 13, y] = [];

Then x is 13 and y is undefined since the array is empty.

Since 13 is the default value of x , it’s assigned to it.

Therefore undefined triggers default values to be assigned.

Default values are computed on demand.

If they aren’t needed, then they won’t be used.

For example, if we have:

const {
  prop: y = fn()
} = foo;

Then that’s the same as:

let y;
if (foo.prop === undefined) {
  y = fn();
} else {
  y = foo.prop;
}

Default values can refer to other variables in the pattern.

For instance, we can write:

const [x = 13, y = x] = [];

Then x and y are both 13.

If we have:

const [x = 3, y = x] = [17];

Then x and y are both 17.

And if we write:

const [x = 3, y = x] = [7, 4];

Then x is 7 and y is 4.

The default value is only used when there’s no corresponding value on the right side.

We can also have default object values when destructuring.

For example, we can write:

const [{
  prop: x
} = {}] = [];

Then x is an empty object since there’s nothing on the right side.

If we have:

const {
  prop: x
} = {};

we get the same thing.

If we have:

const [{
  prop: x
} = {
  prop: 'foo'
}] = [];

Then x is foo since we assigned an object to the left side with the default value.

However, if we have:

const [{
  prop: x
} = {
  prop: 'foo'
}] = [{}];

Then x us undefined since we have an object in the array on the right side, so the default value won’t be assigned on the left side.

If we want to trigger the default value assignment, then we’ve to assign a default value to the property itself:

const [{
  prop: x = 'foo'
} = {}] = [{}];

Then x would be 'foo' since prop isn’t found on the right side.

Property Value Shorthands

Property value shorthand works like we expect with destructuring as we can see from the previous examples.

So:

const {
  x,
  y
} = {
  x: 1,
  y: 2
};

is the same as:

const {
  x: x,
  y: y
} = {
  x: 1,
  y: 2
};

Conclusion

Destructuring can be done with objects and arrays.

There’re many tricks with default values.

Categories
Modern JavaScript

Best of Modern JavaScript — Destructuring

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript destructuring.

Array Destructuring

We can destructure arrays into variables by their position.

For example, if we have:

const arr = ['a', 'b'];
const [x, y] = arr;

Then x is 'a' and y is 'b' .

Returned values are also processed.

For example, we can write:

const [all, areaCode, officeCode, number] =
/^(ddd)-(ddd)-(dddd)$/
.exec('555-555-1212');

We destructure the matched patterns into their own variables.

exec returns an array with the whole string and the parts matched by patterns so we can assign to variables.

Where can Destructuring be Used?

Destructuring can be used in many places.

For instance, they can be used in arrays:

const [x] = ['a'];
let [x] = ['a'];
var [x] = ['a'];

We assign the array entry into the x variable.

We can also destructure in parameters.

For example, we can write:

`function` `f([x])` `{`
  //...
`}`
`f(['a']);`

And x is 'a' .

Also, we can destructure with the for-of loop:

const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
  console.log(index, element);
}

We call arr.entries to get an array with an array of indexes and the element as the entries.

Patterns for Destructuring

If we want to destructure an object or area, we need the source and the target.

The right-hand side is the source and the left-hand side has the target.

For example, we can write:

const obj = {
  a: [{
    foo: 'bar',
    bar: 'abc'
  }, {}],
  b: true
};
const {
  a: [{
    foo: f
  }]
} = obj;

We restructured the nested object with the a array with an object with the foo property inside.

bar doesn’t exist on the right side so we set it to 'abc' as the default value.

b is set to true since it doesn’t exist on the right side.

We don’t have to assign everything to its own variable.

We can just pick what we need.

For example, we can write:

const { x } = { x: 1, y: 3 };

We just destructure x .

So x is 1.

We can do the same with an array:

const [x, y] = ['a', 'b', 'c'];

Then x is 'a' and y is 'b' .

Object Destructuring Coerce Values to Objects

We can use destructuring with primitive values.

For example, we can write:

const {
  length: len
} = 'foo';

And len is 3 since it gets the length property of the string.

We can also destructure numbers by writing:

const {
  toString: s
} = 123;

Then we get the toString method of Number.prototype as the value of s .

Failing to Object-Destructure a Value

A value may not be destructed in some cases.

If the value can’t be converted to an object with ToObject , then it can’t be destructured.

For instance, if we have:

const { prop: x } = undefined;
const { prop: y } = null;

Then we get TypeError in both cases since those properties on the left side don’t exist.

Conclusion

Destructuring can be used in many places.

Categories
Modern JavaScript

Best of Modern JavaScript — Core Features

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at the core features of JavaScript.

From var to const/let

var is no longer the only keyword used to declare variables.

There’re the better alternatives which are let and const .

var is function scoped and can be hoisted.

This makes determining where a variable declared with var hard.

On the other than, determining where a variable declared with let or const is easy.

They’re both block-scoped, so we know they’re only available within a block.,

For instance, if we have:

var x = 100;

function foo(randomize) {
  if (randomize) {
    var x = Math.random();
    return x;
  }
  return x;
}
foo(false);

Then we don’t know what x would be without looking at the each line.

On the other hand, if we have:

let x = 100;

function foo(randomize) {
  if (randomize) {
    let x = Math.random();
    return x;
  }
  return x;
}
foo(false);

Then we know x on the outside has nothing to with x on the inside.

x outside the function is 100.

And x inside the function is the random number.

Therefore, we should declare variables with let or const .

If we don’t want to change the variable’s value after it’s declared, then we declare it with const .

We can’t blinding replace var with let or const .

We got to make sure the logic is still correct after replacement.

But from now in, we use const most of the time, let for variables that can change, and never use var .

IIFEs to blocks

To make private variables before ES6, we put them in IIFEs.

IIFEs stands for immediately invoked function expression.

It’s an expression that looks like:

(function() {
  var foo = '...'
}());

We have a function that we wrap around parentheses and called.

tmp isn’t available outside the function.

With ES6, we can use blocks with let or const keywords to create private variables:

{
  let foo = '..';
}

We created the variable foo which is only available inside the block.

Concatenating Strings to Template Literals

With ES6, we finally have template literals.

They let us interpolate expressions in our strings.

This is much better than concatenation since they’re easier to ready and debug.

For instance, instead of writing:

function getDimensions(width, height) {
  console.log('width: ' + width + ', height: ' + height);
}

We write:

function getDimensions(width, height) {
  console.log(`width: ${width},  height: ${height}`);
}

Multi-line Strings

We can make multiline strings easily with template literals.

We just have to put them in the string the way we want them.

For instance, instead of writing:

let html = '<!doctype html>\n' +
  '<html>\n' +
  '<head>\n' +
  '    <meta charset="UTF-8">\n' +
  '    <title></title>\n' +
  '</head>\n' +
  '<body>\n' +
  '</body>\n' +
  '</html>\n

We write:

let html = `
<!doctype html>
<html>

  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>

  <body>
  </body>

</html>

It’s much cleaner and we don’t have to do any concatenation anymore.

Conclusion

The core features of modern JavaScript are let , const and template strings.