nas5w / javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
MIT License
1.2k stars 73 forks source link

Open call for tips! #3

Open nas5w opened 5 years ago

nas5w commented 5 years ago

This is an open call for any tips! Please let me know if you have anything to share.

Additionally, if you're relatively new to javascript, let me know what questions you have! Those often evolve into the best tips themselves.

Andrei0872 commented 5 years ago

I do have some tips that I'd love to share.

For example:

1) When working with JS in the browser, instead of writing document.querySelector()/document.querySelectorAll() multiple times, you could do the following thing:

const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);

// Usage
const demo = $("#demo");
// Select all the `a` tags
[...$$("a[href *='#']")].forEach(console.log)

2) Comparing 2 objects:

function equalObjects (obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2)
}
  1. Good use cases for Object Destructuring: a. Getting specific properties from an object:
    
    const o = {
    name: 'John',
    age: 18,
    country: 'Unknown'
    }

const { country, ...needed } = o; console.log(needed) // { name: 'John', age: 18 }

  b. Conditionally add properties to an object

const age = 17; const allowedToVote = age >= 18;

const person = { ...{ allowedToVote }.allowedToVote && { age } || { name: 'Default Name' } };

console.log(person) // { name: 'Default Name' } 



I know the last one might be a little bit confusing, but I personally find it very useful.
nas5w commented 5 years ago

Thanks for the list @Andrei0872!

Give me some time to review and I'll get back to you. I'll probably ask you to contribute at least a few of these :smile:. Some I might not want to include. For example, there's actually an issue using JSON.stringify(obj1) === JSON.stringify(obj2). Technically objects properties don't have a specific order, so two objects can be identical but, when stringified, the props could be in a different order (totally valid). This would return false even though they are technically identical. An example:

'{"name":"Joe","age":25}' === '{"age":25,"name":"Joe"}' will return false because the props were stringified in different orders despite being the same object.

Otherwise, awesome list :+1: :+1: :+1:

Andrei0872 commented 5 years ago

Oh, I didn't know about that! Thank you! Apologies for my misunderstanding!

nas5w commented 5 years ago

No worries, I'll definitely be learning a lot from your tips so I'm glad I could contribute a little to your knowledge in return!

nas5w commented 5 years ago

@Andrei0872 I'd like to add at least a couple of these tips! I'm going to create separate issues to address them. Would you be willing to fork the repository, add the new content, and do pull requests as I ask for the the new sections?

I added issue #8 if you'd be willing to work on it!

Andrei0872 commented 5 years ago

Sorry for the tardy answer! Yes, that would be my pleasure.

TravisL12 commented 5 years ago

Something that I've found quite useful lately is Date formatting via toLocaleDateString.

If you have a date that you want to format you can use this function in many ways. Example:

const date = new Date();
// Sat Feb 23 2019 20:17:31 GMT-0800 (Pacific Standard Time)

date.toLocaleDateString();
// 2/23/2019

date.toLocaleDateString('en-US', { year: 'numeric', month: 'long' });
// February 2019

date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', weekday: 'long' });
// February 2019 Saturday

// You can use any language localization (i.e. `de-DE`, `es-ES`, etc.)
date.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', weekday: 'long' });
// febrero de 2019 sábado

You can use it to use UTC time as well:
const options = {
    timeZone: 'UTC',
    timeZoneName: 'short',
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    hour:'numeric',
};
date.toLocaleDateString('en-US', options);
// February 2019 Sunday, 4 AM UTC

*/ I'm happy to add more examples */

I'll admit the date options object can get a bit large but I've appreciated this over the confusing strftime formatting.

Kaushal28 commented 5 years ago

As a beginner in Javascript, I just learned the difference between function() declaration and arrow functions. I can add this with a few examples if you agree.

nas5w commented 5 years ago

@TravisL12 love the idea. Can we discuss this in issue #10 that I just opened?

nas5w commented 5 years ago

@Kaushal28 This is definitely a good topic. Let’s discuss in issue #11. There’s a lot of potential for misunderstanding so I want to make sure we get it right before adding to the repo.

Andrei0872 commented 5 years ago

Here's a quick tip that I found to be very useful.

Applying multiple styles to an element:

const $ = document.querySelector.bind(document);

const elem = $("#demo");

  Object.assign(elem.style, {
     fontSize: '20px',
     color: 'green',
     textDecoration: 'underline'
   });