• JS things I never knew existed
  • Originally written by Skyllo
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Yong Li
  • Proofread by: Yukiko, DZ

JS features I’ve never seen before

One day I was reading the MDN documentation and found some features and apis that I didn’t even realize existed in JS. I have listed a few here, whether they are useful or not, JS learning is endless.

Mark the statement

How many people know that in JS you can name for loops and blocks? I don’t know… After naming the new name you can use the new name after break and continue in the for loop and after break in the statement block.

Loop1: / / tag"loop1" 
for (let i = 0; i < 3; i++) { // "loop1"Loop2: / / tag"loop2"
   for (let j = 0; j < 3; j++) { // "loop2"
      if (i === 1) {
         continueloop1; // Continue with the outer layer"loop1"Cycle / /breakloop1; // Abort the outer"loop1"Loop} console.log(' I = '${i}, j = ${j}`);
   }
}

/* 
 * # output
 * i = 0, j = 0
 * i = 0, j = 1
 * i = 0, j = 2
 * i = 2, j = 0
 * i = 2, j = 1
 * i = 2, j = 2
 */
Copy the code

Here is an example of block naming, where you can only use the new name after break.

foo: {
  console.log('one');
  break foo;
  console.log('This print will not be executed');
}
console.log('two'); / * *# output
 * one
 * two
 */
Copy the code

“Void” operator

I thought I knew all the operators until I saw this one. It has been in JS since 1996. All browsers support it, and it’s easy to understand, quoted from MDN:

The void operator evaluates the given expression and returns undefined.

With it, you can write an immediate function expression (IIFE) in another way, like this:

void function iife() {
	console.log('hello'); } (); // Is equivalent to the following (function iife() {
    console.log('hello'); }) ()Copy the code

One thing to note about using void is that the entire result of the void operator is empty (undefined), no matter what the given expression returns!

const word = void function iife() {
	return 'hello'; } (); // use 'undefined' const word = (function iife() {
	return 'hello'; }) (); / / word is"hello"
Copy the code

You can also use void with async so that you can use functions as entrances to asynchronous code:

void async function() { 
    try {
        const response = await fetch('air.ghost.io'); const text = await response.text(); console.log(text); } catch(e) { console.error(e); }}() // or keep writing (async () => {try {const response = await fetch('air.ghost.io'); 
        const text = await response.text();
        console.log(text);
    } catch(e) {
        console.error(e);
    }
})();
Copy the code

Comma operator

After learning about the comma operator, I realized that I didn’t fully understand how it worked. Here is a quote from MDN:

The comma operator evaluates each of its operands (left to right) and returns the value of the last operand.

function myFunc() {
  let x = 0;
  return(x += 1, x); / / equivalent to thereturn ++x;
}

y = false.true; // consoletrue
console.log(y); // false, comma priority is lower than assignment z = (false.true); // consoletrue
console.log(z); // true, returns the whole thing in parenthesestrue
Copy the code

Cooperate withConditional operator

The last value in the comma operator is returned to the conditional operator, so you can put as many expressions as you want before the last value. In the example below, I put the print statement before the returned Boolean value.

const type = 'man';

const isMale = type= = ='man' ? (
    console.log('Hi Man! '),
    true
) : (
    console.log('Hi Lady! '),
    false
);

console.log(`isMale is "${isMale}"`);
Copy the code

Internationalization API

Internationalization is hard to do well under the best of circumstances. Fortunately, there is a set of apis that most browsers support well. One of my favorite features is date formatting, as shown in the following example:

const date = new Date();

const options = {
  year: 'numeric', 
  month: 'long', 
  day: 'numeric'
};

const formatter1 = new Intl.DateTimeFormat('es-es', options);
console.log(formatter1.format(date)); // 22 de diciembre de 2017

const formatter2 = new Intl.DateTimeFormat('en-us', options);
console.log(formatter2.format(date)); // December 22, 2017
Copy the code

Pipe operator

As of this writing, this feature is only supported by Firefox 58 and above with a startup parameter passed in, but Babel already has a plug-in proposal for it. It looks like it was inspired by Bash and I think it’s great!

const square = (n) => n * n; const increment = (n) => n + 1; Increment (square(2)); 25 / / / / using the pipe operator 2 | > square | > increment | > square; / / 25Copy the code

It is worth mentioning

Atomics

When data is shared by multiple threads, atomic operations ensure that the data being read and written is as expected, that the next atomic operation must not begin until the last atomic operation has finished. This helps to keep data synchronized between different threads (such as the main thread and another WebWorker thread).

I love atomicity in other languages like Java. My hunch is that as more and more people use WebWorkers to separate operations from the main thread, the use of atomic operations will become more widespread.

Array.prototype.reduceRight

Well, I’ve never seen this before because it’s basically the same as array.prototype.reduce () + array.prototype.reverse () and you rarely need to do that. But if you have this need, reduceRight is the best choice!

const flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
    returna.concat(b); } []); // flattened array is [4, 5, 2, 3, 0, 1]Copy the code

SetTimeout () parameters

This already exists, but if I had known about it earlier, I could have saved a lot of.bind(…) .

setTimeout(alert, 1000, 'Hello world! '); / * *# alert output* Hello World! * /function log(text, textTwo) {
    console.log(text, textTwo);
}

setTimeout(log, 1000, 'Hello World! '.'And Mars! '); / * *# output* Hello World! And Mars! * /Copy the code

HTMLElement.dataset

Until now I had been using the custom data attribute data-* for HTML elements because I didn’t realize there was an API to easily query them. Aside from some naming restrictions (see link above), it basically allows you to query dash-case properties using camelCase when querying in JS. So the attribute name data-birth-planet becomes birthPlanet in JS.

<div id='person' data-name='john' data-birth-planet='earth'></div>
Copy the code

Query:

let personEl = document.querySelector('#person');

console.log(personEl.dataset) // DOMStringMap {name: "john", birthPlanet: "earth"} the console. The log (personEl. Dataset. Name) / / John console. The log (personEl. Dataset. BirthPlanet) / / earth / / you can also add attributes in the program personEl.dataset.foo ='bar';
console.log(personEl.dataset.foo); // bar
Copy the code

conclusion

I hope you learned something new here as I did. Also like Mozila’s new MDN site, it looks great and I spent more time reading the documentation than I thought.

Revision: Fixed several names and forasyncThe function to addtry.catch. Thank you so much for Reddit.

Happy 2018 New Year!


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.