Just like any other programming language, JavaScript has many tricks to perform both tasks. Some of the tips are widely known:
Get the unique values of an array
Getting an array of unique values might be easier than you think:
1 2 3 | var j = [...new Set([1, 2, 3, 3])] >> [1, 2, 3] |
Array and Boolean
Ever need to filter falsy values (0, undefined, null, false, etc.) from an array? You may not know this trick:
1 2 3 4 5 6 7 | myArray .map(item => { // ... }) // Get rid of bad values .filter(Boolean); |
Create blank Objects
Sure, you can create an empty Object with {}, but that Object still has the proto , hasOwnProperty, and other object methods. However, there is a way to create a pure “dictionary” object:
1 2 3 4 5 | let dict = Object.create(null); // dict.__proto__ === "undefined" // Không có thuộc tính cho object trừ khi bạn thêm chúng |
Merge objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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", } */ |
Require Function Parameters
It is possible to set default values for function arguments, but see this tip to request the values passed to a given argument:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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'); |
Destructuring Aliases
1 2 3 4 5 6 7 8 | const obj = { x: 1 }; // Grabs obj.x as { x } const { x } = obj; // Grabs obj.x as { otherName } const { x: otherName } = obj; |
Very useful to avoid naming conflicts with existing variables!
Get the query string parameter
We often use multiple expressions to retrieve query string values, but it’s now easier with the URLSearchParams API:
1 2 3 4 5 6 7 8 9 10 | // 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" |
Refer here