JavaScript Best Practices

Ahmed Murtaza

ahmedgmurtaza

@ahmedgmurtaza

codepen.io/ahmedgmurtaza

codesandbox.io/u/Ahmedgmurtaza

slides.com/ahmedmurtaza

What this workshop is

  • Will look into basic but Must-to-do coding practices in javascript
  • will cover Hoisting
  • Will go through chrome dev tools + eslint

 

1 - Use === Instead of ==

 

BUT

CORRECT

WRONG

 

2 - Don't use short-hand, use {}, () when necessory

 

Bad

Good

( always use brackets)

3 - Place Scripts at the Bottom of Your Page

  • Load HTML document before sub document resources
  • Specially when using DOM manipulation 

4 - Declare Variables Outside loops

Bad

Good

5 - Reduce Globals

"By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries."
- Douglas Crockford

Better

6 - /* Comment your code */

  • Easy to grasp the code context after months
  • Extremely useful for team projects
  • Less documentation required

 

7 - Long List of Variables? Omit the var/const/let Keyword and Use Commas Instead

Better

8 - Always, Always use Semicolons;

Example

when missing semicolons become problematic

Example

when inserting semicolons gives unexpected results

To convert it into expected behavior, we need to pull { from line 3 to line 2 to make JavaScript not insert a semicolon on line 2

9 - Self-executing functions

  1. Helps to reduce conflicts from other scripts and libraries 

10 - Hoisting

  • Hoist declaration, not initialization
  • Allows you to use a function before you declare it in your code

Only declarations are hoisted

Your expectations

How it works..

What do you think will print?

Answer

 

11 - Use ESLint

 

  • Bug free code
  • Consistent code quality
  • Configure your own style guidelines

Extensions are available

12 - Use Chrome Dev Tools

  • Elements
  • Resources
  • Network
  • Sources
  • Console
  • ...more

https://developers.google.com/web/tools/chrome-devtools/

For more details

11 - Use Chrome Dev Tools

Elements

 

Resources

 

11 - Use Chrome Dev Tools

Network

 

11 - Use Chrome Dev Tools

Console

11 - Use Chrome Dev Tools

References

  • https://app.pluralsight.com/library/courses/javascript-best-practices/table-of-contents

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

Javascript best practices

By Ahmed Murtaza

Javascript best practices

Must-to-do coding practices for Javascript developers. ESLint and Chrome dev tool are also part of this presentation.

  • 335