Modern JavaScript features you may miss


By Jimmy Breck mckye

Crazy technology house


No reprint without permission

Although I’ve been writing JavaScript code almost every day for the past seven years, I have to admit that I don’t really pay much attention to es language release statements.async/awaitandProxiesMajor features like this are one thing, but steady small-scale, incremental improvements are emerging every year because there is always something to learn.

So in this article, I’ve collected some modern JavaScript features that didn’t get much attention when they were first released. Some of them are just the improvement of coding quality, while others are really convenient and can reduce a lot of code. Here are some things you might miss:


Binary and octal

In JavaScript, binary operations are not common, but sometimes they are also encountered, otherwise, it will not solve your problem. You may be writing high-performance code for low-power devices, compressing bits into local storage, pixel RGB operations in browsers, or having to deal with tightly packed binary data formats.

This may mean that there is a lot of work to be done on binary numbers, which I always think can be done in decimal system. Well, ES6 adds a binary number format for this:0b

const binaryZero = 0b0;
const binaryOne  = 0b1;
const binary255  = 0b11111111;
const binaryLong = 0b111101011101101;

This makes it easy to handle binary flags:

// Pizza toppings
const olives    = 0b0001;
const ham       = 0b0010;
const pineapple = 0b0100;
const artechoke = 0b1000;

const pizza_ham_pineapple = pineapple | ham;
const pizza_four_seasons  = olives | ham | artechoke;

The same is true for octal numbers. In the JS world, these areas are a bit niche, but they are common on the web and in some file formats. Now you can use grammar0oHandle octal.


Do not cooperate withwindow.isNaN()Confusion is a new method with more intuitive behavior.

You’ll find, classicisNaNThere are some interesting quirks:

isNaN(NaN)              === true
isNaN(null)             === false
isNaN(undefined)        === true
isNaN({})               === true
isNaN('0/0')            === true
isNaN('hello')          === true

What led to this result? First of all, none of these parameters are actuallyNaN。 As always, the problem is with your “favorite” JavaScript feature: type coercion. adoptNumberFunction willwindow.isNaNThe parameter of is forced to be a number.

All right, newNumber.isNaN()The static method solves all the problems. It will return once and for all the arguments andNaNEquality of. This is absolutely clear:

Number.isNaN(NaN)       === true
Number.isNaN(null)      === false
Number.isNaN(undefined) === false
Number.isNaN({})        === false
Number.isNaN('0/0')     === false
Number.isNaN('hello')   === false

Function signature: Number.isNaN : (value: any) => boolean


Exponential (power) operator

I’m glad to have a literal grammar for power:

2**2 === 4
3**2 === 9
3**3 === 27

(it’s strange, because IConvictionJavaScript already has this – I’ve probably been thinking about Python)


This feature deserves attention if you’ve been writingarray.indexOf(x)!== -1This kind of code can now use the newincludesMethod:

[1, 2, 3].includes(2)    === true
[1, 2, 3].includes(true) === false

includesUsing the same value zero algorithm===Same) but it can handleNaNValue. Like equality checking, it compares objects by reference rather than by content:

const object1 = {};
const object2 = {};

const array = [object1, 78, NaN];

array.includes(object1) === true
array.includes(object2) === false
array.includes(NaN)     === true

includesYou can use the second parameterfromIndexLets you provide an offset:

// positions   0  1  2  3  4
const array = [1, 1, 1, 2, 2];

array.includes(1, 2) === true
array.includes(1, 3) === false

It’s so easy.

Function signature: Array.prototype.includes : (match: any, offset?: Int) => boolean


Shared array buffers and atomic operations

It’s a great pair of features, and if you’re going to do a lot of work with web workers, these features will prove invaluable. They allow you to share memory directly between processes and avoid resource contention by setting locks.

They are quite complex API functions, so we won’t summarize them here, but we can learn more from sitepen’s article. At present, some browsers are not supported, but it is expected to be improved in the next few years.


Powerful regular expressions

Es2018 introduces a set of regular expression features:

Lookbehind match (forward match)

In the runtime that supports it, you can now use regular expressions for forward matching. For example, to find all numbers that start with dollars:

const regex = /(?<=$)\d+/;
const text  = 'This cost $400';
text.match(regex) === ['400']

The key is that the new lookbehind search group and lookahead search group are evil twins:

Look ahead:  (?=abc)
Look behind: (?<=abc)

Look ahead negative:  (?!abc)
Look behind negative: (?<!abc)

Unfortunately, there is no way to support new backward syntax for older browsers, so you can only use it on node at present.

You can name the capture group

The real powerful function of regular expressions is to be able to pick out sub matches and use them for some simple parsing. But until recently, we could only refer to sub matches by numbers, such as:

const getNameParts  = /(\w+)\s+(\w+)/g;
const name          = "Weyland Smithers";
const subMatches    = getNameParts.exec(name);

subMatches[1]     === 'Weyland'
subMatches[2]     === 'Smithers'

Now you have a syntax that you can place at the beginning of each bracket for each group you want to name?To assign the names of these sub matches (or capture groups):

const getNameParts  = /(?<first>\w+)\s(?<last>\w+)/g;
const name          = "Weyland Smithers";
const subMatches    = getNameParts.exec(name);

const {first, last} = subMatches.groups
first             === 'Weyland'
last              === 'Smithers'

Unfortunately, currently only chrome and node support it.

Now you can match new lines with dots

You just need to provide/sSigns, such as/someRegex./s`/anotherRegex./sg


Array.prototype.flat() & flatMap()

I’m glad to see that on MDN.

Simply put,flat()Set multidimensional array to the specified maximumdepthFlattening:

const multiDimensional = [
    [1, 2, 3],
    [4, 5, 6],

multiDimensional.flat(2) === [1, 2, 3, 4, 5, 6, 7, 8, 9]

flatMapIs essentially amap, and the depth is 1flat。 When an array is returned from a mapping function, but you do not want the result to be a nested data structure, it is convenient to use:

const texts = ["Hello,", "today I", "will", "use FlatMap"];

// with a plain map
const mapped = => text.split(' '));
mapped === ['Hello', ['today', 'I'], 'will', ['use', 'FlatMap']];

// with flatmap
const flatMapped = texts.flatMap(text => text.split(' '));
flatMapped === ['Hello', 'today', 'I', 'will', 'use', 'FlatMap'];

Unbound capture

Now you can write a try / catch statement without binding the thrown error:

try {
  // something throws
} catch {
  // don't have to do catch(e)

By the way, I don’t care about youeThe capture behavior of the value of, sometimes calledPok é mon exception handling。 ‘because you want to capture everything’!

String pruning method

Small but easy to use:

const padded         = '          Hello world   ';
padded.trimStart() === 'Hello world   ';
padded.trimEnd()   === '          Hello world';

This article starts with WeChat public: front-end pioneer.

Welcome to scan the two-dimensional code to pay attention to the public number, push you every day to send fresh front-end technical articles.

Modern JavaScript features you may miss

Welcome to other great articles in this column:

  • Deep understanding of shadow DOM v1
  • Step by step to teach you how to use webvr to realize virtual reality games
  • 13 modern CSS frameworks to improve your development efficiency
  • Get started bootstrap Vue
  • How does the JavaScript engine work? Everything you need to know from call stack to promise
  • Websocket practice: real time communication between node and react
  • 20 interview questions about Git
  • In depth analysis of console.log of node.js
  • What is node.js?
  • Build an API server with node.js in 30 minutes
  • Object copy of JavaScript
  • Programmers can’t earn 30K a month before they are 30 years old. Where to go
  • 14 best JavaScript data visualization Libraries
  • 8 top level vs code extensions for the front end
  • Node.js multithreading full guide
  • Four schemes and implementation of transforming HTML into PDF

  • More articles