length
property. In this case, for example, there is no need to, in order to clear an array, write to a variable that stores a reference to it, a reference to a new array. const arr = [11, 22, 33, 44, 55, 66]; // arr.length = 3; console.log(arr); //=> [11, 22, 33] // arr.length = 0; console.log(arr); //=> [] console.log(arr[2]); //=> undefined
doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; // ... }
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) { // ... }
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { // ... }
const csvFileLine = '1997,John Doe,US,john@doe.com,New York'; const { 2: country, 4: state } = csvFileLine.split(',');
switch
: function getWaterState(tempInCelsius) { let state; switch (true) { case (tempInCelsius <= 0): state = 'Solid'; break; case (tempInCelsius > 0 && tempInCelsius < 100): state = 'Liquid'; break; default: state = 'Gas'; } return state; }
Promise.all
used, it is possible to organize waiting for the execution of several asynchronous functions: await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
Object
(for example, it is a constructor
, toString()
and so on). Here's how to do it: const pureObject = Object.create(null); console.log(pureObject); //=> {} console.log(pureObject.constructor); //=> undefined console.log(pureObject.toString); //=> undefined console.log(pureObject.hasOwnProperty); //=> undefined
JSON.stringify
method is capable of more than the usual conversion of objects into their string representation. In particular, the resulting JSON code with this method can be formatted: const obj = { foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } }; // - , // JSON-. JSON.stringify(obj, null, 4); // =>"{ // => "foo": { // => "bar": [ // => 11, // => 22, // => 33, // => 44 // => ], // => "baz": { // => "bing": true, // => "boom": "Hello" // => } // => } // =>}"
Set
from ES2015 with an extension operator makes it easy and convenient to remove duplicate elements from arrays: const removeDuplicateItems = arr => [...new Set(arr)]; removeDuplicateItems([42, 'foo', 42, 'foo', true, true]); //=> [42, "foo", true]
const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
function flattenArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; } const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenArray(arr); //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
Source: https://habr.com/ru/post/354676/
All Articles