Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Useful JS Tricks #11

Open
BKJang opened this issue Apr 30, 2019 · 0 comments
Open

Useful JS Tricks #11

BKJang opened this issue Apr 30, 2019 · 0 comments
Labels
completed This is completed. Javascript This is related to Javascript. Tip This is tip for developement.

Comments

@BKJang
Copy link
Owner

BKJang commented Apr 30, 2019

🔨 Get Unique Values of an Array

var j = [...new Set([1, 2, 3, 3])]
>> [1, 2, 3]

🔨 Array and Boolean

filter falsy values (0, undefined, null, false, etc.) out of an array.

myArray
    .map(item => {
        // ...
    })
    // Get rid of bad values
    .filter(Boolean);

🔨 Create Empty Objects

Create empty object __proto__ and the usual hasOwnProperty and other object methods are not exist.

let dict = Object.create(null);

// dict.__proto__ === "undefined"
// No object properties exist until you add them

🔨 Merge Objects

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

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

const obj = { x: 1 };

// Grabs obj.x as { x }
const { x } = obj;

// Grabs obj.x as { otherName }
const { x: otherName } = obj;

🔨 Get Query String Parameters

// 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"

🙏 Reference

@BKJang BKJang added Javascript This is related to Javascript. Tip This is tip for developement. completed This is completed. labels May 2, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
completed This is completed. Javascript This is related to Javascript. Tip This is tip for developement.
Projects
None yet
Development

No branches or pull requests

1 participant