Get Unique Values of an Array
Getting an array of unique values is probably easier than you think:
var j = [...new Set([1, 2, 3, 3])] >> [1, 2, 3]
I love the mixture of rest expression and
Array and Boolean
Ever need to filter falsy values (
false, etc.) out of an array? You may not have known this trick:
myArray .map(item => // ... ) // Get rid of bad values .filter(Boolean);
Boolean and all those falsy value go away!
Create Empty Objects
Sure you can create an object that seems empty with
, but that object still has a
__proto__ and the usual
hasOwnProperty and other object methods. There is a way, however, to create a pure “dictionary” object:
let dict = Object.create(null); // dict.__proto__ === "undefined" // No object properties exist until you add them
There are absolutely no keys or methods on that object that you don’t put there!
const person = name: 'David Walsh', gender: 'Male' ; const tools = computer: 'Mac', editor: 'Atom' ; const attributes = handsomeness: 'Extreme', hair: 'Brown', eyes: 'Blue' ; const summary = ...person, ...tools, ...attributes; /* Object "computer": "Mac", "editor": "Atom", "eyes": "Blue", "gender": "Male", "hair": "Brown", "handsomeness": "Extreme", "name": "David Walsh", */
Those three dots made the task so much easier!
Require Function Parameters
const isRequired = () => throw new Error('param is required'); ; const hello = (name = isRequired()) => console.log(`hello $name`) ; // This will throw an error because no name is provided hello(); // This will also throw an error hello(undefined); // These are good! hello(null); hello('David');
const obj = x: 1 ; // Grabs obj.x as x const x = obj; // Grabs obj.x as as otherName const x: otherName = obj;
Useful for avoiding naming conflicts with existing variables!
Get Query String Parameters
For years we wrote gross regular expressions to get query string values but those days are gone — enter the amazing
// Assuming "?post=1234&action=edit" var urlParams = new URLSearchParams(window.location.search); console.log(urlParams.has('post')); // true console.log(urlParams.get('action')); // "edit" console.log(urlParams.getAll('action')); // ["edit"] console.log(urlParams.toString()); // "?post=1234&action=edit" console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
Much easier than we used to fight with!