Giter Club home page Giter Club logo

javascript-tips-and-tidbits's Introduction

About

I'm a senior UI engineer at Microsoft. Previously, I worked on modernizing government software systems with the U.S. Digital Service. In my spare time, you'll find me writing blog posts, newsletters, and contributing to open source.

Other things

I like working on lots of projects in my spare time! There's a good chance one of them brought you to my profile here. If you're interested in following some of my work, consider:

  • โž• Following me here! Hooray vanity metrics!
  • ๐Ÿ“ Checking out my blog

javascript-tips-and-tidbits's People

Contributors

andrei0872 avatar j127 avatar nas5w avatar pvenky avatar pytal avatar rinatvaliullov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

javascript-tips-and-tidbits's Issues

JSON deep comparison

The noted problem with a JSON deep comparison is relatively mitigatible given a .split+.sort+.join even if other problems with the method are not.

Explaining var, let and const. Using const in examples when reference is not reassigned. Adding an example of promise chaining. Pointing out that an async function will return a promise.

I have a few changes I'd like to submit. The first is largely opinion based but I think the community adopting a consistent style will ease the onboarding process for those getting into the language. I think the examples should be using const instead of let when the reference is not reassigned. Airbnb has a really good style guide for javascript and while it's not a bible it's a good launching point for those developing their own styles IMO. https://github.com/airbnb/javascript#references--prefer-const

I'd like to add an explanation and example for var, let and const, something along the lines of:

Var, Let, Const

Var is basically antiquated at this point. It was the pre-ES6 way to declare a variable and comes with some gotchas. The declarations are function scoped and var declarations get hoisted to the top of the function which can lead to some unexpected behavior.

function varCheck() {
  console.log(x); // => Uncaught ReferenceError: x is not defined
}
var x = 1;
function varCheck() {
  console.log(x); // => undefined
  {
    var x = 2;
    console.log(x); // => 2
  }
}

Let is the way to declare a variable in ES6. It can be reassigned after declaration and is block scoped.

let x = 1;
function letCheck() {
  console.log(x); // => 1
  {
    let x = 2;
    console.log(x); // => 2
  }
  console.log(x): // => 1
}

Const is the way to declare a constant in ES6. The variable can not be assigned after declaration.

const x = 1;
x = 2; // => SyntaxError: Assignment to constant variable: x at 2:0

There is some debate on whether or not const should be used for non primitive types that are mutated but the reference is not reassigned.

const myArray = [1, 2, 3];
myArray.pop();
console.log(myArray); // => [1, 2]

Is valid. If you're unsure airbnb has a fantastic style guide to reference. https://github.com/airbnb/javascript#references--prefer-const

I think that an example of promise chaining is probably a good idea.

.then methods can be chained. I see a lot of new comers end up in some kind of call back hell inside of a promise when it's completely unnecessary.

//The wrong way
getSomedata
  .then(data => {
    getSomeMoreData(data)
      .then(newData => {
        getSomeRelatedData(newData)
          .then(finalData => {
            console.log(newData);
          });
        });
      });
  });
//The right way
getSomeData
  .then(data => {
    return getSomeMoreData(data);
  })
  .then(data => {
    return getSomeRelatedData(data);
  })
  .then(data => {
    console.log(data);
  });

You can see how it's much easier to read the second form and with ES6 implicit returns we could even simplify that further

getSomeData
  .then(data => getSomeMoreData(data))
  .then(data => getSomeRelatedData(data))
  .then(data => console.log(data));

// Because the function supplied to .then will be called with the the result of the resolve method from the promise we can omit the ceremony of creating an anonymous function altogether. This is equivalent to above
getSomeData
  .then(getSomeMoreData)
  .then(getSomeRelatedData)
  .then(console.log);

In the async await section I think it's a good idea to point out that an async function will return a promise

Note: One important thing to note here is that the result of an async function is a promise

async function myFunc() {
  return await greeter;
}

console.log(myFunc()) // => Promise {}

myFunc().then(console.log); // => Hello world!

Example using generators with for..of and spread

E.g. with

function* numbers(x) {
  yield 1;
  yield 2;
  yield 3;
  yield x;
}

For..of:

for (const x of numbers(99)) {
  console.log(x);
}
// => 1
// => 2
// => 3
// => 99

Spread:

const arr = [...numbers(99)];
console.log(are);
// => [1, 2, 3, 99]

Typo in Promises example

In the Promises section, the last line of the example should read "Error: Oh no", instead of "Error: On no"

DOM Manipulation

Indicate that .bind needs to be polyfilled for <IE9 and as a result should probably not be used.

Binding the function like the following would be more advisable:

function $(id) {
return typeof id == "string" ? document.getElementById(id) : id;
}

A slight alteration to Rest Syntax section for better understanding

I read through the Rest Syntax section and I felt it was improvement could be made by letting readers know that you can use declared params and rest syntax together. We can either state that ...args has to be the last function argument in text or update the example to the following (or do both ๐Ÿ™‚):

function myFunc(param1, ...args) {
    console.log(param1 + args[0] + args[1]);
}

myFunc("The Result is: " , 1, 2, 3, 4);
// The Result is: 3

I'd be happy to make the pull request.

Tiny Correction 2

It says:
console.log(introduce(person));
// "I'm Eddie and I'm 24 years old!"

"console.log(introduce(person)); " produces "undefined" in the console log.
The function does not return anything.

Maybe it should just be:
introduce(person)

The introduce method already has console.log.

Add Query Selector Shorthand Tip

Add a "DOM Manipulation" section after the "Async Await" section. Make sure to add a link from the table of contents as well.

Add the following as the first item in the DOM Manipulation section.

Create Your Own Query Selector Shorthand

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)

Suggest using += instead of ++

Please consider replacing the increment/decrement operators (++ and --) for their cousins, += and -= respectively.

Even there is no consensus if those operators are good/bad, there are some who believe they are legacy and should be avoided or even removed from the language (eg. python, go)

Here is a quick few reasons that I've seen first-hand when teaching programing 101 at my Uni:

  1. they have a complex side-effect, which is not intuitive to newcomers: like the readme explains, i++ and ++i means two different things and their post-conditions are entirely different to each other.

  2. at a glance they seem to break from parenthesis, which again could be surprising for the newcomers, like for instance a=(i++) will still produce the value previously to be incremented

  3. they are poorly defined at grammar level, for instance (i)++ works, which should not, but even if that works then why (a, i)++ wont?

  4. they break the right-to-left expected order of operations, for instance compare a = b += 1 with a = ++b


Honestly using += 1 is not too much of a trouble than ++ and certainly helps to avoid some pitfalls plus at the same time it makes the development environment more inclusive and easy for everybody to precisely understand what is the original author intended.

Please don't write clever code, be clever writing code that everybody can understand!

Open call for tips!

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.

The array in querySelectorAll example is not necessary

It's not needed to convert to array in this example: [...$$("a[href *='#']")].forEach(console.log);

querySelectorAll returns NodeList. While that is not an array, it does have forEach natively. It would be more appropriate to use one of these:

  • $$("a[href *='#']").forEach(console.log)
  • [...$$("a[href *='#']")].map(element => console.log(element.href))

Maybe these things could be pointed out separately - what's NodeList, converting spreadables to arrays and also applying array methods to spreadable items directly. You know - [...$$('a')].map(myFun) creates an array while Array.prototype.map.call($$('a'), myFun) uses the map method on whatever.

[...$$("a[href *='#']")].forEach(console.log)

Value vs Reference small error

In the first section the proposed output is not correct

let var1 = 'My string';
let var2 = var1;

var2 = 'My string';

console.log(var1);
// 'My string'
console.log(var2);
// 'My new string'

For console.log(var2); to output My new string line 4 needs to be var2 = 'My new string'

Great article, tiny correction.

Great article !

Tiny correction.

It says:
Accordingly, reassigning var2 has not effect on var1.

It should say:
Accordingly, reassigning var2 has no effect on var1.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.