Downloads & Free Reading Options - Results

Javascript by Thomas A. Powell

Read "Javascript" by Thomas A. Powell through these free online access and download options.

Search for Downloads

Search by Title or Author

Books Results

Source: The Internet Archive

The internet Archive Search Results

Available books for downloads and borrow from The internet Archive

1Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 31. Projeto Final Game Estourando Balões Arquivos Do Projeto

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 31. Projeto final - Game estourando balões - arquivos do projeto

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 31. Projeto Final Game Estourando Balões Arquivos Do Projeto” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 31. Projeto Final Game Estourando Balões Arquivos Do Projeto

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s went public at Sat May 15 2021.

Available formats:
HTML - Metadata -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 31. Projeto Final Game Estourando Balões Arquivos Do Projeto at online marketplaces:


2Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 32. Projeto Final Game Estourando Balões Parte 1

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 32. Projeto final - Game estourando balões - parte 1

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 32. Projeto Final Game Estourando Balões Parte 1” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 32. Projeto Final Game Estourando Balões Parte 1

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.03 Mbs, the file-s went public at Fri May 14 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 32. Projeto Final Game Estourando Balões Parte 1 at online marketplaces:


3Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 25. Eventos Parte 4 De 4 Formulário

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 25. Eventos - parte 4 de 4 formulário

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 25. Eventos Parte 4 De 4 Formulário” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 25. Eventos Parte 4 De 4 Formulário

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.03 Mbs, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 25. Eventos Parte 4 De 4 Formulário at online marketplaces:


4Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 18. Estruturas De Repetição Parte 3 De 4 Do While

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 18. Estruturas de repetição - parte 3 de 4 do while

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 18. Estruturas De Repetição Parte 3 De 4 Do While” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 18. Estruturas De Repetição Parte 3 De 4 Do While

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 18. Estruturas De Repetição Parte 3 De 4 Do While at online marketplaces:


5Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 23. Estruturas De Repetição Parte 3 De 5 Do While

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 12. PHP 23. Estruturas de repetição - parte 3 de 5 do while

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 23. Estruturas De Repetição Parte 3 De 5 Do While” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 23. Estruturas De Repetição Parte 3 De 5 Do While

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.03 Mbs, the file-s for this book were downloaded 3 times, the file-s went public at Sun May 16 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 23. Estruturas De Repetição Parte 3 De 5 Do While at online marketplaces:


6Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 3. HTML 2. O Que É HTML

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 3. HTML 2. O que é HTML

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 3. HTML 2. O Que É HTML” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 3. HTML 2. O Que É HTML

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Mon May 17 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 3. HTML 2. O Que É HTML at online marketplaces:


7Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 17. PHP & My SQL Projeto Aplicado Twitter Clone 15. Cadastro De Usuário Bloquear Inclusão De Usuários Já Cadastrados Parte 1

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 17. PHP & MySQL - Projeto aplicado Twitter Clone 15. Cadastro de usuário - Bloquear inclusão de usuários já cadastrados parte 1

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 17. PHP & My SQL Projeto Aplicado Twitter Clone 15. Cadastro De Usuário Bloquear Inclusão De Usuários Já Cadastrados Parte 1” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 17. PHP & My SQL Projeto Aplicado Twitter Clone 15. Cadastro De Usuário Bloquear Inclusão De Usuários Já Cadastrados Parte 1

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.04 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 17. PHP & My SQL Projeto Aplicado Twitter Clone 15. Cadastro De Usuário Bloquear Inclusão De Usuários Já Cadastrados Parte 1 at online marketplaces:


8Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 10. Download Projeto Auxiliar Catálogo De Produtos

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 12. PHP 10. Download - Projeto auxiliar catálogo de produtos

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 10. Download Projeto Auxiliar Catálogo De Produtos” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 10. Download Projeto Auxiliar Catálogo De Produtos

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Sat May 15 2021.

Available formats:
HTML - Metadata -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 12. PHP 10. Download Projeto Auxiliar Catálogo De Produtos at online marketplaces:


9Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 14. Operadores Aritméticos

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 14. Operadores aritméticos

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 14. Operadores Aritméticos” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 14. Operadores Aritméticos

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 14. Operadores Aritméticos at online marketplaces:


10Splatty-doo And Other JavaScript Features You Should Avoid - JSJ 543

By

Today in this all panelist episode, we talk about JS features you should avoid using. However opinions don't always align, and some come with much debate! Although we couldn't cover them all, today we discuss:eval withargumentsdo while for I++continue classesprototypesthisvar with letdeleteSponsorsTop End DevsRaygun | Click here to get started on your free 14-day trialCoaching | Top End DevsLinksJavaScript Remote Conference 2022Twitter: ?@cmaxwPicksAJ- Virginia Ctenucha Ctenucha virginica (Esper, 1794) | Butterflies and Moths of North AmericaAJ- The Mistborn Trilogy by Brandon SandersonAJ- Thread pitch gauge at Lowes.com: Search ResultsCharles- AntidoteCharles- Conferences | Top End DevsCharles- 1883 - Yellowstone Prequel (Official Site) Watch on Paramount+Dan- Can I use... Support tables for HTML5, CSS3, etcDan - War in UkraineDan- Webb Space Telescope GSFC/NASASteve- Coworker Standing At Desk Obviously Just Hasn't Learned About Chairs YetSteve - Dad Jokes

“Splatty-doo And Other JavaScript Features You Should Avoid - JSJ 543” Metadata:

  • Title: ➤  Splatty-doo And Other JavaScript Features You Should Avoid - JSJ 543
  • Author:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 55.14 Mbs, the file-s for this book were downloaded 5 times, the file-s went public at Sat Aug 27 2022.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find Splatty-doo And Other JavaScript Features You Should Avoid - JSJ 543 at online marketplaces:


11182: The Weight Of Javascript

By

Ben finalizes Formkeep's Ember removal, toys with the idea of manual on boarding, and positions himself to begin experimenting with plans and pricing. Meanwhile, Chris deals with credit card fraud, too many inodes on Upcase's server, and finishes the changes required to offer free videos.UpcaseFormkeepBarbell Investment StrategyDesigning Forms That ConvertFree Gitsh Video from The Weekly IterationWhat is 2.5 * 26?Support Giant Robots Smashing Into Other Giant Robots

“182: The Weight Of Javascript” Metadata:

  • Title: 182: The Weight Of Javascript
  • Author: ➤  

“182: The Weight Of Javascript” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 47.20 Mbs, the file-s for this book were downloaded 4 times, the file-s went public at Sun Mar 07 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find 182: The Weight Of Javascript at online marketplaces:


12JSON And JavaScript (The Changelog #26)

By

While at TXJS - Adam and Wynn caught up with Douglas Crockford, author of both JavaScript: The Good Parts and the JSON spec, and a global namespace unto himself.

“JSON And JavaScript (The Changelog #26)” Metadata:

  • Title: ➤  JSON And JavaScript (The Changelog #26)
  • Author:

“JSON And JavaScript (The Changelog #26)” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 7.65 Mbs, the file-s for this book were downloaded 6 times, the file-s went public at Wed Feb 24 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find JSON And JavaScript (The Changelog #26) at online marketplaces:


13JavaScript In Latin America (JS Party #5)

By

Mikeal Rogers, Alex Sexton, and special guest Juan Pablo Buritica discuss all things JavaScript in Latin America. The conferences, the communities, the meetups, JavaScript tooling, and more.

“JavaScript In Latin America (JS Party #5)” Metadata:

  • Title: ➤  JavaScript In Latin America (JS Party #5)
  • Author:

“JavaScript In Latin America (JS Party #5)” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 87.11 Mbs, the file-s for this book were downloaded 2 times, the file-s went public at Wed Feb 24 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find JavaScript In Latin America (JS Party #5) at online marketplaces:


14Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 4. Variáveis

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 9. JavaScript 4. Variáveis

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 4. Variáveis” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 4. Variáveis

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.03 Mbs, the file-s for this book were downloaded 6 times, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 9. Java Script 4. Variáveis at online marketplaces:


15Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 4. Box Model Modelo De Caixas ( Arquivos Do Projeto)

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 5. CSS Intermediário 4. Box Model  Modelo de caixas - (Arquivos do projeto)

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 4. Box Model Modelo De Caixas ( Arquivos Do Projeto)” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 4. Box Model Modelo De Caixas ( Arquivos Do Projeto)

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Sat May 15 2021.

Available formats:
HTML - Metadata -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 4. Box Model Modelo De Caixas ( Arquivos Do Projeto) at online marketplaces:


16Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 18. Tec Blog Projeto Final Parte I ( Arquivos Do Projeto)

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 5. CSS Intermediário 18. TecBlog Projeto Final - parte I - (Arquivos do projeto)

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 18. Tec Blog Projeto Final Parte I ( Arquivos Do Projeto)” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 18. Tec Blog Projeto Final Parte I ( Arquivos Do Projeto)

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Fri May 14 2021.

Available formats:
HTML - Metadata -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 5. CSS Intermediário 18. Tec Blog Projeto Final Parte I ( Arquivos Do Projeto) at online marketplaces:


17Javascript Numbers Thumbnail

By

Thumbnail art for javascript numbers video.

“Javascript Numbers Thumbnail” Metadata:

  • Title: Javascript Numbers Thumbnail
  • Author:
  • Language: English

Edition Identifiers:

Downloads Information:

The book is available for download in "image" format, the size of the file-s is: 0.54 Mbs, the file-s for this book were downloaded 3 times, the file-s went public at Wed May 14 2025.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata -

Related Links:

Online Marketplaces

Find Javascript Numbers Thumbnail at online marketplaces:


18Obok MeatGod Deleted JavaScript

By

His Obok MeatGod JavaScript Got Community Guidelines And His Account Got Banned For Due Community Guidelines For Graphic Or Sexual Content

“Obok MeatGod Deleted JavaScript” Metadata:

  • Title: ➤  Obok MeatGod Deleted JavaScript
  • Author:
  • Language: English

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 0.02 Mbs, the file-s went public at Wed May 21 2025.

Available formats:
Archive BitTorrent - Metadata - ZIP -

Related Links:

Online Marketplaces

Find Obok MeatGod Deleted JavaScript at online marketplaces:


19Javascript Amozesh Farsi 2 Www.aghazeh.com

sdfghjkl;

“Javascript Amozesh Farsi 2 Www.aghazeh.com” Metadata:

  • Title: ➤  Javascript Amozesh Farsi 2 Www.aghazeh.com

“Javascript Amozesh Farsi 2 Www.aghazeh.com” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 2.87 Mbs, the file-s for this book were downloaded 137 times, the file-s went public at Mon Feb 03 2014.

Available formats:
Archive BitTorrent - Metadata - ZIP -

Related Links:

Online Marketplaces

Find Javascript Amozesh Farsi 2 Www.aghazeh.com at online marketplaces:


20Github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52

By

30 days of JavaScript programming challenge is a step-by-step guide to learn JavaScript programming language in 30 days. This challenge may take more than 100 days, please just follow your own pace. To restore the repository download the bundle wget https://archive.org/download/github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52/Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52.bundle and run: git clone Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52.bundle Source: https://github.com/Asabeneh/30-Days-Of-JavaScript Uploader: Asabeneh Upload date: 2022-02-09

“Github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52” Metadata:

  • Title: ➤  Github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52
  • Author:

“Github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 121.49 Mbs, the file-s for this book were downloaded 69 times, the file-s went public at Wed Feb 09 2022.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-Asabeneh-30-Days-Of-JavaScript_-_2022-02-09_02-39-52 at online marketplaces:


21JSJ 430: Learning JavaScript In 2020 With Matt Crook

By

JavaScript Remote Conf 2020 May 13th to 15th - register now! Matt Crook joins the conversation to talk with the JavaScript Jabber panel to talk about his experience going through Nashville Software School. The panel discusses and asks questions about getting into programming, working through the bootcamp, and what prospects are for bootcamp graduates. Panel ? AJ O’Neal ? Aimee Knight ? Charles Max Wood ? Steve Edwards ? Dan Shappir Guest ? Matt Crook Sponsors ? Taiko ? Educative.io | Click here for 10% discount "The MaxCoders Guide to Finding Your Dream Developer Job" by Charles Max Wood is now available on Amazon. Get Your Copy Today!   Picks AJ O’Neal: ? PostgREST ? The Way of Kings ? VirtualBox ? Bootable Installers for MacOS, Windows, and more Aimee Knight: ? State of Microservices 2020 Report ? Peloton Bike Charles Max Wood: ? The Hobbit ? D&D Starter Set ? JavaScript Weekly ? Devchat.tv Remote Meetups ? Devchat.tv Remote Conferences ? Reading to Kids Steve Edwards: ? It Is Well With My Soul ? Pitbull Gold PRO Skull Shaver ? Brad Balfour Dan Shappir: ? Gödel, Escher, Bach ? Translating "The Hobbit" in Captivity Matt Crook: ? Follow Matt on Twitter > @mgcrook , Instagram , LinkedIn ? Swolenormous ? Fireship ? Static Headz ? Yugen Follow JavaScript Jabber on Twitter > @JSJabber

“JSJ 430: Learning JavaScript In 2020 With Matt Crook” Metadata:

  • Title: ➤  JSJ 430: Learning JavaScript In 2020 With Matt Crook
  • Author:

“JSJ 430: Learning JavaScript In 2020 With Matt Crook” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 68.22 Mbs, the file-s for this book were downloaded 13 times, the file-s went public at Sun Jan 10 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find JSJ 430: Learning JavaScript In 2020 With Matt Crook at online marketplaces:


22GNOME Asia 2012 - Javascript With GNOME

For Schedule of the conference, please see http://2012.gnome.asia/schedule/

“GNOME Asia 2012 - Javascript With GNOME” Metadata:

  • Title: ➤  GNOME Asia 2012 - Javascript With GNOME

“GNOME Asia 2012 - Javascript With GNOME” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 2279.46 Mbs, the file-s for this book were downloaded 302 times, the file-s went public at Sat Oct 27 2012.

Available formats:
Animated GIF - Archive BitTorrent - Item Tile - Metadata - Ogg Video - Thumbnail - WebM - h.264 -

Related Links:

Online Marketplaces

Find GNOME Asia 2012 - Javascript With GNOME at online marketplaces:


23BADCampUK April 2012 - Craig Moore - Drupal, Javascript And You

By

Source: http://badcampuk.net/sessions/drupal-javascript-and-you-0 The limitations of a technology or platform can be best understood by examining the technologies upon which they are based - in the case of Drupal, we have already made some decisions about how it is implemented and how data is stored (PHP and a database layer such as MySQL). However, Drupal itself is extremely extensible, and Javascript offers unique opportunities for developers who are willing to get their hands dirty. This is a technical talk, starting with the basics of JQuery and integrating Javascript with Drupal, hopefully leading into discussion of options for further integration and the benefits provided.

“BADCampUK April 2012 - Craig Moore - Drupal, Javascript And You” Metadata:

  • Title: ➤  BADCampUK April 2012 - Craig Moore - Drupal, Javascript And You
  • Author:

“BADCampUK April 2012 - Craig Moore - Drupal, Javascript And You” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 750.49 Mbs, the file-s for this book were downloaded 62 times, the file-s went public at Wed May 23 2012.

Available formats:
Animated GIF - Archive BitTorrent - Item Tile - MPEG2 - Metadata - Ogg Video - Thumbnail - Video Index - h.264 -

Related Links:

Online Marketplaces

Find BADCampUK April 2012 - Craig Moore - Drupal, Javascript And You at online marketplaces:


24FollowUp20 JavaScript Part13

FollowUp20 JavaScript Part13

“FollowUp20 JavaScript Part13” Metadata:

  • Title: FollowUp20 JavaScript Part13

“FollowUp20 JavaScript Part13” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 288.49 Mbs, the file-s for this book were downloaded 106 times, the file-s went public at Tue Jan 22 2008.

Available formats:
512Kb MPEG4 - Animated GIF - Archive BitTorrent - Cinepack - Item Tile - Metadata - Ogg Video - Thumbnail -

Related Links:

Online Marketplaces

Find FollowUp20 JavaScript Part13 at online marketplaces:


25Github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25

By

Starter files, final projects and FAQ for my Complete JavaScript course Course Material and FAQ for my Complete JavaScript Course This repo contains starter files and the finished project files for all the projects contained in the course. Plus, I made all the course slides available for download , to make it easier to follow along the conceptual videos. 👇 Please read the following Frequently Asked Questions (FAQ) carefully before starting the course 👇 FAQ Q1: How do I download the files? A: If you're new to GitHub and just want to download the complete package, hit the green button saying "Clone or download", choose the "Download ZIP" option, and you're good to go. Q2: I'm stuck in one of the projects. Where do I get help? A: Have you extensively tried fixing the problem on your own? If you failed at fixing it, please post a detailled description of the problem to the Q&A area of that video over at Udemy , along with a codepen containing your code. You will get help as fast as possible! Please don't send me a personal message or email to fix coding problems. Q3: Brackets shows me errors, but my code works. Why is that? A: These are not errors in your code, and you can simply ignore them (they just come from so-called linters that are not correctly set up). Q4: You keep mentioning your resources page. Where can I find it? A: It's on my website at http://codingheroes.io/resources . You can subscribe for updates 😉 Q5: What Brackets and VSCode themes are you using? A: I use the theme "OS X Style | Flat & Dark" in Brackets and "Oceanic Next (dimmed bg)" in VSCode. Here is the complete setup . Q6: Can I see a final version of the course projects? A: Sure, I have an online version of all three. Here they are: Pig Game (DOM manipulation), Budgety (advanced JavaScript) and Forkify (modern JavaScript and AJAX). Q7: Videos don't load, can you fix it? A: Unfortunately, there is nothing I can do about it. The course is hosted on Udemy's platform, and sometimes they have small technical issues like this one. Please just come back a bit later or contact their support team . Q8: Videos are blurred / have low quality, can you fix it? A: Please open video settings and change the quality from 'Auto' to another value, for example 720p. If that doesn't help, please contact the Udemy support team . Q9: Are the videos downloadable? A: Yes, I made all videos downloadable on the Udemy platform so you can learn even without an internet connection. To download a video, use the settings icon in the right bottom corner of the video player. Q10: I love your courses and want to get updates on new courses. How? A: First, you can subscribe to my email list at my website . Plus, I make important announcements on twitter @jonasschmedtman , so you should definitely follow me there 🔥 Q11: How do I get my certificate of completion? A: A certificate of completion is provided by Udemy after you complete 100% of the course. After completing the course, just click on the "Your progress" indicator in the top right-hand corner of the course page. If you want to change your name on the certificate, please contact the Udemy support team . Q12: Do you accept pull requests? A: No, for the simple reason that I want this repository to contain the exact same code that is shown in the videos. However, please feel free to add an issue if you found one. To restore the repository download the bundle wget https://archive.org/download/github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25/jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25.bundle and run: git clone jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25.bundle Source: https://github.com/jonasschmedtmann/complete-javascript-course Uploader: jonasschmedtmann Upload date: 2019-11-17

“Github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25” Metadata:

  • Title: ➤  Github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25
  • Author:

“Github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 27.71 Mbs, the file-s for this book were downloaded 117 times, the file-s went public at Mon Nov 25 2019.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-jonasschmedtmann-complete-javascript-course_-_2019-11-17_20-33-25 at online marketplaces:


26GitHub JavaScript Dump October 2016

A dump of the top

“GitHub JavaScript Dump October 2016” Metadata:

  • Title: ➤  GitHub JavaScript Dump October 2016
  • Language: English

“GitHub JavaScript Dump October 2016” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 13112.35 Mbs, the file-s for this book were downloaded 72 times, the file-s went public at Wed Nov 30 2016.

Available formats:
Archive BitTorrent - Metadata - Unknown -

Related Links:

Online Marketplaces

Find GitHub JavaScript Dump October 2016 at online marketplaces:


27Github.com-airbnb-javascript_-_2022-05-26_04-23-02

By

JavaScript Style Guide Airbnb JavaScript Style Guide() { A mostly reasonable approach to JavaScript Note : this guide assumes you are using Babel , and requires that you use babel-preset-airbnb or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims or the equivalent. This guide is available in other languages too. See Translation Other Style Guides ES5 (Deprecated) React CSS-in-JavaScript CSS & Sass Ruby Table of Contents Types References Objects Arrays Destructuring Strings Functions Arrow Functions Classes & Constructors Modules Iterators and Generators Properties Variables Hoisting Comparison Operators & Equality Blocks Control Statements Comments Whitespace Commas Semicolons Type Casting & Coercion Naming Conventions Accessors Events jQuery ECMAScript 5 Compatibility ECMAScript 6+ (ES 2015+) Styles Standard Library Testing Performance Resources In the Wild Translation The JavaScript Style Guide Guide Chat With Us About JavaScript Contributors License Amendments Types - 1.1 Primitives : When you access a primitive type you work directly on its value. - `string`- `number`- `boolean`- `null`- `undefined`- `symbol`- `bigint````javascriptconst foo = 1;let bar = foo;bar = 9;console.log(foo, bar); // => 1, 9```- Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively. - 1.2 Complex : When you access a complex type you work on a reference to its value. - `object`- `array`- `function````javascriptconst foo = [1, 2];const bar = foo;bar[0] = 9;console.log(foo[0], bar[0]); // => 9, 9``` ⬆ back to top References - 2.1 Use const for all of your references; avoid using var . eslint: <code>prefer-const</code> , <code>no-const-assign</code> > Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.```javascript// badvar a = 1;var b = 2;// goodconst a = 1;const b = 2;``` - 2.2 If you must reassign references, use let instead of var . eslint: <code>no-var</code> > Why? `let` is block-scoped rather than function-scoped like `var`.```javascript// badvar count = 1;if (true) { count += 1;}// good, use the let.let count = 1;if (true) { count += 1;}``` - 2.3 Note that both let and const are block-scoped, whereas var is function-scoped. ```javascript// const and let only exist in the blocks they are defined in.{ let a = 1; const b = 1; var c = 1;}console.log(a); // ReferenceErrorconsole.log(b); // ReferenceErrorconsole.log(c); // Prints 1```In the above code, you can see that referencing `a` and `b` will produce a ReferenceError, while `c` contains the number. This is because `a` and `b` are block scoped, while `c` is scoped to the containing function. ⬆ back to top Objects - 3.1 Use the literal syntax for object creation. eslint: <code>no-new-object</code> ```javascript// badconst item = new Object();// goodconst item = {};``` - 3.2 Use computed property names when creating objects with dynamic property names. > Why? They allow you to define all the properties of an object in one place.```javascriptfunction getKey(k) { return `a key named ${k}`;}// badconst obj = { id: 5, name: 'San Francisco',};obj[getKey('enabled')] = true;// goodconst obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true,};``` - 3.3 Use object method shorthand. eslint: <code>object-shorthand</code> ```javascript// badconst atom = { value: 1, addValue: function (value) { return atom.value + value; },};// goodconst atom = { value: 1, addValue(value) { return atom.value + value; },};``` - 3.4 Use property value shorthand. eslint: <code>object-shorthand</code> > Why? It is shorter and descriptive.```javascriptconst lukeSkywalker = 'Luke Skywalker';// badconst obj = { lukeSkywalker: lukeSkywalker,};// goodconst obj = { lukeSkywalker,};``` - 3.5 Group your shorthand properties at the beginning of your object declaration. > Why? It’s easier to tell which properties are using the shorthand.```javascriptconst anakinSkywalker = 'Anakin Skywalker';const lukeSkywalker = 'Luke Skywalker';// badconst obj = { episodeOne: 1, twoJediWalkIntoACantina: 2, lukeSkywalker, episodeThree: 3, mayTheFourth: 4, anakinSkywalker,};// goodconst obj = { lukeSkywalker, anakinSkywalker, episodeOne: 1, twoJediWalkIntoACantina: 2, episodeThree: 3, mayTheFourth: 4,};``` - 3.6 Only quote properties that are invalid identifiers. eslint: <code>quote-props</code> > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.```javascript// badconst bad = { 'foo': 3, 'bar': 4, 'data-blah': 5,};// goodconst good = { foo: 3, bar: 4, 'data-blah': 5,};``` - 3.7 Do not call Object.prototype methods directly, such as hasOwnProperty , propertyIsEnumerable , and isPrototypeOf . eslint: <code>no-prototype-builtins</code> > Why? These methods may be shadowed by properties on the object in question - consider `{ hasOwnProperty: false }` - or, the object may be a null object (`Object.create(null)`).```javascript// badconsole.log(object.hasOwnProperty(key));// goodconsole.log(Object.prototype.hasOwnProperty.call(object, key));// bestconst has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.console.log(has.call(object, key));/* or */import has from 'has'; // https://www.npmjs.com/package/hasconsole.log(has(object, key));``` - 3.8 Prefer the object spread syntax over <code>Object.assign</code> to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint: <code>prefer-object-spread</code> ```javascript// very badconst original = { a: 1, b: 2 };const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠdelete copy.a; // so does this// badconst original = { a: 1, b: 2 };const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }// goodconst original = { a: 1, b: 2 };const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }const { a, ...noA } = copy; // noA => { b: 2, c: 3 }``` ⬆ back to top Arrays - 4.1 Use the literal syntax for array creation. eslint: <code>no-array-constructor</code> ```javascript// badconst items = new Array();// goodconst items = [];``` - 4.2 Use Array#push instead of direct assignment to add items to an array. ```javascriptconst someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');``` - 4.3 Use array spreads ... to copy arrays. ```javascript// badconst len = items.length;const itemsCopy = [];let i;for (i = 0; i < len; i += 1) { itemsCopy[i] = items[i];}// goodconst itemsCopy = [...items];``` - 4.4 To convert an iterable object to an array, use spreads ... instead of <code>Array.from</code> ```javascriptconst foo = document.querySelectorAll('.foo');// goodconst nodes = Array.from(foo);// bestconst nodes = [...foo];``` - 4.5 Use <code>Array.from</code> for converting an array-like object to an array. ```javascriptconst arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };// badconst arr = Array.prototype.slice.call(arrLike);// goodconst arr = Array.from(arrLike);``` - 4.6 Use <code>Array.from</code> instead of spread ... for mapping over iterables, because it avoids creating an intermediate array. ```javascript// badconst baz = [...foo].map(bar);// goodconst baz = Array.from(foo, bar);``` - 4.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2 . eslint: <code>array-callback-return</code> ```javascript// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => x + 1);// bad - no returned value means `acc` becomes undefined after the first iteration[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item);});// good[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); return flatten;});// badinbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } else { return false; }});// goodinbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } return false;});``` - 4.8 Use line breaks after open and before close array brackets if an array has multiple lines ```javascript// badconst arr = [ [0, 1], [2, 3], [4, 5],];const objectInArray = [{ id: 1,}, { id: 2,}];const numberInArray = [ 1, 2,];// goodconst arr = [[0, 1], [2, 3], [4, 5]];const objectInArray = [ { id: 1, }, { id: 2, },];const numberInArray = [ 1, 2,];``` ⬆ back to top Destructuring - 5.1 Use object destructuring when accessing and using multiple properties of an object. eslint: <code>prefer-destructuring</code> > Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.```javascript// badfunction getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`;}// goodfunction getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`;}// bestfunction getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`;}``` - 5.2 Use array destructuring. eslint: <code>prefer-destructuring</code> ```javascriptconst arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;``` - 5.3 Use object destructuring for multiple return values, not array destructuring. > Why? You can add new properties over time or change the order of things without breaking call sites.```javascript// badfunction processInput(input) { // then a miracle occurs return [left, right, top, bottom];}// the caller needs to think about the order of return dataconst [left, __, top] = processInput(input);// goodfunction processInput(input) { // then a miracle occurs return { left, right, top, bottom };}// the caller selects only the data they needconst { left, top } = processInput(input);``` ⬆ back to top Strings - 6.1 Use single quotes '' for strings. eslint: <code>quotes</code> ```javascript// badconst name = "Capt. Janeway";// bad - template literals should contain interpolation or newlinesconst name = `Capt. Janeway`;// goodconst name = 'Capt. Janeway';``` - 6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation. > Why? Broken strings are painful to work with and make code less searchable.```javascript// badconst errorMessage = 'This is a super long error that was thrown because \of Batman. When you stop to think about how Batman had anything to do \with this, you would get nowhere \fast.';// badconst errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.';// goodconst errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';``` - 6.3 When programmatically building up strings, use template strings instead of concatenation. eslint: <code>prefer-template</code> <code>template-curly-spacing</code> > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.```javascript// badfunction sayHi(name) { return 'How are you, ' + name + '?';}// badfunction sayHi(name) { return ['How are you, ', name, '?'].join();}// badfunction sayHi(name) { return `How are you, ${ name }?`;}// goodfunction sayHi(name) { return `How are you, ${name}?`;}``` - 6.4 Never use eval() on a string, it opens too many vulnerabilities. eslint: <code>no-eval</code> - 6.5 Do not unnecessarily escape characters in strings. eslint: <code>no-useless-escape</code> > Why? Backslashes harm readability, thus they should only be present when necessary.```javascript// badconst foo = '\'this\' \i\s \"quoted\"';// goodconst foo = '\'this\' is "quoted"';const foo = `my name is '${name}'`;``` ⬆ back to top Functions - 7.1 Use named function expressions instead of function declarations. eslint: <code>func-style</code> > Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. ([Discussion](https://github.com/airbnb/javascript/issues/794))```javascript// badfunction foo() { // ...}// badconst foo = function () { // ...};// good// lexical name distinguished from the variable-referenced invocation(s)const short = function longUniqueMoreDescriptiveLexicalFoo() { // ...};``` - 7.2 Wrap immediately invoked function expressions in parentheses. eslint: <code>wrap-iife</code> > Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.```javascript// immediately-invoked function expression (IIFE)(function () { console.log('Welcome to the Internet. Please follow me.');}());``` - 7.3 Never declare a function in a non-function block ( if , while , etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint: <code>no-loop-func</code> - 7.4 Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. ```javascript// badif (currentUser) { function test() { console.log('Nope.'); }}// goodlet test;if (currentUser) { test = () => { console.log('Yup.'); };}``` - 7.5 Never name a parameter arguments . This will take precedence over the arguments object that is given to every function scope. ```javascript// badfunction foo(name, options, arguments) { // ...}// goodfunction foo(name, options, args) { // ...}``` - 7.6 Never use arguments , opt to use rest syntax ... instead. eslint: <code>prefer-rest-params</code> > Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`.```javascript// badfunction concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join('');}// goodfunction concatenateAll(...args) { return args.join('');}``` - 7.7 Use default parameter syntax rather than mutating function arguments. ```javascript// really badfunction handleThings(opts) { // No! We shouldn’t mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may // be what you want but it can introduce subtle bugs. opts = opts || {}; // ...}// still badfunction handleThings(opts) { if (opts === void 0) { opts = {}; } // ...}// goodfunction handleThings(opts = {}) { // ...}``` - 7.8 Avoid side effects with default parameters. > Why? They are confusing to reason about.```javascriptvar b = 1;// badfunction count(a = b++) { console.log(a);}count(); // 1count(); // 2count(3); // 3count(); // 3``` - 7.9 Always put default parameters last. eslint: <code>default-param-last</code> ```javascript// badfunction handleThings(opts = {}, name) { // ...}// goodfunction handleThings(name, opts = {}) { // ...}``` - 7.10 Never use the Function constructor to create a new function. eslint: <code>no-new-func</code> > Why? Creating a function in this way evaluates a string similarly to `eval()`, which opens vulnerabilities.```javascript// badvar add = new Function('a', 'b', 'return a + b');// still badvar subtract = Function('a', 'b', 'return a - b');``` - 7.11 Spacing in a function signature. eslint: <code>space-before-function-paren</code> <code>space-before-blocks</code> > Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.```javascript// badconst f = function(){};const g = function (){};const h = function() {};// goodconst x = function () {};const y = function a() {};``` - 7.12 Never mutate parameters. eslint: <code>no-param-reassign</code> > Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.```javascript// badfunction f1(obj) { obj.key = 1;}// goodfunction f2(obj) { const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;}``` - 7.13 Never reassign parameters. eslint: <code>no-param-reassign</code> > Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the `arguments` object. It can also cause optimization issues, especially in V8.```javascript// badfunction f1(a) { a = 1; // ...}function f2(a) { if (!a) { a = 1; } // ...}// goodfunction f3(a) { const b = a || 1; // ...}function f4(a = 1) { // ...}``` - 7.14 Prefer the use of the spread syntax ... to call variadic functions. eslint: <code>prefer-spread</code> > Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose `new` with `apply`.```javascript// badconst x = [1, 2, 3, 4, 5];console.log.apply(console, x);// goodconst x = [1, 2, 3, 4, 5];console.log(...x);// badnew (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));// goodnew Date(...[2016, 8, 5]);``` - 7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint: <code>function-paren-newline</code> ```javascript// badfunction foo(bar, baz, quux) { // ...}// goodfunction foo( bar, baz, quux,) { // ...}// badconsole.log(foo, bar, baz);// goodconsole.log( foo, bar, baz,);``` ⬆ back to top Arrow Functions - 8.1 When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint: <code>prefer-arrow-callback</code> , <code>arrow-spacing</code> > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.> Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.```javascript// bad[1, 2, 3].map(function (x) { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});``` - 8.2 If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a return statement. eslint: <code>arrow-parens</code> , <code>arrow-body-style</code> > Why? Syntactic sugar. It reads well when multiple functions are chained together.```javascript// bad[1, 2, 3].map((number) => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`;});// good[1, 2, 3].map((number) => `A string containing the ${number + 1}.`);// good[1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`;});// good[1, 2, 3].map((number, index) => ({ [index]: number,}));// No implicit return with side effectsfunction foo(callback) { const val = callback(); if (val === true) { // Do something if callback returns true }}let bool = false;// badfoo(() => bool = true);// goodfoo(() => { bool = true;});``` - 8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability. > Why? It shows clearly where the function starts and ends.```javascript// bad['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ));// good['get', 'post', 'put'].map((httpMethod) => ( Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, )));``` - 8.4 Always include parentheses around arguments for clarity and consistency. eslint: <code>arrow-parens</code> > Why? Minimizes diff churn when adding or removing arguments.```javascript// bad[1, 2, 3].map(x => x * x);// good[1, 2, 3].map((x) => x * x);// bad[1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// good[1, 2, 3].map((number) => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});``` - 8.5 Avoid confusing arrow function syntax ( => ) with comparison operators ( <= , >= ). eslint: <code>no-confusing-arrow</code> ```javascript// badconst itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => { const { height, largeSize, smallSize } = item; return height <= 256 ? largeSize : smallSize;};``` - 8.6 Enforce the location of arrow function bodies with implicit returns. eslint: <code>implicit-arrow-linebreak</code> ```javascript// bad(foo) => bar;(foo) => (bar);// good(foo) => bar;(foo) => (bar);(foo) => ( bar)``` ⬆ back to top Classes & Constructors - 9.1 Always use class . Avoid manipulating prototype directly. > Why? `class` syntax is more concise and easier to reason about.```javascript// badfunction Queue(contents = []) { this.queue = [...contents];}Queue.prototype.pop = function () { const value = this.queue[0]; this.queue.splice(0, 1); return value;};// goodclass Queue { constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; }}``` - 9.2 Use extends for inheritance. > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.```javascript// badconst inherits = require('inherits');function PeekableQueue(contents) { Queue.apply(this, contents);}inherits(PeekableQueue, Queue);PeekableQueue.prototype.peek = function () { return this.queue[0];};// goodclass PeekableQueue extends Queue { peek() { return this.queue[0]; }}``` - 9.3 Methods can return this to help with method chaining. ```javascript// badJedi.prototype.jump = function () { this.jumping = true; return true;};Jedi.prototype.setHeight = function (height) { this.height = height;};const luke = new Jedi();luke.jump(); // => trueluke.setHeight(20); // => undefined// goodclass Jedi { jump() { this.jumping = true; return this; } setHeight(height) { this.height = height; return this; }}const luke = new Jedi();luke.jump() .setHeight(20);``` - 9.4 It’s okay to write a custom toString() method, just make sure it works successfully and causes no side effects. ```javascriptclass Jedi { constructor(options = {}) { this.name = options.name || 'no name'; } getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; }}``` - 9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: <code>no-useless-constructor</code> ```javascript// badclass Jedi { constructor() {} getName() { return this.name; }}// badclass Rey extends Jedi { constructor(...args) { super(...args); }}// goodclass Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; }}``` - 9.6 Avoid duplicate class members. eslint: <code>no-dupe-class-members</code> > Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.```javascript// badclass Foo { bar() { return 1; } bar() { return 2; }}// goodclass Foo { bar() { return 1; }}// goodclass Foo { bar() { return 2; }}``` - 9.7 Class methods should use this or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver. eslint: <code>class-methods-use-this</code> ```javascript// badclass Foo { bar() { console.log('bar'); }}// good - this is usedclass Foo { bar() { console.log(this.bar); }}// good - constructor is exemptclass Foo { constructor() { // ... }}// good - static methods aren't expected to use thisclass Foo { static bar() { console.log('bar'); }}``` ⬆ back to top Modules - 10.1 Always use modules ( import / export ) over a non-standard module system. You can always transpile to your preferred module system. > Why? Modules are the future, let’s start using the future now.```javascript// badconst AirbnbStyleGuide = require('./AirbnbStyleGuide');module.exports = AirbnbStyleGuide.es6;// okimport AirbnbStyleGuide from './AirbnbStyleGuide';export default AirbnbStyleGuide.es6;// bestimport { es6 } from './AirbnbStyleGuide';export default es6;``` - 10.2 Do not use wildcard imports. > Why? This makes sure you have a single default export.```javascript// badimport * as AirbnbStyleGuide from './AirbnbStyleGuide';// goodimport AirbnbStyleGuide from './AirbnbStyleGuide';``` - 10.3 And do not export directly from an import. > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.```javascript// bad// filename es6.jsexport { es6 as default } from './AirbnbStyleGuide';// good// filename es6.jsimport { es6 } from './AirbnbStyleGuide';export default es6;``` - 10.4 Only import from a path in one place. eslint: <code>no-duplicate-imports</code> Why? Having multiple lines that import from the same path can make code harder to maintain. ```javascript// badimport foo from 'foo';// … some other imports … //import { named1, named2 } from 'foo';// goodimport foo, { named1, named2 } from 'foo';// goodimport foo, { named1, named2,} from 'foo';``` - 10.5 Do not export mutable bindings. eslint: <code>import/no-mutable-exports</code> Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported. ```javascript// badlet foo = 3;export { foo };// goodconst foo = 3;export { foo };``` - 10.6 In modules with a single export, prefer default export over named export. eslint: <code>import/prefer-default-export</code> Why? To encourage more files that only ever export one thing, which is better for readability and maintainability. ```javascript// badexport function foo() {}// goodexport default function foo() {}``` - 10.7 Put all import s above non-import statements. eslint: <code>import/first</code> Why? Since import s are hoisted, keeping them all at the top prevents surprising behavior. ```javascript// badimport foo from 'foo';foo.init();import bar from 'bar';// goodimport foo from 'foo';import bar from 'bar';foo.init();``` - 10.8 Multiline imports should be indented just like multiline array and object literals. eslint: <code>object-curly-newline</code> > Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.```javascript// badimport {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';// goodimport { longNameA, longNameB, longNameC, longNameD, longNameE,} from 'path';``` - 10.9 Disallow Webpack loader syntax in module import statements. eslint: <code>import/no-webpack-loader-syntax</code> Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in webpack.config.js . ```javascript// badimport fooSass from 'css!sass!foo.scss';import barCss from 'style!css!bar.css';// goodimport fooSass from 'foo.scss';import barCss from 'bar.css';``` - 10.10 Do not include JavaScript filename extensions eslint: <code>import/extensions</code> Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer. ```javascript// badimport foo from './foo.js';import bar from './bar.jsx';import baz from './baz/index.jsx';// goodimport foo from './foo';import bar from './bar';import baz from './baz';``` ⬆ back to top Iterators and Generators - 11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of . eslint: <code>no-iterator</code> <code>no-restricted-syntax</code> > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.> Use `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... to iterate over arrays, and `Object.keys()` / `Object.values()` / `Object.entries()` to produce arrays so you can iterate over objects.```javascriptconst numbers = [1, 2, 3, 4, 5];// badlet sum = 0;for (let num of numbers) { sum += num;}sum === 15;// goodlet sum = 0;numbers.forEach((num) => { sum += num;});sum === 15;// best (use the functional force)const sum = numbers.reduce((total, num) => total + num, 0);sum === 15;// badconst increasedByOne = [];for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1);}// goodconst increasedByOne = [];numbers.forEach((num) => { increasedByOne.push(num + 1);});// best (keeping it functional)const increasedByOne = numbers.map((num) => num + 1);``` - 11.2 Don’t use generators for now. > Why? They don’t transpile well to ES5. - 11.3 If you must use generators, or if you disregard our advice , make sure their function signature is spaced properly. eslint: <code>generator-star-spacing</code> > Why? `function` and `*` are part of the same conceptual keyword - `*` is not a modifier for `function`, `function*` is a unique construct, different from `function`.```javascript// badfunction * foo() { // ...}// badconst bar = function * () { // ...};// badconst baz = function *() { // ...};// badconst quux = function*() { // ...};// badfunction*foo() { // ...}// badfunction *foo() { // ...}// very badfunction*foo() { // ...}// very badconst wat = function*() { // ...};// goodfunction* foo() { // ...}// goodconst foo = function* () { // ...};``` ⬆ back to top Properties - 12.1 Use dot notation when accessing properties. eslint: <code>dot-notation</code> ```javascriptconst luke = { jedi: true, age: 28,};// badconst isJedi = luke['jedi'];// goodconst isJedi = luke.jedi;``` - 12.2 Use bracket notation [] when accessing properties with a variable. ```javascriptconst luke = { jedi: true, age: 28,};function getProp(prop) { return luke[prop];}const isJedi = getProp('jedi');``` - 12.3 Use exponentiation operator ** when calculating exponentiations. eslint: <code>no-restricted-properties</code> . ```javascript// badconst binary = Math.pow(2, 10);// goodconst binary = 2 ** 10;``` ⬆ back to top Variables - 13.1 Always use const or let to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: <code>no-undef</code> <code>prefer-const</code> ```javascript// badsuperPower = new SuperPower();// goodconst superPower = new SuperPower();``` - 13.2 Use one const or let declaration per variable or assignment. eslint: <code>one-var</code> > Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.```javascript// badconst items = getItems(), goSportsTeam = true, dragonball = 'z';// bad// (compare to above, and try to spot the mistake)const items = getItems(), goSportsTeam = true; dragonball = 'z';// goodconst items = getItems();const goSportsTeam = true;const dragonball = 'z';``` - 13.3 Group all your const s and then group all your let s. > Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.```javascript// badlet i, len, dragonball, items = getItems(), goSportsTeam = true;// badlet i;const items = getItems();let dragonball;const goSportsTeam = true;let len;// goodconst goSportsTeam = true;const items = getItems();let dragonball;let i;let length;``` - 13.4 Assign variables where you need them, but place them in a reasonable place. > Why? `let` and `const` are block scoped and not function scoped.```javascript// bad - unnecessary function callfunction checkName(hasName) { const name = getName(); if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name;}// goodfunction checkName(hasName) { if (hasName === 'test') { return false; } const name = getName(); if (name === 'test') { this.setName(''); return false; } return name;}``` - 13.5 Don’t chain variable assignments. eslint: <code>no-multi-assign</code> > Why? Chaining variable assignments creates implicit global variables.```javascript// bad(function example() { // JavaScript interprets this as // let a = ( b = ( c = 1 ) ); // The let keyword only applies to variable a; variables b and c become // global variables. let a = b = c = 1;}());console.log(a); // throws ReferenceErrorconsole.log(b); // 1console.log(c); // 1// good(function example() { let a = 1; let b = a; let c = a;}());console.log(a); // throws ReferenceErrorconsole.log(b); // throws ReferenceErrorconsole.log(c); // throws ReferenceError// the same applies for `const```` - 13.6 Avoid using unary increments and decrements ( ++ , -- ). eslint <code>no-plusplus</code> > Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like `num += 1` instead of `num++` or `num ++`. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.```javascript// badconst array = [1, 2, 3];let num = 1;num++;--num;let sum = 0;let truthyCount = 0;for (let i = 0; i < array.length; i++) { let value = array[i]; sum += value; if (value) { truthyCount++; }}// goodconst array = [1, 2, 3];let num = 1;num += 1;num -= 1;const sum = array.reduce((a, b) => a + b, 0);const truthyCount = array.filter(Boolean).length;``` - 13.7 Avoid linebreaks before or after = in an assignment. If your assignment violates <code>max-len</code> , surround the value in parens. eslint <code>operator-linebreak</code> . > Why? Linebreaks surrounding `=` can obfuscate the value of an assignment.```javascript// badconst foo = superLongLongLongLongLongLongLongLongFunctionName();// badconst foo = 'superLongLongLongLongLongLongLongLongString';// goodconst foo = ( superLongLongLongLongLongLongLongLongFunctionName());// goodconst foo = 'superLongLongLongLongLongLongLongLongString';``` - 13.8 Disallow unused variables. eslint: <code>no-unused-vars</code> > Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.```javascript// badvar some_unused_var = 42;// Write-only variables are not considered as used.var y = 10;y = 5;// A read for a modification of itself is not considered as used.var z = 0;z = z + 1;// Unused function arguments.function getX(x, y) { return x;}// goodfunction getXPlusY(x, y) { return x + y;}var x = 1;var y = a + 2;alert(getXPlusY(x, y));// 'type' is ignored even if unused because it has a rest property sibling.// This is a form of extracting an object that omits the specified keys.var { type, ...coords } = data;// 'coords' is now the 'data' object without its 'type' property.``` ⬆ back to top Hoisting - 14.1 var declarations get hoisted to the top of their closest enclosing function scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ) . It’s important to know why typeof is no longer safe . ```javascript// we know this wouldn’t work (assuming there// is no notDefined global variable)function example() { console.log(notDefined); // => throws a ReferenceError}// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true;}// the interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true;}// using const and letfunction example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true;}``` - 14.2 Anonymous function expressions hoist their variable name, but not the function assignment. ```javascriptfunction example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); };}``` - 14.3 Named function expressions hoist the variable name, not the function name or the function body. ```javascriptfunction example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); };}// the same is true when the function name// is the same as the variable name.function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named'); };}``` - 14.4 Function declarations hoist their name and the function body. ```javascriptfunction example() { superPower(); // => Flying function superPower() { console.log('Flying'); }}``` For more information refer to JavaScript Scoping & Hoisting by Ben Cherry . ⬆ back to top Comparison Operators & Equality - 15.1 Use === and !== over == and != . eslint: <code>eqeqeq</code> - 15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules: - **Objects** evaluate to **true**- **Undefined** evaluates to **false**- **Null** evaluates to **false**- **Booleans** evaluate to **the value of the boolean**- **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**- **Strings** evaluate to **false** if an empty string `''`, otherwise **true**```javascriptif ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true}``` - 15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers. ```javascript// badif (isValid === true) { // ...}// goodif (isValid) { // ...}// badif (name) { // ...}// goodif (name !== '') { // ...}// badif (collection.length) { // ...}// goodif (collection.length > 0) { // ...}``` - 15.4 For more information see Truth Equality and JavaScript by Angus Croll. - 15.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let , const , function , and class ). eslint: <code>no-case-declarations</code> > Why? Lexical declarations are visible in the entire `switch` block but only get initialized when assigned, which only happens when its `case` is reached. This causes problems when multiple `case` clauses attempt to define the same thing.```javascript// badswitch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() { // ... } break; default: class C {}}// goodswitch (foo) { case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() { // ... } break; } case 4: bar(); break; default: { class C {} }}``` - 15.6 Ternaries should not be nested and generally be single line expressions. eslint: <code>no-nested-ternary</code> ```javascript// badconst foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null;// split into 2 separated ternary expressionsconst maybeNull = value1 > value2 ? 'baz' : null;// betterconst foo = maybe1 > maybe2 ? 'bar' : maybeNull;// bestconst foo = maybe1 > maybe2 ? 'bar' : maybeNull;``` - 15.7 Avoid unneeded ternary statements. eslint: <code>no-unneeded-ternary</code> ```javascript// badconst foo = a ? a : b;const bar = c ? true : false;const baz = c ? false : true;// goodconst foo = a || b;const bar = !!c;const baz = !c;``` - 15.8 When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators: + , - , and ** since their precedence is broadly understood. We recommend enclosing / and * in parentheses because their precedence can be ambiguous when they are mixed. eslint: <code>no-mixed-operators</code> > Why? This improves readability and clarifies the developer’s intention.```javascript// badconst foo = a && b < 0 || c > 0 || d + 1 === 0;// badconst bar = a ** b - 5 % d;// bad// one may be confused into thinking (a || b) && cif (a || b && c) { return d;}// badconst bar = a + b / c * d;// goodconst foo = (a && b < 0) || c > 0 || (d + 1 === 0);// goodconst bar = a ** b - (5 % d);// goodif (a || (b && c)) { return d;}// goodconst bar = a + (b / c) * d;``` ⬆ back to top Blocks - 16.1 Use braces with all multiline blocks. eslint: <code>nonblock-statement-body-position</code> ```javascript// badif (test) return false;// goodif (test) return false;// goodif (test) { return false;}// badfunction foo() { return false; }// goodfunction bar() { return false;}``` - 16.2 If you’re using multiline blocks with if and else , put else on the same line as your if block’s closing brace. eslint: <code>brace-style</code> ```javascript// badif (test) { thing1(); thing2();}else { thing3();}// goodif (test) { thing1(); thing2();} else { thing3();}``` - 16.3 If an if block always executes a return statement, the subsequent else block is unnecessary. A return in an else if block following an if block that contains a return can be separated into multiple if blocks. eslint: <code>no-else-return</code> ```javascript// badfunction foo() { if (x) { return x; } else { return y; }}// badfunction cats() { if (x) { return x; } else if (y) { return y; }}// badfunction dogs() { if (x) { return x; } else { if (y) { return y; } }}// goodfunction foo() { if (x) { return x; } return y;}// goodfunction cats() { if (x) { return x; } if (y) { return y; }}// goodfunction dogs(x) { if (x) { if (z) { return y; } } else { return z; }}``` ⬆ back to top Control Statements - 17.1 In case your control statement ( if , while etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line. > Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.```javascript// badif ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1();}// badif (foo === 123 && bar === 'abc') { thing1();}// badif (foo === 123 && bar === 'abc') { thing1();}// badif ( foo === 123 && bar === 'abc') { thing1();}// goodif ( foo === 123 && bar === 'abc') { thing1();}// goodif ( (foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1();}// goodif (foo === 123 && bar === 'abc') { thing1();}``` - 17.2 Don't use selection operators in place of control statements. ```javascript// bad!isRunning && startRunning();// goodif (!isRunning) { startRunning();}``` ⬆ back to top Comments - 18.1 Use /** ... */ for multiline comments. ```javascript// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} elementfunction make(tag) { // ... return element;}// good/** * make() returns a new element * based on the passed-in tag name */function make(tag) { // ... return element;}``` - 18.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block. ```javascript// badconst active = true; // is current tab// good// is current tabconst active = true;// badfunction getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type;}// goodfunction getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type;}// also goodfunction getType() { // set the default type to 'no type' const type = this.type || 'no type'; return type;}``` - 18.3 Start all comments with a space to make it easier to read. eslint: <code>spaced-comment</code> ```javascript// bad//is current tabconst active = true;// good// is current tabconst active = true;// bad/** *make() returns a new element *based on the passed-in tag name */function make(tag) { // ... return element;}// good/** * make() returns a new element * based on the passed-in tag name */function make(tag) { // ... return element;}``` - 18.4 Prefixing your comments with FIXME or TODO helps other developers quickly understand if you’re pointing out a problem that needs to be revisited, or if you’re suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME: -- need to figure this out or TODO: -- need to implement . - 18.5 Use // FIXME: to annotate problems. ```javascriptclass Calculator extends Abacus { constructor() { super(); // FIXME: shouldn’t use a global here total = 0; }}``` - 18.6 Use // TODO: to annotate solutions to problems. ```javascriptclass Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; }}``` ⬆ back to top Whitespace - 19.1 Use soft tabs (space character) set to 2 spaces. eslint: <code>indent</code> ```javascript// badfunction foo() {∙∙∙∙let name;}// badfunction bar() {∙let name;}// goodfunction baz() {∙∙let name;}``` - 19.2 Place 1 space before the leading brace. eslint: <code>space-before-blocks</code> ```javascript// badfunction test(){ console.log('test');}// goodfunction test() { console.log('test');}// baddog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog',});// gooddog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog',});``` - 19.3 Place 1 space before the opening parenthesis in control statements ( if , while etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: <code>keyword-spacing</code> ```javascript// badif(isJedi) { fight ();}// goodif (isJedi) { fight();}// badfunction fight () { console.log ('Swooosh!');}// goodfunction fight() { console.log('Swooosh!');}``` - 19.4 Set off operators with spaces. eslint: <code>space-infix-ops</code> ```javascript// badconst x=y+5;// goodconst x = y + 5;``` - 19.5 End files with a single newline character. eslint: <code>eol-last</code> ```javascript// badimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;``````javascript// badimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;↵↵``````javascript// goodimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;↵``` - 19.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint: <code>newline-per-chained-call</code> <code>no-whitespace-before-property</code> ```javascript// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// bad$('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount();// good$('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount();// badconst leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', `translate(${radius + margin},${radius + margin})`) .call(tron.led);// goodconst leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', `translate(${radius + margin},${radius + margin})`) .call(tron.led);// goodconst leds = stage.selectAll('.led').data(data);const svg = leds.enter().append('svg:svg');svg.classed('led', true).attr('width', (radius + margin) * 2);const g = svg.append('svg:g');g.attr('transform', `translate(${radius + margin},${radius + margin})`).call(tron.led);``` - 19.7 Leave a blank line after blocks and before the next statement. ```javascript// badif (foo) { return bar;}return baz;// goodif (foo) { return bar;}return baz;// badconst obj = { foo() { }, bar() { },};return obj;// goodconst obj = { foo() { }, bar() { },};return obj;// badconst arr = [ function foo() { }, function bar() { },];return arr;// goodconst arr = [ function foo() { }, function bar() { },];return arr;``` - 19.8 Do not pad your blocks with blank lines. eslint: <code>padded-blocks</code> ```javascript// badfunction bar() { console.log(foo);}// badif (baz) { console.log(qux);} else { console.log(foo);}// badclass Foo { constructor(bar) { this.bar = bar; }}// goodfunction bar() { console.log(foo);}// goodif (baz) { console.log(qux);} else { console.log(foo);}``` - 19.9 Do not use multiple blank lines to pad your code. eslint: <code>no-multiple-empty-lines</code> <!-- markdownlint-disable MD012 -->```javascript// badclass Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = this.getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. }}// goodclass Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. }}``` - 19.10 Do not add spaces inside parentheses. eslint: <code>space-in-parens</code> ```javascript// badfunction bar( foo ) { return foo;}// goodfunction bar(foo) { return foo;}// badif ( foo ) { console.log(foo);}// goodif (foo) { console.log(foo);}``` - 19.11 Do not add spaces inside brackets. eslint: <code>array-bracket-spacing</code> ```javascript// badconst foo = [ 1, 2, 3 ];console.log(foo[ 0 ]);// goodconst foo = [1, 2, 3];console.log(foo[0]);``` - 19.12 Add spaces inside curly braces. eslint: <code>object-curly-spacing</code> ```javascript// badconst foo = {clark: 'kent'};// goodconst foo = { clark: 'kent' };``` - 19.13 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above , long strings are exempt from this rule, and should not be broken up. eslint: <code>max-len</code> > Why? This ensures readability and maintainability.```javascript// badconst foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;// bad$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));// goodconst foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;// good$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' },}) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));``` - 19.14 Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint: <code>block-spacing</code> ```javascript// badfunction foo() {return true;}if (foo) { bar = 0;}// goodfunction foo() { return true; }if (foo) { bar = 0; }``` - 19.15 Avoid spaces before commas and require a space after commas. eslint: <code>comma-spacing</code> ```javascript// badvar foo = 1,bar = 2;var arr = [1 , 2];// goodvar foo = 1, bar = 2;var arr = [1, 2];``` - 19.16 Enforce spacing inside of computed property brackets. eslint: <code>computed-property-spacing</code> ```javascript// badobj[foo ]obj[ 'foo']var x = {[ b ]: a}obj[foo[ bar ]]// goodobj[foo]obj['foo']var x = { [b]: a }obj[foo[bar]]``` - 19.17 Avoid spaces between functions and their invocations. eslint: <code>func-call-spacing</code> ```javascript// badfunc ();func();// goodfunc();``` - 19.18 Enforce spacing between keys and values in object literal properties. eslint: <code>key-spacing</code> ```javascript// badvar obj = { foo : 42 };var obj2 = { foo:42 };// goodvar obj = { foo: 42 };``` - 19.19 Avoid trailing spaces at the end of lines. eslint: <code>no-trailing-spaces</code> - 19.20 Avoid multiple empty lines, only allow one newline at the end of files, and avoid a newline at the beginning of files. eslint: <code>no-multiple-empty-lines</code> <!-- markdownlint-disable MD012 -->```javascript// bad - multiple empty linesvar x = 1;var y = 2;// bad - 2+ newlines at end of filevar x = 1;var y = 2;// bad - 1+ newline(s) at beginning of filevar x = 1;var y = 2;// goodvar x = 1;var y = 2;```<!-- markdownlint-enable MD012 --> ⬆ back to top Commas - 20.1 Leading commas: Nope. eslint: <code>comma-style</code> ```javascript// badconst story = [ once , upon , aTime];// goodconst story = [ once, upon, aTime,];// badconst hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers'};// goodconst hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers',};``` - 20.2 Additional trailing comma: Yup. eslint: <code>comma-dangle</code> > Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don’t have to worry about the [trailing comma problem](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) in legacy browsers.```diff// bad - git diff without trailing commaconst hero = { firstName: 'Florence',- lastName: 'Nightingale'+ lastName: 'Nightingale',+ inventorOf: ['coxcomb chart', 'modern nursing']};// good - git diff with trailing commaconst hero = { firstName: 'Florence', lastName: 'Nightingale',+ inventorOf: ['coxcomb chart', 'modern nursing'],};``````javascript// badconst hero = { firstName: 'Dana', lastName: 'Scully'};const heroes = [ 'Batman', 'Superman'];// goodconst hero = { firstName: 'Dana', lastName: 'Scully',};const heroes = [ 'Batman', 'Superman',];// badfunction createHero( firstName, lastName, inventorOf) { // does nothing}// goodfunction createHero( firstName, lastName, inventorOf,) { // does nothing}// good (note that a comma must not appear after a "rest" element)function createHero( firstName, lastName, inventorOf, ...heroArgs) { // does nothing}// badcreateHero( firstName, lastName, inventorOf);// goodcreateHero( firstName, lastName, inventorOf,);// good (note that a comma must not appear after a "rest" element)createHero( firstName, lastName, inventorOf, ...heroArgs);``` ⬆ back to top Semicolons - 21.1 Yup. eslint: <code>semi</code> > Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) to determine whether it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.```javascript// bad - raises exceptionconst luke = {}const leia = {}[luke, leia].forEach((jedi) => jedi.father = 'vader')// bad - raises exceptionconst reaction = "No! That’s impossible!"(async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ...}())// bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!function foo() { return 'search your feelings, you know it to be foo'}// goodconst luke = {};const leia = {};[luke, leia].forEach((jedi) => { jedi.father = 'vader';});// goodconst reaction = "No! That’s impossible!";(async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ...}());// goodfunction foo() { return 'search your feelings, you know it to be foo';}```[Read more](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214). ⬆ back to top Type Casting & Coercion - 22.1 Perform type coercion at the beginning of the statement. - 22.2 Strings: eslint: <code>no-new-wrappers</code> ```javascript// => this.reviewScore = 9;// badconst totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"// badconst totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()// badconst totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string// goodconst totalScore = String(this.reviewScore);``` - 22.3 Numbers: Use Number for type casting and parseInt always with a radix for parsing strings. eslint: <code>radix</code> <code>no-new-wrappers</code> > Why? The `parseInt` function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading whitespace in string is ignored. If radix is `undefined` or `0`, it is assumed to be `10` except when the number begins with the character pairs `0x` or `0X`, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix.```javascriptconst inputValue = '4';// badconst val = new Number(inputValue);// badconst val = +inputValue;// badconst val = inputValue >> 0;// badconst val = parseInt(inputValue);// goodconst val = Number(inputValue);// goodconst val = parseInt(inputValue, 10);``` - 22.4 If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons , leave a comment explaining why and what you’re doing. ```javascript// good/** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */const val = inputValue >> 0;``` - 22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values , but bitshift operations always return a 32-bit integer ( source ). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion . Largest signed 32-bit Int is 2,147,483,647: ```javascript2147483647 >> 0; // => 21474836472147483648 >> 0; // => -21474836482147483649 >> 0; // => -2147483647``` - 22.6 Booleans: eslint: <code>no-new-wrappers</code> ```javascriptconst age = 0;// badconst hasAge = new Boolean(age);// goodconst hasAge = Boolean(age);// bestconst hasAge = !!age;``` ⬆ back to top Naming Conventions - 23.1 Avoid single letter names. Be descriptive with your naming. eslint: <code>id-length</code> ```javascript// badfunction q() { // ...}// goodfunction query() { // ...}``` - 23.2 Use camelCase when naming objects, functions, and instances. eslint: <code>camelcase</code> ```javascript// badconst OBJEcttsssss = {};const this_is_my_object = {};function c() {}// goodconst thisIsMyObject = {};function thisIsMyFunction() {}``` - 23.3 Use PascalCase only when naming constructors or classes. eslint: <code>new-cap</code> ```javascript// badfunction user(options) { this.name = options.name;}const bad = new user({ name: 'nope',});// goodclass User { constructor(options) { this.name = options.name; }}const good = new User({ name: 'yup',});``` - 23.4 Do not use trailing or leading underscores. eslint: <code>no-underscore-dangle</code> > Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.```javascript// badthis.__firstName__ = 'Panda';this.firstName_ = 'Panda';this._firstName = 'Panda';// goodthis.firstName = 'Panda';// good, in environments where WeakMaps are available// see https://kangax.github.io/compat-table/es6/#test-WeakMapconst firstNames = new WeakMap();firstNames.set(this, 'Panda');``` - 23.5 Don’t save references to this . Use arrow functions or Function#bind . ```javascript// badfunction foo() { const self = this; return function () { console.log(self); };}// badfunction foo() { const that = this; return function () { console.log(that); };}// goodfunction foo() { return () => { console.log(this); };}``` - 23.6 A base filename should exactly match the name of its default export. ```javascript// file 1 contentsclass CheckBox { // ...}export default CheckBox;// file 2 contentsexport default function fortyTwo() { return 42; }// file 3 contentsexport default function insideDirectory() {}// in some other file// badimport CheckBox from './checkBox'; // PascalCase import/export, camelCase filenameimport FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase exportimport InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export// badimport CheckBox from './check_box'; // PascalCase import/export, snake_case filenameimport forty_two from './forty_two'; // snake_case import/filename, camelCase exportimport inside_directory from './inside_directory'; // snake_case import, camelCase exportimport index from './inside_directory/index'; // requiring the index file explicitlyimport insideDirectory from './insideDirectory/index'; // requiring the index file explicitly// goodimport CheckBox from './CheckBox'; // PascalCase export/import/filenameimport fortyTwo from './fortyTwo'; // camelCase export/import/filenameimport insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"// ^ supports both insideDirectory.js and insideDirectory/index.js``` - 23.7 Use camelCase when you export-default a function. Your filename should be identical to your function’s name. ```javascriptfunction makeStyleGuide() { // ...}export default makeStyleGuide;``` - 23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object. ```javascriptconst AirbnbStyleGuide = { es6: { },};export default AirbnbStyleGuide;``` - 23.9 Acronyms and initialisms should always be all uppercased, or all lowercased. > Why? Names are for readability, not to appease a computer algorithm.```javascript// badimport SmsContainer from './containers/SmsContainer';// badconst HttpRequests = [ // ...];// goodimport SMSContainer from './containers/SMSContainer';// goodconst HTTPRequests = [ // ...];// also goodconst httpRequests = [ // ...];// bestimport TextMessageContainer from './containers/TextMessageContainer';// bestconst requests = [ // ...];``` - 23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a const (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change. > Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.- What about all `const` variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.- What about exported objects? - Uppercase at the top level of export (e.g. `EXPORTED_OBJECT.key`) and maintain that all nested properties do not change.```javascript// badconst PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';// badexport const THING_TO_BE_CHANGED = 'should obviously not be uppercased';// badexport let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';// ---// allowed but does not supply semantic valueexport const apiKey = 'SOMEKEY';// better in most casesexport const API_KEY = 'SOMEKEY';// ---// bad - unnecessarily uppercases key while adding no semantic valueexport const MAPPING = { KEY: 'value'};// goodexport const MAPPING = { key: 'value'};``` ⬆ back to top Accessors - 24.1 Accessor functions for properties are not required. - 24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello') . ```javascript// badclass Dragon { get age() { // ... } set age(value) { // ... }}// goodclass Dragon { getAge() { // ... } setAge(value) { // ... }}``` - 24.3 If the property/method is a boolean , use isVal() or hasVal() . ```javascript// badif (!dragon.age()) { return false;}// goodif (!dragon.hasAge()) { return false;}``` - 24.4 It’s okay to create get() and set() functions, but be consistent. ```javascriptclass Jedi { constructor(options = {}) { const lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber); } set(key, val) { this[key] = val; } get(key) { return this[key]; }}``` ⬆ back to top Events - 25.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: ```javascript// bad$(this).trigger('listingUpdated', listing.id);// ...$(this).on('listingUpdated', (e, listingID) => { // do something with listingID});```prefer:```javascript// good$(this).trigger('listingUpdated', { listingID: listing.id });// ...$(this).on('listingUpdated', (e, data) => { // do something with data.listingID});``` ⬆ back to top jQuery - 26.1 Prefix jQuery object variables with a $ . ```javascript// badconst sidebar = $('.sidebar');// goodconst $sidebar = $('.sidebar');// goodconst $sidebarBtn = $('.sidebar-btn');``` - 26.2 Cache jQuery lookups. ```javascript// badfunction setSidebar() { $('.sidebar').hide(); // ... $('.sidebar').css({ 'background-color': 'pink', });}// goodfunction setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide(); // ... $sidebar.css({ 'background-color': 'pink', });}``` - 26.3 For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul') . jsPerf - 26.4 Use find with scoped jQuery object queries. ```javascript// bad$('ul', '.sidebar').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good$sidebar.find('ul').hide();``` ⬆ back to top ECMAScript 5 Compatibility - 27.1 Refer to Kangax ’s ES5 compatibility table . ⬆ back to top ECMAScript 6+ (ES 2015+) Styles - 28.1 This is a collection of links to the various ES6+ features. Arrow Functions Classes Object Shorthand Object Concise Object Computed Properties Template Strings Destructuring Default Parameters Rest Array Spreads Let and Const Exponentiation Operator Iterators and Generators Modules 28.2 Do not use TC39 proposals that have not reached stage 3. Why? They are not finalized , and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet. ⬆ back to top Standard Library The Standard Library contains utilities that are functionally broken but remain for legacy reasons. - 29.1 Use Number.isNaN instead of global isNaN . eslint: <code>no-restricted-globals</code> > Why? The global `isNaN` coerces non-numbers to numbers, returning true for anything that coerces to NaN.> If this behavior is desired, make it explicit.```javascript// badisNaN('1.2'); // falseisNaN('1.2.3'); // true// goodNumber.isNaN('1.2.3'); // falseNumber.isNaN(Number('1.2.3')); // true``` - 29.2 Use Number.isFinite instead of global isFinite . eslint: <code>no-restricted-globals</code> > Why? The global `isFinite` coerces non-numbers to numbers, returning true for anything that coerces to a finite number.> If this behavior is desired, make it explicit.```javascript// badisFinite('2e3'); // true// goodNumber.isFinite('2e3'); // falseNumber.isFinite(parseInt('2e3', 10)); // true``` ⬆ back to top Testing - 30.1 Yup. ```javascriptfunction foo() { return true;}``` - 30.2 No, but seriously : - Whichever testing framework you use, you should be writing tests! - Strive to write many small pure functions, and minimize where mutations occur. - Be cautious about stubs and mocks - they can make your tests more brittle. - We primarily use <code>mocha</code> and <code>jest</code> at Airbnb. <code>tape</code> is also used occasionally for small, separate modules. - 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it. - Whenever you fix a bug, write a regression test . A bug fixed without a regression test is almost certainly going to break again in the future. ⬆ back to top Performance On Layout & Web Performance String vs Array Concat Try/Catch Cost In a Loop Bang Function jQuery Find vs Context, Selector innerHTML vs textContent for script text Long String Concatenation Are JavaScript functions like <code>map()</code>, <code>reduce()</code>, and <code>filter()</code> optimized for traversing arrays? Loading... ⬆ back to top Resources Learning ES6+ Latest ECMA spec ExploringJS ES6 Compatibility Table Comprehensive Overview of ES6 Features Read This Standard ECMA-262 Tools Code Style Linters ESlint - Airbnb Style .eslintrc JSHint - Airbnb Style .jshintrc Neutrino Preset - @neutrinojs/airbnb Other Style Guides Google JavaScript Style Guide Google JavaScript Style Guide (Old) jQuery Core Style Guidelines Principles of Writing Consistent, Idiomatic JavaScript StandardJS Other Styles Naming this in nested functions - Christian Johansen Conditional Callbacks - Ross Allen Popular JavaScript Coding Conventions on GitHub - JeongHoon Byun Multiple var statements in JavaScript, not superfluous - Ben Alman Further Reading Understanding JavaScript Closures - Angus Croll Basic JavaScript for the impatient programmer - Dr. Axel Rauschmayer You Might Not Need jQuery - Zack Bloom & Adam Schwartz ES6 Features - Luke Hoban Frontend Guidelines - Benjamin De Cock Books JavaScript: The Good Parts - Douglas Crockford JavaScript Patterns - Stoyan Stefanov Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders Maintainable JavaScript - Nicholas C. Zakas JavaScript Web Applications - Alex MacCaw Pro JavaScript Techniques - John Resig Smashing Node.js: JavaScript Everywhere - Guillermo Rauch Secrets of the JavaScript Ninja - John Resig and Bear Bibeault Human JavaScript - Henrik Joreteg Superhero.js - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy JSBooks - Julien Bouquillon Third Party JavaScript - Ben Vinegar and Anton Kovalyov Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript - David Herman Eloquent JavaScript - Marijn Haverbeke You Don’t Know JS: ES6 & Beyond - Kyle Simpson Blogs JavaScript Weekly JavaScript, JavaScript... Bocoup Weblog Adequately Good NCZOnline Perfection Kills Ben Alman Dmitry Baranovskiy nettuts Podcasts JavaScript Air JavaScript Jabber ⬆ back to top In the Wild This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list. 123erfasst : 123erfasst/javascript 4Catalyzer : 4Catalyzer/javascript Aan Zee : AanZee/javascript Airbnb : airbnb/javascript AloPeyk : AloPeyk AltSchool : AltSchool/javascript Apartmint : apartmint/javascript Ascribe : ascribe/javascript Avant : avantcredit/javascript Axept : axept/javascript Billabong : billabong/javascript Bisk : bisk Bonhomme : bonhommeparis/javascript Brainshark : brainshark/javascript CaseNine : CaseNine/javascript Cerner : Cerner Chartboost : ChartBoost/javascript-style-guide Coeur d'Alene Tribe : www.cdatribe-nsn.gov ComparaOnline : comparaonline/javascript Compass Learning : compasslearning/javascript-style-guide DailyMotion : dailymotion/javascript DoSomething : DoSomething/eslint-config Digitpaint digitpaint/javascript Drupal : www.drupal.org Ecosia : ecosia/javascript Evernote : evernote/javascript-style-guide Evolution Gaming : evolution-gaming/javascript EvozonJs : evozonjs/javascript ExactTarget : ExactTarget/javascript Flexberry : Flexberry/javascript-style-guide Gawker Media : gawkermedia General Electric : GeneralElectric/javascript Generation Tux : GenerationTux/javascript GoodData : gooddata/gdc-js-style GreenChef : greenchef/javascript Grooveshark : grooveshark/javascript Grupo-Abraxas : Grupo-Abraxas/javascript Happeo : happeo/javascript Honey : honeyscience/javascript How About We : howaboutwe/javascript HubSpot : HubSpot/javascript Hyper : hyperoslo/javascript-playbook InterCity Group : intercitygroup/javascript-style-guide Jam3 : Jam3/Javascript-Code-Conventions JSSolutions : JSSolutions/javascript Kaplan Komputing : kaplankomputing/javascript KickorStick : kickorstick Kinetica Solutions : kinetica/javascript LEINWAND : LEINWAND/javascript Lonely Planet : lonelyplanet/javascript M2GEN : M2GEN/javascript Mighty Spring : mightyspring/javascript MinnPost : MinnPost/javascript MitocGroup : MitocGroup/javascript Muber : muber National Geographic : natgeo NullDev : NullDevCo/JavaScript-Styleguide Nulogy : nulogy/javascript Orange Hill Development : orangehill/javascript Orion Health : orionhealth/javascript OutBoxSoft : OutBoxSoft/javascript Peerby : Peerby/javascript Pier 1 : Pier1/javascript Qotto : Qotto/javascript-style-guide React : facebook.github.io/react/contributing/how-to-contribute.html#style-guide REI : reidev/js-style-guide Ripple : ripple/javascript-style-guide Sainsbury’s Supermarkets : jsainsburyplc Shutterfly : shutterfly/javascript Sourcetoad : sourcetoad/javascript Springload : springload StratoDem Analytics : stratodem/javascript SteelKiwi Development : steelkiwi/javascript StudentSphere : studentsphere/javascript SwoopApp : swoopapp/javascript SysGarage : sysgarage/javascript-style-guide Syzygy Warsaw : syzygypl/javascript Target : target/javascript Terra : terra TheLadders : TheLadders/javascript The Nerdery : thenerdery/javascript-standards Tomify : tomprats Traitify : traitify/eslint-config-traitify T4R Technology : T4R-Technology/javascript UrbanSim : urbansim VoxFeed : VoxFeed/javascript-style-guide WeBox Studio : weboxstudio/javascript Weggo : Weggo/javascript Zillow : zillow/javascript ZocDoc : ZocDoc/javascript ⬆ back to top Translation This style guide is also available in other languages: Brazilian Portuguese : armoucar/javascript-style-guide Bulgarian : borislavvv/javascript Catalan : fpmweb/javascript-style-guide Chinese (Simplified) : lin-123/javascript Chinese (Traditional) : jigsawye/javascript French : nmussy/javascript-style-guide German : timofurrer/javascript-style-guide Italian : sinkswim/javascript-style-guide Japanese : mitsuruog/javascript-style-guide Korean : ParkSB/javascript-style-guide Russian : leonidlebedev/javascript-airbnb Spanish : paolocarrasco/javascript-style-guide Thai : lvarayut/javascript-style-guide Turkish : eraycetinay/javascript Ukrainian : ivanzusko/javascript Vietnam : dangkyokhoang/javascript-style-guide The JavaScript Style Guide Guide Reference Chat With Us About JavaScript Find us on gitter . Contributors View Contributors License (The MIT License) Copyright (c) 2012 Airbnb Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the'Software'), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions: The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ⬆ back to top Amendments We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts. }; To restore the repository download the bundle wget https://archive.org/download/github.com-airbnb-javascript_-_2022-05-26_04-23-02/airbnb-javascript_-_2022-05-26_04-23-02.bundle and run: git clone airbnb-javascript_-_2022-05-26_04-23-02.bundle Source: https://github.com/airbnb/javascript Uploader: airbnb Upload date: 2022-05-26

“Github.com-airbnb-javascript_-_2022-05-26_04-23-02” Metadata:

  • Title: ➤  Github.com-airbnb-javascript_-_2022-05-26_04-23-02
  • Author:

“Github.com-airbnb-javascript_-_2022-05-26_04-23-02” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 4.06 Mbs, the file-s for this book were downloaded 52 times, the file-s went public at Thu May 26 2022.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-airbnb-javascript_-_2022-05-26_04-23-02 at online marketplaces:


28Microsoft Programming In HTML5 With JavaScript And CSS3

Microsoft Programming in HTML5 with JavaScript and CSS3

“Microsoft Programming In HTML5 With JavaScript And CSS3” Metadata:

  • Title: ➤  Microsoft Programming In HTML5 With JavaScript And CSS3

Edition Identifiers:

Downloads Information:

The book is available for download in "image" format, the size of the file-s is: 0.19 Mbs, the file-s for this book were downloaded 94 times, the file-s went public at Mon Aug 07 2017.

Available formats:
Archive BitTorrent - Item Tile - JPEG Thumb - Metadata - PNG -

Related Links:

Online Marketplaces

Find Microsoft Programming In HTML5 With JavaScript And CSS3 at online marketplaces:


29Introduction To Programming With Javascript: Arrays Exercises (Part 2)

By

Part 1 is here. In this video, I go through the remaining arrays exercises in Launch School's Introduction to Programming JavaScript book. These exercises are meant to be repeated often in order to solidify one's understanding of JavaScript fundamentals.

“Introduction To Programming With Javascript: Arrays Exercises (Part 2)” Metadata:

  • Title: ➤  Introduction To Programming With Javascript: Arrays Exercises (Part 2)
  • Author:
  • Language: English

“Introduction To Programming With Javascript: Arrays Exercises (Part 2)” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 245.05 Mbs, the file-s for this book were downloaded 78 times, the file-s went public at Thu Jul 29 2021.

Available formats:
Archive BitTorrent - Item Tile - MPEG4 - Metadata - Thumbnail - h.264 IA -

Related Links:

Online Marketplaces

Find Introduction To Programming With Javascript: Arrays Exercises (Part 2) at online marketplaces:


30J Query A Biblioteca Do Programador Javascript

J Query A Biblioteca Do Programador Javascript

“J Query A Biblioteca Do Programador Javascript” Metadata:

  • Title: ➤  J Query A Biblioteca Do Programador Javascript

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 136.71 Mbs, the file-s for this book were downloaded 218 times, the file-s went public at Wed Mar 01 2023.

Available formats:
Additional Text PDF - Archive BitTorrent - DjVuTXT - Djvu XML - Image Container PDF - Item Tile - Metadata - OCR Page Index - OCR Search Text - Page Numbers JSON - Scandata - Single Page Processed JP2 ZIP - chOCR - hOCR -

Related Links:

Online Marketplaces

Find J Query A Biblioteca Do Programador Javascript at online marketplaces:


31Github.com-airbnb-javascript_-_2023-05-15_21-29-30

By

JavaScript Style Guide Airbnb JavaScript Style Guide() { A mostly reasonable approach to JavaScript Note : this guide assumes you are using Babel , and requires that you use babel-preset-airbnb or the equivalent. It also assumes you are installing shims/polyfills in your app, with airbnb-browser-shims or the equivalent. This guide is available in other languages too. See Translation Other Style Guides ES5 (Deprecated) React CSS-in-JavaScript CSS & Sass Ruby Table of Contents Types References Objects Arrays Destructuring Strings Functions Arrow Functions Classes & Constructors Modules Iterators and Generators Properties Variables Hoisting Comparison Operators & Equality Blocks Control Statements Comments Whitespace Commas Semicolons Type Casting & Coercion Naming Conventions Accessors Events jQuery ECMAScript 5 Compatibility ECMAScript 6+ (ES 2015+) Styles Standard Library Testing Performance Resources In the Wild Translation The JavaScript Style Guide Guide Chat With Us About JavaScript Contributors License Amendments Types - 1.1 Primitives : When you access a primitive type you work directly on its value. - `string`- `number`- `boolean`- `null`- `undefined`- `symbol`- `bigint`<br />```javascriptconst foo = 1;let bar = foo;bar = 9;console.log(foo, bar); // => 1, 9```- Symbols and BigInts cannot be faithfully polyfilled, so they should not be used when targeting browsers/environments that don’t support them natively. - 1.2 Complex : When you access a complex type you work on a reference to its value. - `object`- `array`- `function`<br />```javascriptconst foo = [1, 2];const bar = foo;bar[0] = 9;console.log(foo[0], bar[0]); // => 9, 9``` ⬆ back to top References - 2.1 Use const for all of your references; avoid using var . eslint: <code>prefer-const</code> , <code>no-const-assign</code> > Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.```javascript// badvar a = 1;var b = 2;// goodconst a = 1;const b = 2;``` - 2.2 If you must reassign references, use let instead of var . eslint: <code>no-var</code> > Why? `let` is block-scoped rather than function-scoped like `var`.```javascript// badvar count = 1;if (true) { count += 1;}// good, use the let.let count = 1;if (true) { count += 1;}``` - 2.3 Note that both let and const are block-scoped, whereas var is function-scoped. ```javascript// const and let only exist in the blocks they are defined in.{ let a = 1; const b = 1; var c = 1;}console.log(a); // ReferenceErrorconsole.log(b); // ReferenceErrorconsole.log(c); // Prints 1```In the above code, you can see that referencing `a` and `b` will produce a ReferenceError, while `c` contains the number. This is because `a` and `b` are block scoped, while `c` is scoped to the containing function. ⬆ back to top Objects - 3.1 Use the literal syntax for object creation. eslint: <code>no-new-object</code> ```javascript// badconst item = new Object();// goodconst item = {};``` - 3.2 Use computed property names when creating objects with dynamic property names. > Why? They allow you to define all the properties of an object in one place.```javascriptfunction getKey(k) { return `a key named ${k}`;}// badconst obj = { id: 5, name: 'San Francisco',};obj[getKey('enabled')] = true;// goodconst obj = { id: 5, name: 'San Francisco', [getKey('enabled')]: true,};``` - 3.3 Use object method shorthand. eslint: <code>object-shorthand</code> ```javascript// badconst atom = { value: 1, addValue: function (value) { return atom.value + value; },};// goodconst atom = { value: 1, addValue(value) { return atom.value + value; },};``` - 3.4 Use property value shorthand. eslint: <code>object-shorthand</code> > Why? It is shorter and descriptive.```javascriptconst lukeSkywalker = 'Luke Skywalker';// badconst obj = { lukeSkywalker: lukeSkywalker,};// goodconst obj = { lukeSkywalker,};``` - 3.5 Group your shorthand properties at the beginning of your object declaration. > Why? It’s easier to tell which properties are using the shorthand.```javascriptconst anakinSkywalker = 'Anakin Skywalker';const lukeSkywalker = 'Luke Skywalker';// badconst obj = { episodeOne: 1, twoJediWalkIntoACantina: 2, lukeSkywalker, episodeThree: 3, mayTheFourth: 4, anakinSkywalker,};// goodconst obj = { lukeSkywalker, anakinSkywalker, episodeOne: 1, twoJediWalkIntoACantina: 2, episodeThree: 3, mayTheFourth: 4,};``` - 3.6 Only quote properties that are invalid identifiers. eslint: <code>quote-props</code> > Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.```javascript// badconst bad = { 'foo': 3, 'bar': 4, 'data-blah': 5,};// goodconst good = { foo: 3, bar: 4, 'data-blah': 5,};``` - 3.7 Do not call Object.prototype methods directly, such as hasOwnProperty , propertyIsEnumerable , and isPrototypeOf . eslint: <code>no-prototype-builtins</code> > Why? These methods may be shadowed by properties on the object in question - consider `{ hasOwnProperty: false }` - or, the object may be a null object (`Object.create(null)`).```javascript// badconsole.log(object.hasOwnProperty(key));// goodconsole.log(Object.prototype.hasOwnProperty.call(object, key));// bestconst has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.console.log(has.call(object, key));/* or */import has from 'has'; // https://www.npmjs.com/package/hasconsole.log(has(object, key));/* or */console.log(Object.hasOwn(object, key)); // https://www.npmjs.com/package/object.hasown``` - 3.8 Prefer the object spread syntax over <code>Object.assign</code> to shallow-copy objects. Use the object rest parameter syntax to get a new object with certain properties omitted. eslint: <code>prefer-object-spread</code> ```javascript// very badconst original = { a: 1, b: 2 };const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠdelete copy.a; // so does this// badconst original = { a: 1, b: 2 };const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }// goodconst original = { a: 1, b: 2 };const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }const { a, ...noA } = copy; // noA => { b: 2, c: 3 }``` ⬆ back to top Arrays - 4.1 Use the literal syntax for array creation. eslint: <code>no-array-constructor</code> ```javascript// badconst items = new Array();// goodconst items = [];``` - 4.2 Use Array#push instead of direct assignment to add items to an array. ```javascriptconst someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');``` - 4.3 Use array spreads ... to copy arrays. ```javascript// badconst len = items.length;const itemsCopy = [];let i;for (i = 0; i < len; i += 1) { itemsCopy[i] = items[i];}// goodconst itemsCopy = [...items];``` - 4.4 To convert an iterable object to an array, use spreads ... instead of <code>Array.from</code> ```javascriptconst foo = document.querySelectorAll('.foo');// goodconst nodes = Array.from(foo);// bestconst nodes = [...foo];``` - 4.5 Use <code>Array.from</code> for converting an array-like object to an array. ```javascriptconst arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };// badconst arr = Array.prototype.slice.call(arrLike);// goodconst arr = Array.from(arrLike);``` - 4.6 Use <code>Array.from</code> instead of spread ... for mapping over iterables, because it avoids creating an intermediate array. ```javascript// badconst baz = [...foo].map(bar);// goodconst baz = Array.from(foo, bar);``` - 4.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2 . eslint: <code>array-callback-return</code> ```javascript// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => x + 1);// bad - no returned value means `acc` becomes undefined after the first iteration[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item);});// good[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { const flatten = acc.concat(item); return flatten;});// badinbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } else { return false; }});// goodinbox.filter((msg) => { const { subject, author } = msg; if (subject === 'Mockingbird') { return author === 'Harper Lee'; } return false;});``` - 4.8 Use line breaks after opening array brackets and before closing array brackets, if an array has multiple lines ```javascript// badconst arr = [ [0, 1], [2, 3], [4, 5],];const objectInArray = [{ id: 1,}, { id: 2,}];const numberInArray = [ 1, 2,];// goodconst arr = [[0, 1], [2, 3], [4, 5]];const objectInArray = [ { id: 1, }, { id: 2, },];const numberInArray = [ 1, 2,];``` ⬆ back to top Destructuring - 5.1 Use object destructuring when accessing and using multiple properties of an object. eslint: <code>prefer-destructuring</code> > Why? Destructuring saves you from creating temporary references for those properties, and from repetitive access of the object. Repeating object access creates more repetitive code, requires more reading, and creates more opportunities for mistakes. Destructuring objects also provides a single site of definition of the object structure that is used in the block, rather than requiring reading the entire block to determine what is used.```javascript// badfunction getFullName(user) { const firstName = user.firstName; const lastName = user.lastName; return `${firstName} ${lastName}`;}// goodfunction getFullName(user) { const { firstName, lastName } = user; return `${firstName} ${lastName}`;}// bestfunction getFullName({ firstName, lastName }) { return `${firstName} ${lastName}`;}``` - 5.2 Use array destructuring. eslint: <code>prefer-destructuring</code> ```javascriptconst arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;``` - 5.3 Use object destructuring for multiple return values, not array destructuring. > Why? You can add new properties over time or change the order of things without breaking call sites.```javascript// badfunction processInput(input) { // then a miracle occurs return [left, right, top, bottom];}// the caller needs to think about the order of return dataconst [left, __, top] = processInput(input);// goodfunction processInput(input) { // then a miracle occurs return { left, right, top, bottom };}// the caller selects only the data they needconst { left, top } = processInput(input);``` ⬆ back to top Strings - 6.1 Use single quotes '' for strings. eslint: <code>quotes</code> ```javascript// badconst name = "Capt. Janeway";// bad - template literals should contain interpolation or newlinesconst name = `Capt. Janeway`;// goodconst name = 'Capt. Janeway';``` - 6.2 Strings that cause the line to go over 100 characters should not be written across multiple lines using string concatenation. > Why? Broken strings are painful to work with and make code less searchable.```javascript// badconst errorMessage = 'This is a super long error that was thrown because \of Batman. When you stop to think about how Batman had anything to do \with this, you would get nowhere \fast.';// badconst errorMessage = 'This is a super long error that was thrown because ' + 'of Batman. When you stop to think about how Batman had anything to do ' + 'with this, you would get nowhere fast.';// goodconst errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';``` - 6.3 When programmatically building up strings, use template strings instead of concatenation. eslint: <code>prefer-template</code> <code>template-curly-spacing</code> > Why? Template strings give you a readable, concise syntax with proper newlines and string interpolation features.```javascript// badfunction sayHi(name) { return 'How are you, ' + name + '?';}// badfunction sayHi(name) { return ['How are you, ', name, '?'].join();}// badfunction sayHi(name) { return `How are you, ${ name }?`;}// goodfunction sayHi(name) { return `How are you, ${name}?`;}``` - 6.4 Never use eval() on a string, it opens too many vulnerabilities. eslint: <code>no-eval</code> - 6.5 Do not unnecessarily escape characters in strings. eslint: <code>no-useless-escape</code> > Why? Backslashes harm readability, thus they should only be present when necessary.```javascript// badconst foo = '\'this\' \i\s \"quoted\"';// goodconst foo = '\'this\' is "quoted"';const foo = `my name is '${name}'`;``` ⬆ back to top Functions - 7.1 Use named function expressions instead of function declarations. eslint: <code>func-style</code> > Why? Function declarations are hoisted, which means that it’s easy - too easy - to reference the function before it is defined in the file. This harms readability and maintainability. If you find that a function’s definition is large or complex enough that it is interfering with understanding the rest of the file, then perhaps it’s time to extract it to its own module! Don’t forget to explicitly name the expression, regardless of whether or not the name is inferred from the containing variable (which is often the case in modern browsers or when using compilers such as Babel). This eliminates any assumptions made about the Error’s call stack. ([Discussion](https://github.com/airbnb/javascript/issues/794))```javascript// badfunction foo() { // ...}// badconst foo = function () { // ...};// good// lexical name distinguished from the variable-referenced invocation(s)const short = function longUniqueMoreDescriptiveLexicalFoo() { // ...};``` - 7.2 Wrap immediately invoked function expressions in parentheses. eslint: <code>wrap-iife</code> > Why? An immediately invoked function expression is a single unit - wrapping both it, and its invocation parens, in parens, cleanly expresses this. Note that in a world with modules everywhere, you almost never need an IIFE.```javascript// immediately-invoked function expression (IIFE)(function () { console.log('Welcome to the Internet. Please follow me.');}());``` - 7.3 Never declare a function in a non-function block ( if , while , etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently, which is bad news bears. eslint: <code>no-loop-func</code> - 7.4 Note: ECMA-262 defines a block as a list of statements. A function declaration is not a statement. ```javascript// badif (currentUser) { function test() { console.log('Nope.'); }}// goodlet test;if (currentUser) { test = () => { console.log('Yup.'); };}``` - 7.5 Never name a parameter arguments . This will take precedence over the arguments object that is given to every function scope. ```javascript// badfunction foo(name, options, arguments) { // ...}// goodfunction foo(name, options, args) { // ...}``` - 7.6 Never use arguments , opt to use rest syntax ... instead. eslint: <code>prefer-rest-params</code> > Why? `...` is explicit about which arguments you want pulled. Plus, rest arguments are a real Array, and not merely Array-like like `arguments`.```javascript// badfunction concatenateAll() { const args = Array.prototype.slice.call(arguments); return args.join('');}// goodfunction concatenateAll(...args) { return args.join('');}``` - 7.7 Use default parameter syntax rather than mutating function arguments. ```javascript// really badfunction handleThings(opts) { // No! We shouldn’t mutate function arguments. // Double bad: if opts is falsy it'll be set to an object which may // be what you want but it can introduce subtle bugs. opts = opts || {}; // ...}// still badfunction handleThings(opts) { if (opts === void 0) { opts = {}; } // ...}// goodfunction handleThings(opts = {}) { // ...}``` - 7.8 Avoid side effects with default parameters. > Why? They are confusing to reason about.```javascriptlet b = 1;// badfunction count(a = b++) { console.log(a);}count(); // 1count(); // 2count(3); // 3count(); // 3``` - 7.9 Always put default parameters last. eslint: <code>default-param-last</code> ```javascript// badfunction handleThings(opts = {}, name) { // ...}// goodfunction handleThings(name, opts = {}) { // ...}``` - 7.10 Never use the Function constructor to create a new function. eslint: <code>no-new-func</code> > Why? Creating a function in this way evaluates a string similarly to `eval()`, which opens vulnerabilities.```javascript// badconst add = new Function('a', 'b', 'return a + b');// still badconst subtract = Function('a', 'b', 'return a - b');``` - 7.11 Spacing in a function signature. eslint: <code>space-before-function-paren</code> <code>space-before-blocks</code> > Why? Consistency is good, and you shouldn’t have to add or remove a space when adding or removing a name.```javascript// badconst f = function(){};const g = function (){};const h = function() {};// goodconst x = function () {};const y = function a() {};``` - 7.12 Never mutate parameters. eslint: <code>no-param-reassign</code> > Why? Manipulating objects passed in as parameters can cause unwanted variable side effects in the original caller.```javascript// badfunction f1(obj) { obj.key = 1;}// goodfunction f2(obj) { const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1;}``` - 7.13 Never reassign parameters. eslint: <code>no-param-reassign</code> > Why? Reassigning parameters can lead to unexpected behavior, especially when accessing the `arguments` object. It can also cause optimization issues, especially in V8.```javascript// badfunction f1(a) { a = 1; // ...}function f2(a) { if (!a) { a = 1; } // ...}// goodfunction f3(a) { const b = a || 1; // ...}function f4(a = 1) { // ...}``` - 7.14 Prefer the use of the spread syntax ... to call variadic functions. eslint: <code>prefer-spread</code> > Why? It’s cleaner, you don’t need to supply a context, and you can not easily compose `new` with `apply`.```javascript// badconst x = [1, 2, 3, 4, 5];console.log.apply(console, x);// goodconst x = [1, 2, 3, 4, 5];console.log(...x);// badnew (Function.prototype.bind.apply(Date, [null, 2016, 8, 5]));// goodnew Date(...[2016, 8, 5]);``` - 7.15 Functions with multiline signatures, or invocations, should be indented just like every other multiline list in this guide: with each item on a line by itself, with a trailing comma on the last item. eslint: <code>function-paren-newline</code> ```javascript// badfunction foo(bar, baz, quux) { // ...}// goodfunction foo( bar, baz, quux,) { // ...}// badconsole.log(foo, bar, baz);// goodconsole.log( foo, bar, baz,);``` ⬆ back to top Arrow Functions - 8.1 When you must use an anonymous function (as when passing an inline callback), use arrow function notation. eslint: <code>prefer-arrow-callback</code> , <code>arrow-spacing</code> > Why? It creates a version of the function that executes in the context of `this`, which is usually what you want, and is a more concise syntax.> Why not? If you have a fairly complicated function, you might move that logic out into its own named function expression.```javascript// bad[1, 2, 3].map(function (x) { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});``` - 8.2 If the function body consists of a single statement returning an expression without side effects, omit the braces and use the implicit return. Otherwise, keep the braces and use a return statement. eslint: <code>arrow-parens</code> , <code>arrow-body-style</code> > Why? Syntactic sugar. It reads well when multiple functions are chained together.```javascript// bad[1, 2, 3].map((number) => { const nextNumber = number + 1; `A string containing the ${nextNumber}.`;});// good[1, 2, 3].map((number) => `A string containing the ${number + 1}.`);// good[1, 2, 3].map((number) => { const nextNumber = number + 1; return `A string containing the ${nextNumber}.`;});// good[1, 2, 3].map((number, index) => ({ [index]: number,}));// No implicit return with side effectsfunction foo(callback) { const val = callback(); if (val === true) { // Do something if callback returns true }}let bool = false;// badfoo(() => bool = true);// goodfoo(() => { bool = true;});``` - 8.3 In case the expression spans over multiple lines, wrap it in parentheses for better readability. > Why? It shows clearly where the function starts and ends.```javascript// bad['get', 'post', 'put'].map((httpMethod) => Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, ));// good['get', 'post', 'put'].map((httpMethod) => ( Object.prototype.hasOwnProperty.call( httpMagicObjectWithAVeryLongName, httpMethod, )));``` - 8.4 Always include parentheses around arguments for clarity and consistency. eslint: <code>arrow-parens</code> > Why? Minimizes diff churn when adding or removing arguments.```javascript// bad[1, 2, 3].map(x => x * x);// good[1, 2, 3].map((x) => x * x);// bad[1, 2, 3].map(number => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// good[1, 2, 3].map((number) => ( `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => { const y = x + 1; return x * y;});// good[1, 2, 3].map((x) => { const y = x + 1; return x * y;});``` - 8.5 Avoid confusing arrow function syntax ( => ) with comparison operators ( <= , >= ). eslint: <code>no-confusing-arrow</code> ```javascript// badconst itemHeight = (item) => item.height <= 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height >= 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = (item) => (item.height <= 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => { const { height, largeSize, smallSize } = item; return height <= 256 ? largeSize : smallSize;};``` - 8.6 Enforce the location of arrow function bodies with implicit returns. eslint: <code>implicit-arrow-linebreak</code> ```javascript// bad(foo) => bar;(foo) => (bar);// good(foo) => bar;(foo) => (bar);(foo) => ( bar)``` ⬆ back to top Classes & Constructors - 9.1 Always use class . Avoid manipulating prototype directly. > Why? `class` syntax is more concise and easier to reason about.```javascript// badfunction Queue(contents = []) { this.queue = [...contents];}Queue.prototype.pop = function () { const value = this.queue[0]; this.queue.splice(0, 1); return value;};// goodclass Queue { constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; }}``` - 9.2 Use extends for inheritance. > Why? It is a built-in way to inherit prototype functionality without breaking `instanceof`.```javascript// badconst inherits = require('inherits');function PeekableQueue(contents) { Queue.apply(this, contents);}inherits(PeekableQueue, Queue);PeekableQueue.prototype.peek = function () { return this.queue[0];};// goodclass PeekableQueue extends Queue { peek() { return this.queue[0]; }}``` - 9.3 Methods can return this to help with method chaining. ```javascript// badJedi.prototype.jump = function () { this.jumping = true; return true;};Jedi.prototype.setHeight = function (height) { this.height = height;};const luke = new Jedi();luke.jump(); // => trueluke.setHeight(20); // => undefined// goodclass Jedi { jump() { this.jumping = true; return this; } setHeight(height) { this.height = height; return this; }}const luke = new Jedi();luke.jump() .setHeight(20);``` - 9.4 It’s okay to write a custom toString() method, just make sure it works successfully and causes no side effects. ```javascriptclass Jedi { constructor(options = {}) { this.name = options.name || 'no name'; } getName() { return this.name; } toString() { return `Jedi - ${this.getName()}`; }}``` - 9.5 Classes have a default constructor if one is not specified. An empty constructor function or one that just delegates to a parent class is unnecessary. eslint: <code>no-useless-constructor</code> ```javascript// badclass Jedi { constructor() {} getName() { return this.name; }}// badclass Rey extends Jedi { constructor(...args) { super(...args); }}// goodclass Rey extends Jedi { constructor(...args) { super(...args); this.name = 'Rey'; }}``` - 9.6 Avoid duplicate class members. eslint: <code>no-dupe-class-members</code> > Why? Duplicate class member declarations will silently prefer the last one - having duplicates is almost certainly a bug.```javascript// badclass Foo { bar() { return 1; } bar() { return 2; }}// goodclass Foo { bar() { return 1; }}// goodclass Foo { bar() { return 2; }}``` - 9.7 Class methods should use this or be made into a static method unless an external library or framework requires using specific non-static methods. Being an instance method should indicate that it behaves differently based on properties of the receiver. eslint: <code>class-methods-use-this</code> ```javascript// badclass Foo { bar() { console.log('bar'); }}// good - this is usedclass Foo { bar() { console.log(this.bar); }}// good - constructor is exemptclass Foo { constructor() { // ... }}// good - static methods aren't expected to use thisclass Foo { static bar() { console.log('bar'); }}``` ⬆ back to top Modules - 10.1 Always use modules ( import / export ) over a non-standard module system. You can always transpile to your preferred module system. > Why? Modules are the future, let’s start using the future now.```javascript// badconst AirbnbStyleGuide = require('./AirbnbStyleGuide');module.exports = AirbnbStyleGuide.es6;// okimport AirbnbStyleGuide from './AirbnbStyleGuide';export default AirbnbStyleGuide.es6;// bestimport { es6 } from './AirbnbStyleGuide';export default es6;``` - 10.2 Do not use wildcard imports. > Why? This makes sure you have a single default export.```javascript// badimport * as AirbnbStyleGuide from './AirbnbStyleGuide';// goodimport AirbnbStyleGuide from './AirbnbStyleGuide';``` - 10.3 And do not export directly from an import. > Why? Although the one-liner is concise, having one clear way to import and one clear way to export makes things consistent.```javascript// bad// filename es6.jsexport { es6 as default } from './AirbnbStyleGuide';// good// filename es6.jsimport { es6 } from './AirbnbStyleGuide';export default es6;``` - 10.4 Only import from a path in one place. eslint: <code>no-duplicate-imports</code> Why? Having multiple lines that import from the same path can make code harder to maintain. ```javascript// badimport foo from 'foo';// … some other imports … //import { named1, named2 } from 'foo';// goodimport foo, { named1, named2 } from 'foo';// goodimport foo, { named1, named2,} from 'foo';``` - 10.5 Do not export mutable bindings. eslint: <code>import/no-mutable-exports</code> Why? Mutation should be avoided in general, but in particular when exporting mutable bindings. While this technique may be needed for some special cases, in general, only constant references should be exported. ```javascript// badlet foo = 3;export { foo };// goodconst foo = 3;export { foo };``` - 10.6 In modules with a single export, prefer default export over named export. eslint: <code>import/prefer-default-export</code> Why? To encourage more files that only ever export one thing, which is better for readability and maintainability. ```javascript// badexport function foo() {}// goodexport default function foo() {}``` - 10.7 Put all import s above non-import statements. eslint: <code>import/first</code> Why? Since import s are hoisted, keeping them all at the top prevents surprising behavior. ```javascript// badimport foo from 'foo';foo.init();import bar from 'bar';// goodimport foo from 'foo';import bar from 'bar';foo.init();``` - 10.8 Multiline imports should be indented just like multiline array and object literals. eslint: <code>object-curly-newline</code> > Why? The curly braces follow the same indentation rules as every other curly brace block in the style guide, as do the trailing commas.```javascript// badimport {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path';// goodimport { longNameA, longNameB, longNameC, longNameD, longNameE,} from 'path';``` - 10.9 Disallow Webpack loader syntax in module import statements. eslint: <code>import/no-webpack-loader-syntax</code> Why? Since using Webpack syntax in the imports couples the code to a module bundler. Prefer using the loader syntax in webpack.config.js . ```javascript// badimport fooSass from 'css!sass!foo.scss';import barCss from 'style!css!bar.css';// goodimport fooSass from 'foo.scss';import barCss from 'bar.css';``` - 10.10 Do not include JavaScript filename extensions eslint: <code>import/extensions</code> Why? Including extensions inhibits refactoring, and inappropriately hardcodes implementation details of the module you're importing in every consumer. ```javascript// badimport foo from './foo.js';import bar from './bar.jsx';import baz from './baz/index.jsx';// goodimport foo from './foo';import bar from './bar';import baz from './baz';``` ⬆ back to top Iterators and Generators - 11.1 Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of . eslint: <code>no-iterator</code> <code>no-restricted-syntax</code> > Why? This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.> Use `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... to iterate over arrays, and `Object.keys()` / `Object.values()` / `Object.entries()` to produce arrays so you can iterate over objects.```javascriptconst numbers = [1, 2, 3, 4, 5];// badlet sum = 0;for (let num of numbers) { sum += num;}sum === 15;// goodlet sum = 0;numbers.forEach((num) => { sum += num;});sum === 15;// best (use the functional force)const sum = numbers.reduce((total, num) => total + num, 0);sum === 15;// badconst increasedByOne = [];for (let i = 0; i < numbers.length; i++) { increasedByOne.push(numbers[i] + 1);}// goodconst increasedByOne = [];numbers.forEach((num) => { increasedByOne.push(num + 1);});// best (keeping it functional)const increasedByOne = numbers.map((num) => num + 1);``` - 11.2 Don’t use generators for now. > Why? They don’t transpile well to ES5. - 11.3 If you must use generators, or if you disregard our advice , make sure their function signature is spaced properly. eslint: <code>generator-star-spacing</code> > Why? `function` and `*` are part of the same conceptual keyword - `*` is not a modifier for `function`, `function*` is a unique construct, different from `function`.```javascript// badfunction * foo() { // ...}// badconst bar = function * () { // ...};// badconst baz = function *() { // ...};// badconst quux = function*() { // ...};// badfunction*foo() { // ...}// badfunction *foo() { // ...}// very badfunction*foo() { // ...}// very badconst wat = function*() { // ...};// goodfunction* foo() { // ...}// goodconst foo = function* () { // ...};``` ⬆ back to top Properties - 12.1 Use dot notation when accessing properties. eslint: <code>dot-notation</code> ```javascriptconst luke = { jedi: true, age: 28,};// badconst isJedi = luke['jedi'];// goodconst isJedi = luke.jedi;``` - 12.2 Use bracket notation [] when accessing properties with a variable. ```javascriptconst luke = { jedi: true, age: 28,};function getProp(prop) { return luke[prop];}const isJedi = getProp('jedi');``` - 12.3 Use exponentiation operator ** when calculating exponentiations. eslint: <code>prefer-exponentiation-operator</code> . ```javascript// badconst binary = Math.pow(2, 10);// goodconst binary = 2 ** 10;``` ⬆ back to top Variables - 13.1 Always use const or let to declare variables. Not doing so will result in global variables. We want to avoid polluting the global namespace. Captain Planet warned us of that. eslint: <code>no-undef</code> <code>prefer-const</code> ```javascript// badsuperPower = new SuperPower();// goodconst superPower = new SuperPower();``` - 13.2 Use one const or let declaration per variable or assignment. eslint: <code>one-var</code> > Why? It’s easier to add new variable declarations this way, and you never have to worry about swapping out a `;` for a `,` or introducing punctuation-only diffs. You can also step through each declaration with the debugger, instead of jumping through all of them at once.```javascript// badconst items = getItems(), goSportsTeam = true, dragonball = 'z';// bad// (compare to above, and try to spot the mistake)const items = getItems(), goSportsTeam = true; dragonball = 'z';// goodconst items = getItems();const goSportsTeam = true;const dragonball = 'z';``` - 13.3 Group all your const s and then group all your let s. > Why? This is helpful when later on you might need to assign a variable depending on one of the previously assigned variables.```javascript// badlet i, len, dragonball, items = getItems(), goSportsTeam = true;// badlet i;const items = getItems();let dragonball;const goSportsTeam = true;let len;// goodconst goSportsTeam = true;const items = getItems();let dragonball;let i;let length;``` - 13.4 Assign variables where you need them, but place them in a reasonable place. > Why? `let` and `const` are block scoped and not function scoped.```javascript// bad - unnecessary function callfunction checkName(hasName) { const name = getName(); if (hasName === 'test') { return false; } if (name === 'test') { this.setName(''); return false; } return name;}// goodfunction checkName(hasName) { if (hasName === 'test') { return false; } const name = getName(); if (name === 'test') { this.setName(''); return false; } return name;}``` - 13.5 Don’t chain variable assignments. eslint: <code>no-multi-assign</code> > Why? Chaining variable assignments creates implicit global variables.```javascript// bad(function example() { // JavaScript interprets this as // let a = ( b = ( c = 1 ) ); // The let keyword only applies to variable a; variables b and c become // global variables. let a = b = c = 1;}());console.log(a); // throws ReferenceErrorconsole.log(b); // 1console.log(c); // 1// good(function example() { let a = 1; let b = a; let c = a;}());console.log(a); // throws ReferenceErrorconsole.log(b); // throws ReferenceErrorconsole.log(c); // throws ReferenceError// the same applies for `const```` - 13.6 Avoid using unary increments and decrements ( ++ , -- ). eslint <code>no-plusplus</code> > Why? Per the eslint documentation, unary increment and decrement statements are subject to automatic semicolon insertion and can cause silent errors with incrementing or decrementing values within an application. It is also more expressive to mutate your values with statements like `num += 1` instead of `num++` or `num ++`. Disallowing unary increment and decrement statements also prevents you from pre-incrementing/pre-decrementing values unintentionally which can also cause unexpected behavior in your programs.```javascript// badconst array = [1, 2, 3];let num = 1;num++;--num;let sum = 0;let truthyCount = 0;for (let i = 0; i < array.length; i++) { let value = array[i]; sum += value; if (value) { truthyCount++; }}// goodconst array = [1, 2, 3];let num = 1;num += 1;num -= 1;const sum = array.reduce((a, b) => a + b, 0);const truthyCount = array.filter(Boolean).length;``` - 13.7 Avoid linebreaks before or after = in an assignment. If your assignment violates <code>max-len</code> , surround the value in parens. eslint <code>operator-linebreak</code> . > Why? Linebreaks surrounding `=` can obfuscate the value of an assignment.```javascript// badconst foo = superLongLongLongLongLongLongLongLongFunctionName();// badconst foo = 'superLongLongLongLongLongLongLongLongString';// goodconst foo = ( superLongLongLongLongLongLongLongLongFunctionName());// goodconst foo = 'superLongLongLongLongLongLongLongLongString';``` - 13.8 Disallow unused variables. eslint: <code>no-unused-vars</code> > Why? Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.```javascript// badconst some_unused_var = 42;// Write-only variables are not considered as used.let y = 10;y = 5;// A read for a modification of itself is not considered as used.let z = 0;z = z + 1;// Unused function arguments.function getX(x, y) { return x;}// goodfunction getXPlusY(x, y) { return x + y;}const x = 1;const y = a + 2;alert(getXPlusY(x, y));// 'type' is ignored even if unused because it has a rest property sibling.// This is a form of extracting an object that omits the specified keys.const { type, ...coords } = data;// 'coords' is now the 'data' object without its 'type' property.``` ⬆ back to top Hoisting - 14.1 var declarations get hoisted to the top of their closest enclosing function scope, their assignment does not. const and let declarations are blessed with a new concept called Temporal Dead Zones (TDZ) . It’s important to know why typeof is no longer safe . ```javascript// we know this wouldn’t work (assuming there// is no notDefined global variable)function example() { console.log(notDefined); // => throws a ReferenceError}// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.function example() { console.log(declaredButNotAssigned); // => undefined var declaredButNotAssigned = true;}// the interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:function example() { let declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true;}// using const and letfunction example() { console.log(declaredButNotAssigned); // => throws a ReferenceError console.log(typeof declaredButNotAssigned); // => throws a ReferenceError const declaredButNotAssigned = true;}``` - 14.2 Anonymous function expressions hoist their variable name, but not the function assignment. ```javascriptfunction example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log('anonymous function expression'); };}``` - 14.3 Named function expressions hoist the variable name, not the function name or the function body. ```javascriptfunction example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var named = function superPower() { console.log('Flying'); };}// the same is true when the function name// is the same as the variable name.function example() { console.log(named); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log('named'); };}``` - 14.4 Function declarations hoist their name and the function body. ```javascriptfunction example() { superPower(); // => Flying function superPower() { console.log('Flying'); }}``` For more information refer to JavaScript Scoping & Hoisting by Ben Cherry . ⬆ back to top Comparison Operators & Equality - 15.1 Use === and !== over == and != . eslint: <code>eqeqeq</code> - 15.2 Conditional statements such as the if statement evaluate their expression using coercion with the ToBoolean abstract method and always follow these simple rules: - **Objects** evaluate to **true**- **Undefined** evaluates to **false**- **Null** evaluates to **false**- **Booleans** evaluate to **the value of the boolean**- **Numbers** evaluate to **false** if **+0, -0, or NaN**, otherwise **true**- **Strings** evaluate to **false** if an empty string `''`, otherwise **true**```javascriptif ([0] && []) { // true // an array (even an empty one) is an object, objects will evaluate to true}``` - 15.3 Use shortcuts for booleans, but explicit comparisons for strings and numbers. ```javascript// badif (isValid === true) { // ...}// goodif (isValid) { // ...}// badif (name) { // ...}// goodif (name !== '') { // ...}// badif (collection.length) { // ...}// goodif (collection.length > 0) { // ...}``` - 15.4 For more information see Truth Equality and JavaScript by Angus Croll. - 15.5 Use braces to create blocks in case and default clauses that contain lexical declarations (e.g. let , const , function , and class ). eslint: <code>no-case-declarations</code> > Why? Lexical declarations are visible in the entire `switch` block but only get initialized when assigned, which only happens when its `case` is reached. This causes problems when multiple `case` clauses attempt to define the same thing.```javascript// badswitch (foo) { case 1: let x = 1; break; case 2: const y = 2; break; case 3: function f() { // ... } break; default: class C {}}// goodswitch (foo) { case 1: { let x = 1; break; } case 2: { const y = 2; break; } case 3: { function f() { // ... } break; } case 4: bar(); break; default: { class C {} }}``` - 15.6 Ternaries should not be nested and generally be single line expressions. eslint: <code>no-nested-ternary</code> ```javascript// badconst foo = maybe1 > maybe2 ? "bar" : value1 > value2 ? "baz" : null;// split into 2 separated ternary expressionsconst maybeNull = value1 > value2 ? 'baz' : null;// betterconst foo = maybe1 > maybe2 ? 'bar' : maybeNull;// bestconst foo = maybe1 > maybe2 ? 'bar' : maybeNull;``` - 15.7 Avoid unneeded ternary statements. eslint: <code>no-unneeded-ternary</code> ```javascript// badconst foo = a ? a : b;const bar = c ? true : false;const baz = c ? false : true;const quux = a != null ? a : b;// goodconst foo = a || b;const bar = !!c;const baz = !c;const quux = a ?? b;``` - 15.8 When mixing operators, enclose them in parentheses. The only exception is the standard arithmetic operators: + , - , and ** since their precedence is broadly understood. We recommend enclosing / and * in parentheses because their precedence can be ambiguous when they are mixed. eslint: <code>no-mixed-operators</code> > Why? This improves readability and clarifies the developer’s intention.```javascript// badconst foo = a && b < 0 || c > 0 || d + 1 === 0;// badconst bar = a ** b - 5 % d;// bad// one may be confused into thinking (a || b) && cif (a || b && c) { return d;}// badconst bar = a + b / c * d;// goodconst foo = (a && b < 0) || c > 0 || (d + 1 === 0);// goodconst bar = a ** b - (5 % d);// goodif (a || (b && c)) { return d;}// goodconst bar = a + (b / c) * d;``` ⬆ back to top Blocks - 16.1 Use braces with all multiline blocks. eslint: <code>nonblock-statement-body-position</code> ```javascript// badif (test) return false;// goodif (test) return false;// goodif (test) { return false;}// badfunction foo() { return false; }// goodfunction bar() { return false;}``` - 16.2 If you’re using multiline blocks with if and else , put else on the same line as your if block’s closing brace. eslint: <code>brace-style</code> ```javascript// badif (test) { thing1(); thing2();}else { thing3();}// goodif (test) { thing1(); thing2();} else { thing3();}``` - 16.3 If an if block always executes a return statement, the subsequent else block is unnecessary. A return in an else if block following an if block that contains a return can be separated into multiple if blocks. eslint: <code>no-else-return</code> ```javascript// badfunction foo() { if (x) { return x; } else { return y; }}// badfunction cats() { if (x) { return x; } else if (y) { return y; }}// badfunction dogs() { if (x) { return x; } else { if (y) { return y; } }}// goodfunction foo() { if (x) { return x; } return y;}// goodfunction cats() { if (x) { return x; } if (y) { return y; }}// goodfunction dogs(x) { if (x) { if (z) { return y; } } else { return z; }}``` ⬆ back to top Control Statements - 17.1 In case your control statement ( if , while etc.) gets too long or exceeds the maximum line length, each (grouped) condition could be put into a new line. The logical operator should begin the line. > Why? Requiring operators at the beginning of the line keeps the operators aligned and follows a pattern similar to method chaining. This also improves readability by making it easier to visually follow complex logic.```javascript// badif ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1();}// badif (foo === 123 && bar === 'abc') { thing1();}// badif (foo === 123 && bar === 'abc') { thing1();}// badif ( foo === 123 && bar === 'abc') { thing1();}// goodif ( foo === 123 && bar === 'abc') { thing1();}// goodif ( (foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { thing1();}// goodif (foo === 123 && bar === 'abc') { thing1();}``` - 17.2 Don't use selection operators in place of control statements. ```javascript// bad!isRunning && startRunning();// goodif (!isRunning) { startRunning();}``` ⬆ back to top Comments - 18.1 Use /** ... */ for multiline comments. ```javascript// bad// make() returns a new element// based on the passed in tag name//// @param {String} tag// @return {Element} elementfunction make(tag) { // ... return element;}// good/** * make() returns a new element * based on the passed-in tag name */function make(tag) { // ... return element;}``` - 18.2 Use // for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment unless it’s on the first line of a block. ```javascript// badconst active = true; // is current tab// good// is current tabconst active = true;// badfunction getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type;}// goodfunction getType() { console.log('fetching type...'); // set the default type to 'no type' const type = this.type || 'no type'; return type;}// also goodfunction getType() { // set the default type to 'no type' const type = this.type || 'no type'; return type;}``` - 18.3 Start all comments with a space to make it easier to read. eslint: <code>spaced-comment</code> ```javascript// bad//is current tabconst active = true;// good// is current tabconst active = true;// bad/** *make() returns a new element *based on the passed-in tag name */function make(tag) { // ... return element;}// good/** * make() returns a new element * based on the passed-in tag name */function make(tag) { // ... return element;}``` - 18.4 Prefixing your comments with FIXME or TODO helps other developers quickly understand if you’re pointing out a problem that needs to be revisited, or if you’re suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable. The actions are FIXME: -- need to figure this out or TODO: -- need to implement . - 18.5 Use // FIXME: to annotate problems. ```javascriptclass Calculator extends Abacus { constructor() { super(); // FIXME: shouldn’t use a global here total = 0; }}``` - 18.6 Use // TODO: to annotate solutions to problems. ```javascriptclass Calculator extends Abacus { constructor() { super(); // TODO: total should be configurable by an options param this.total = 0; }}``` ⬆ back to top Whitespace - 19.1 Use soft tabs (space character) set to 2 spaces. eslint: <code>indent</code> ```javascript// badfunction foo() {∙∙∙∙let name;}// badfunction bar() {∙let name;}// goodfunction baz() {∙∙let name;}``` - 19.2 Place 1 space before the leading brace. eslint: <code>space-before-blocks</code> ```javascript// badfunction test(){ console.log('test');}// goodfunction test() { console.log('test');}// baddog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog',});// gooddog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog',});``` - 19.3 Place 1 space before the opening parenthesis in control statements ( if , while etc.). Place no space between the argument list and the function name in function calls and declarations. eslint: <code>keyword-spacing</code> ```javascript// badif(isJedi) { fight ();}// goodif (isJedi) { fight();}// badfunction fight () { console.log ('Swooosh!');}// goodfunction fight() { console.log('Swooosh!');}``` - 19.4 Set off operators with spaces. eslint: <code>space-infix-ops</code> ```javascript// badconst x=y+5;// goodconst x = y + 5;``` - 19.5 End files with a single newline character. eslint: <code>eol-last</code> ```javascript// badimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;``````javascript// badimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;↵↵``````javascript// goodimport { es6 } from './AirbnbStyleGuide'; // ...export default es6;↵``` - 19.6 Use indentation when making long method chains (more than 2 method chains). Use a leading dot, which emphasizes that the line is a method call, not a new statement. eslint: <code>newline-per-chained-call</code> <code>no-whitespace-before-property</code> ```javascript// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// bad$('#items'). find('.selected'). highlight(). end(). find('.open'). updateCount();// good$('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount();// badconst leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', `translate(${radius + margin}, ${radius + margin})`) .call(tron.led);// goodconst leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .classed('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', `translate(${radius + margin}, ${radius + margin})`) .call(tron.led);// goodconst leds = stage.selectAll('.led').data(data);const svg = leds.enter().append('svg:svg');svg.classed('led', true).attr('width', (radius + margin) * 2);const g = svg.append('svg:g');g.attr('transform', `translate(${radius + margin}, ${radius + margin})`).call(tron.led);``` - 19.7 Leave a blank line after blocks and before the next statement. ```javascript// badif (foo) { return bar;}return baz;// goodif (foo) { return bar;}return baz;// badconst obj = { foo() { }, bar() { },};return obj;// goodconst obj = { foo() { }, bar() { },};return obj;// badconst arr = [ function foo() { }, function bar() { },];return arr;// goodconst arr = [ function foo() { }, function bar() { },];return arr;``` - 19.8 Do not pad your blocks with blank lines. eslint: <code>padded-blocks</code> ```javascript// badfunction bar() { console.log(foo);}// badif (baz) { console.log(quux);} else { console.log(foo);}// badclass Foo { constructor(bar) { this.bar = bar; }}// goodfunction bar() { console.log(foo);}// goodif (baz) { console.log(quux);} else { console.log(foo);}``` - 19.9 Do not use multiple blank lines to pad your code. eslint: <code>no-multiple-empty-lines</code> <!-- markdownlint-disable MD012 -->```javascript// badclass Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = this.getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. }}// goodclass Person { constructor(fullName, email, birthday) { this.fullName = fullName; this.email = email; this.setAge(birthday); } setAge(birthday) { const today = new Date(); const age = getAge(today, birthday); this.age = age; } getAge(today, birthday) { // .. }}``` - 19.10 Do not add spaces inside parentheses. eslint: <code>space-in-parens</code> ```javascript// badfunction bar( foo ) { return foo;}// goodfunction bar(foo) { return foo;}// badif ( foo ) { console.log(foo);}// goodif (foo) { console.log(foo);}``` - 19.11 Do not add spaces inside brackets. eslint: <code>array-bracket-spacing</code> ```javascript// badconst foo = [ 1, 2, 3 ];console.log(foo[ 0 ]);// goodconst foo = [1, 2, 3];console.log(foo[0]);``` - 19.12 Add spaces inside curly braces. eslint: <code>object-curly-spacing</code> ```javascript// badconst foo = {clark: 'kent'};// goodconst foo = { clark: 'kent' };``` - 19.13 Avoid having lines of code that are longer than 100 characters (including whitespace). Note: per above , long strings are exempt from this rule, and should not be broken up. eslint: <code>max-len</code> > Why? This ensures readability and maintainability.```javascript// badconst foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;// bad$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.'));// goodconst foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy;// betterconst foo = jsonData ?.foo ?.bar ?.baz ?.quux ?.xyzzy;// good$.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' },}) .done(() => console.log('Congratulations!')) .fail(() => console.log('You have failed this city.'));``` - 19.14 Require consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line. eslint: <code>block-spacing</code> ```javascript// badfunction foo() {return true;}if (foo) { bar = 0;}// goodfunction foo() { return true; }if (foo) { bar = 0; }``` - 19.15 Avoid spaces before commas and require a space after commas. eslint: <code>comma-spacing</code> ```javascript// badconst foo = 1,bar = 2;const arr = [1 , 2];// goodconst foo = 1, bar = 2;const arr = [1, 2];``` - 19.16 Enforce spacing inside of computed property brackets. eslint: <code>computed-property-spacing</code> ```javascript// badobj[foo ]obj[ 'foo']const x = {[ b ]: a}obj[foo[ bar ]]// goodobj[foo]obj['foo']const x = { [b]: a }obj[foo[bar]]``` - 19.17 Avoid spaces between functions and their invocations. eslint: <code>func-call-spacing</code> ```javascript// badfunc ();func();// goodfunc();``` - 19.18 Enforce spacing between keys and values in object literal properties. eslint: <code>key-spacing</code> ```javascript// badconst obj = { foo : 42 };const obj2 = { foo:42 };// goodconst obj = { foo: 42 };``` - 19.19 Avoid trailing spaces at the end of lines. eslint: <code>no-trailing-spaces</code> - 19.20 Avoid multiple empty lines, only allow one newline at the end of files, and avoid a newline at the beginning of files. eslint: <code>no-multiple-empty-lines</code> <!-- markdownlint-disable MD012 -->```javascript// bad - multiple empty linesconst x = 1;const y = 2;// bad - 2+ newlines at end of fileconst x = 1;const y = 2;// bad - 1+ newline(s) at beginning of fileconst x = 1;const y = 2;// goodconst x = 1;const y = 2;```<!-- markdownlint-enable MD012 --> ⬆ back to top Commas - 20.1 Leading commas: Nope. eslint: <code>comma-style</code> ```javascript// badconst story = [ once , upon , aTime];// goodconst story = [ once, upon, aTime,];// badconst hero = { firstName: 'Ada' , lastName: 'Lovelace' , birthYear: 1815 , superPower: 'computers'};// goodconst hero = { firstName: 'Ada', lastName: 'Lovelace', birthYear: 1815, superPower: 'computers',};``` - 20.2 Additional trailing comma: Yup. eslint: <code>comma-dangle</code> > Why? This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don’t have to worry about the [trailing comma problem](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) in legacy browsers.```diff// bad - git diff without trailing commaconst hero = { firstName: 'Florence',- lastName: 'Nightingale'+ lastName: 'Nightingale',+ inventorOf: ['coxcomb chart', 'modern nursing']};// good - git diff with trailing commaconst hero = { firstName: 'Florence', lastName: 'Nightingale',+ inventorOf: ['coxcomb chart', 'modern nursing'],};``````javascript// badconst hero = { firstName: 'Dana', lastName: 'Scully'};const heroes = [ 'Batman', 'Superman'];// goodconst hero = { firstName: 'Dana', lastName: 'Scully',};const heroes = [ 'Batman', 'Superman',];// badfunction createHero( firstName, lastName, inventorOf) { // does nothing}// goodfunction createHero( firstName, lastName, inventorOf,) { // does nothing}// good (note that a comma must not appear after a "rest" element)function createHero( firstName, lastName, inventorOf, ...heroArgs) { // does nothing}// badcreateHero( firstName, lastName, inventorOf);// goodcreateHero( firstName, lastName, inventorOf,);// good (note that a comma must not appear after a "rest" element)createHero( firstName, lastName, inventorOf, ...heroArgs);``` ⬆ back to top Semicolons - 21.1 Yup. eslint: <code>semi</code> > Why? When JavaScript encounters a line break without a semicolon, it uses a set of rules called [Automatic Semicolon Insertion](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) to determine whether it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break. These rules will become more complicated as new features become a part of JavaScript. Explicitly terminating your statements and configuring your linter to catch missing semicolons will help prevent you from encountering issues.```javascript// bad - raises exceptionconst luke = {}const leia = {}[luke, leia].forEach((jedi) => jedi.father = 'vader')// bad - raises exceptionconst reaction = "No! That’s impossible!"(async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ...}())// bad - returns `undefined` instead of the value on the next line - always happens when `return` is on a line by itself because of ASI!function foo() { return 'search your feelings, you know it to be foo'}// goodconst luke = {};const leia = {};[luke, leia].forEach((jedi) => { jedi.father = 'vader';});// goodconst reaction = 'No! That’s impossible!';(async function meanwhileOnTheFalcon() { // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` // ...}());// goodfunction foo() { return 'search your feelings, you know it to be foo';}```[Read more](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214). ⬆ back to top Type Casting & Coercion - 22.1 Perform type coercion at the beginning of the statement. - 22.2 Strings: eslint: <code>no-new-wrappers</code> ```javascript// => this.reviewScore = 9;// badconst totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string"// badconst totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf()// badconst totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string// goodconst totalScore = String(this.reviewScore);``` - 22.3 Numbers: Use Number for type casting and parseInt always with a radix for parsing strings. eslint: <code>radix</code> <code>no-new-wrappers</code> > Why? The `parseInt` function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading whitespace in string is ignored. If radix is `undefined` or `0`, it is assumed to be `10` except when the number begins with the character pairs `0x` or `0X`, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix.```javascriptconst inputValue = '4';// badconst val = new Number(inputValue);// badconst val = +inputValue;// badconst val = inputValue >> 0;// badconst val = parseInt(inputValue);// goodconst val = Number(inputValue);// goodconst val = parseInt(inputValue, 10);``` - 22.4 If for whatever reason you are doing something wild and parseInt is your bottleneck and need to use Bitshift for performance reasons , leave a comment explaining why and what you’re doing. ```javascript// good/** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */const val = inputValue >> 0;``` - 22.5 Note: Be careful when using bitshift operations. Numbers are represented as 64-bit values , but bitshift operations always return a 32-bit integer ( source ). Bitshift can lead to unexpected behavior for integer values larger than 32 bits. Discussion . Largest signed 32-bit Int is 2,147,483,647: ```javascript2147483647 >> 0; // => 21474836472147483648 >> 0; // => -21474836482147483649 >> 0; // => -2147483647``` - 22.6 Booleans: eslint: <code>no-new-wrappers</code> ```javascriptconst age = 0;// badconst hasAge = new Boolean(age);// goodconst hasAge = Boolean(age);// bestconst hasAge = !!age;``` ⬆ back to top Naming Conventions - 23.1 Avoid single letter names. Be descriptive with your naming. eslint: <code>id-length</code> ```javascript// badfunction q() { // ...}// goodfunction query() { // ...}``` - 23.2 Use camelCase when naming objects, functions, and instances. eslint: <code>camelcase</code> ```javascript// badconst OBJEcttsssss = {};const this_is_my_object = {};function c() {}// goodconst thisIsMyObject = {};function thisIsMyFunction() {}``` - 23.3 Use PascalCase only when naming constructors or classes. eslint: <code>new-cap</code> ```javascript// badfunction user(options) { this.name = options.name;}const bad = new user({ name: 'nope',});// goodclass User { constructor(options) { this.name = options.name; }}const good = new User({ name: 'yup',});``` - 23.4 Do not use trailing or leading underscores. eslint: <code>no-underscore-dangle</code> > Why? JavaScript does not have the concept of privacy in terms of properties or methods. Although a leading underscore is a common convention to mean “private”, in fact, these properties are fully public, and as such, are part of your public API contract. This convention might lead developers to wrongly think that a change won’t count as breaking, or that tests aren’t needed. tl;dr: if you want something to be “private”, it must not be observably present.```javascript// badthis.__firstName__ = 'Panda';this.firstName_ = 'Panda';this._firstName = 'Panda';// goodthis.firstName = 'Panda';// good, in environments where WeakMaps are available// see https://kangax.github.io/compat-table/es6/#test-WeakMapconst firstNames = new WeakMap();firstNames.set(this, 'Panda');``` - 23.5 Don’t save references to this . Use arrow functions or Function#bind . ```javascript// badfunction foo() { const self = this; return function () { console.log(self); };}// badfunction foo() { const that = this; return function () { console.log(that); };}// goodfunction foo() { return () => { console.log(this); };}``` - 23.6 A base filename should exactly match the name of its default export. ```javascript// file 1 contentsclass CheckBox { // ...}export default CheckBox;// file 2 contentsexport default function fortyTwo() { return 42; }// file 3 contentsexport default function insideDirectory() {}// in some other file// badimport CheckBox from './checkBox'; // PascalCase import/export, camelCase filenameimport FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase exportimport InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export// badimport CheckBox from './check_box'; // PascalCase import/export, snake_case filenameimport forty_two from './forty_two'; // snake_case import/filename, camelCase exportimport inside_directory from './inside_directory'; // snake_case import, camelCase exportimport index from './inside_directory/index'; // requiring the index file explicitlyimport insideDirectory from './insideDirectory/index'; // requiring the index file explicitly// goodimport CheckBox from './CheckBox'; // PascalCase export/import/filenameimport fortyTwo from './fortyTwo'; // camelCase export/import/filenameimport insideDirectory from './insideDirectory'; // camelCase export/import/directory name/implicit "index"// ^ supports both insideDirectory.js and insideDirectory/index.js``` - 23.7 Use camelCase when you export-default a function. Your filename should be identical to your function’s name. ```javascriptfunction makeStyleGuide() { // ...}export default makeStyleGuide;``` - 23.8 Use PascalCase when you export a constructor / class / singleton / function library / bare object. ```javascriptconst AirbnbStyleGuide = { es6: { },};export default AirbnbStyleGuide;``` - 23.9 Acronyms and initialisms should always be all uppercased, or all lowercased. > Why? Names are for readability, not to appease a computer algorithm.```javascript// badimport SmsContainer from './containers/SmsContainer';// badconst HttpRequests = [ // ...];// goodimport SMSContainer from './containers/SMSContainer';// goodconst HTTPRequests = [ // ...];// also goodconst httpRequests = [ // ...];// bestimport TextMessageContainer from './containers/TextMessageContainer';// bestconst requests = [ // ...];``` - 23.10 You may optionally uppercase a constant only if it (1) is exported, (2) is a const (it can not be reassigned), and (3) the programmer can trust it (and its nested properties) to never change. > Why? This is an additional tool to assist in situations where the programmer would be unsure if a variable might ever change. UPPERCASE_VARIABLES are letting the programmer know that they can trust the variable (and its properties) not to change.- What about all `const` variables? - This is unnecessary, so uppercasing should not be used for constants within a file. It should be used for exported constants however.- What about exported objects? - Uppercase at the top level of export (e.g. `EXPORTED_OBJECT.key`) and maintain that all nested properties do not change.```javascript// badconst PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file';// badexport const THING_TO_BE_CHANGED = 'should obviously not be uppercased';// badexport let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables';// ---// allowed but does not supply semantic valueexport const apiKey = 'SOMEKEY';// better in most casesexport const API_KEY = 'SOMEKEY';// ---// bad - unnecessarily uppercases key while adding no semantic valueexport const MAPPING = { KEY: 'value'};// goodexport const MAPPING = { key: 'value',};``` ⬆ back to top Accessors - 24.1 Accessor functions for properties are not required. - 24.2 Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello') . ```javascript// badclass Dragon { get age() { // ... } set age(value) { // ... }}// goodclass Dragon { getAge() { // ... } setAge(value) { // ... }}``` - 24.3 If the property/method is a boolean , use isVal() or hasVal() . ```javascript// badif (!dragon.age()) { return false;}// goodif (!dragon.hasAge()) { return false;}``` - 24.4 It’s okay to create get() and set() functions, but be consistent. ```javascriptclass Jedi { constructor(options = {}) { const lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber); } set(key, val) { this[key] = val; } get(key) { return this[key]; }}``` ⬆ back to top Events - 25.1 When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of: ```javascript// bad$(this).trigger('listingUpdated', listing.id);// ...$(this).on('listingUpdated', (e, listingID) => { // do something with listingID});```prefer:```javascript// good$(this).trigger('listingUpdated', { listingID: listing.id });// ...$(this).on('listingUpdated', (e, data) => { // do something with data.listingID});``` ⬆ back to top jQuery - 26.1 Prefix jQuery object variables with a $ . ```javascript// badconst sidebar = $('.sidebar');// goodconst $sidebar = $('.sidebar');// goodconst $sidebarBtn = $('.sidebar-btn');``` - 26.2 Cache jQuery lookups. ```javascript// badfunction setSidebar() { $('.sidebar').hide(); // ... $('.sidebar').css({ 'background-color': 'pink', });}// goodfunction setSidebar() { const $sidebar = $('.sidebar'); $sidebar.hide(); // ... $sidebar.css({ 'background-color': 'pink', });}``` - 26.3 For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul') . jsPerf - 26.4 Use find with scoped jQuery object queries. ```javascript// bad$('ul', '.sidebar').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good$sidebar.find('ul').hide();``` ⬆ back to top ECMAScript 5 Compatibility - 27.1 Refer to Kangax ’s ES5 compatibility table . ⬆ back to top ECMAScript 6+ (ES 2015+) Styles - 28.1 This is a collection of links to the various ES6+ features. Arrow Functions Classes Object Shorthand Object Concise Object Computed Properties Template Strings Destructuring Default Parameters Rest Array Spreads Let and Const Exponentiation Operator Iterators and Generators Modules 28.2 Do not use TC39 proposals that have not reached stage 3. Why? They are not finalized , and they are subject to change or to be withdrawn entirely. We want to use JavaScript, and proposals are not JavaScript yet. ⬆ back to top Standard Library The Standard Library contains utilities that are functionally broken but remain for legacy reasons. - 29.1 Use Number.isNaN instead of global isNaN . eslint: <code>no-restricted-globals</code> > Why? The global `isNaN` coerces non-numbers to numbers, returning true for anything that coerces to NaN.> If this behavior is desired, make it explicit.```javascript// badisNaN('1.2'); // falseisNaN('1.2.3'); // true// goodNumber.isNaN('1.2.3'); // falseNumber.isNaN(Number('1.2.3')); // true``` - 29.2 Use Number.isFinite instead of global isFinite . eslint: <code>no-restricted-globals</code> > Why? The global `isFinite` coerces non-numbers to numbers, returning true for anything that coerces to a finite number.> If this behavior is desired, make it explicit.```javascript// badisFinite('2e3'); // true// goodNumber.isFinite('2e3'); // falseNumber.isFinite(parseInt('2e3', 10)); // true``` ⬆ back to top Testing - 30.1 Yup. ```javascriptfunction foo() { return true;}``` - 30.2 No, but seriously : - Whichever testing framework you use, you should be writing tests! - Strive to write many small pure functions, and minimize where mutations occur. - Be cautious about stubs and mocks - they can make your tests more brittle. - We primarily use <code>mocha</code> and <code>jest</code> at Airbnb. <code>tape</code> is also used occasionally for small, separate modules. - 100% test coverage is a good goal to strive for, even if it’s not always practical to reach it. - Whenever you fix a bug, write a regression test . A bug fixed without a regression test is almost certainly going to break again in the future. ⬆ back to top Performance On Layout & Web Performance String vs Array Concat Try/Catch Cost In a Loop Bang Function jQuery Find vs Context, Selector innerHTML vs textContent for script text Long String Concatenation Are JavaScript functions like <code>map()</code>, <code>reduce()</code>, and <code>filter()</code> optimized for traversing arrays? Loading... ⬆ back to top Resources Learning ES6+ Latest ECMA spec ExploringJS ES6 Compatibility Table Comprehensive Overview of ES6 Features JavaScript Roadmap Read This Standard ECMA-262 Tools Code Style Linters ESlint - Airbnb Style .eslintrc JSHint - Airbnb Style .jshintrc Neutrino Preset - @neutrinojs/airbnb Other Style Guides Google JavaScript Style Guide Google JavaScript Style Guide (Old) jQuery Core Style Guidelines Principles of Writing Consistent, Idiomatic JavaScript StandardJS Other Styles Naming this in nested functions - Christian Johansen Conditional Callbacks - Ross Allen Popular JavaScript Coding Conventions on GitHub - JeongHoon Byun Multiple var statements in JavaScript, not superfluous - Ben Alman Further Reading Understanding JavaScript Closures - Angus Croll Basic JavaScript for the impatient programmer - Dr. Axel Rauschmayer You Might Not Need jQuery - Zack Bloom & Adam Schwartz ES6 Features - Luke Hoban Frontend Guidelines - Benjamin De Cock Books JavaScript: The Good Parts - Douglas Crockford JavaScript Patterns - Stoyan Stefanov Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders Maintainable JavaScript - Nicholas C. Zakas JavaScript Web Applications - Alex MacCaw Pro JavaScript Techniques - John Resig Smashing Node.js: JavaScript Everywhere - Guillermo Rauch Secrets of the JavaScript Ninja - John Resig and Bear Bibeault Human JavaScript - Henrik Joreteg Superhero.js - Kim Joar Bekkelund, Mads Mobæk, & Olav Bjorkoy JSBooks - Julien Bouquillon Third Party JavaScript - Ben Vinegar and Anton Kovalyov Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript - David Herman Eloquent JavaScript - Marijn Haverbeke You Don’t Know JS: ES6 & Beyond - Kyle Simpson Blogs JavaScript Weekly JavaScript, JavaScript... Bocoup Weblog Adequately Good NCZOnline Perfection Kills Ben Alman Dmitry Baranovskiy nettuts Podcasts JavaScript Air JavaScript Jabber ⬆ back to top In the Wild This is a list of organizations that are using this style guide. Send us a pull request and we'll add you to the list. 123erfasst : 123erfasst/javascript 4Catalyzer : 4Catalyzer/javascript Aan Zee : AanZee/javascript Airbnb : airbnb/javascript AloPeyk : AloPeyk AltSchool : AltSchool/javascript Apartmint : apartmint/javascript Ascribe : ascribe/javascript Avant : avantcredit/javascript Axept : axept/javascript Billabong : billabong/javascript Bisk : bisk Bonhomme : bonhommeparis/javascript Brainshark : brainshark/javascript CaseNine : CaseNine/javascript Cerner : Cerner Chartboost : ChartBoost/javascript-style-guide Coeur d'Alene Tribe : www.cdatribe-nsn.gov ComparaOnline : comparaonline/javascript Compass Learning : compasslearning/javascript-style-guide DailyMotion : dailymotion/javascript DoSomething : DoSomething/eslint-config Digitpaint digitpaint/javascript Drupal : www.drupal.org Ecosia : ecosia/javascript Evernote : evernote/javascript-style-guide Evolution Gaming : evolution-gaming/javascript EvozonJs : evozonjs/javascript ExactTarget : ExactTarget/javascript Flexberry : Flexberry/javascript-style-guide Gawker Media : gawkermedia General Electric : GeneralElectric/javascript Generation Tux : GenerationTux/javascript GoodData : gooddata/gdc-js-style GreenChef : greenchef/javascript Grooveshark : grooveshark/javascript Grupo-Abraxas : Grupo-Abraxas/javascript Happeo : happeo/javascript Honey : honeyscience/javascript How About We : howaboutwe/javascript HubSpot : HubSpot/javascript Hyper : hyperoslo/javascript-playbook InterCity Group : intercitygroup/javascript-style-guide Jam3 : Jam3/Javascript-Code-Conventions JSSolutions : JSSolutions/javascript Kaplan Komputing : kaplankomputing/javascript KickorStick : kickorstick Kinetica Solutions : kinetica/javascript LEINWAND : LEINWAND/javascript Lonely Planet : lonelyplanet/javascript M2GEN : M2GEN/javascript Mighty Spring : mightyspring/javascript MinnPost : MinnPost/javascript MitocGroup : MitocGroup/javascript Muber : muber National Geographic Society : natgeosociety NullDev : NullDevCo/JavaScript-Styleguide Nulogy : nulogy/javascript Orange Hill Development : orangehill/javascript Orion Health : orionhealth/javascript Peerby : Peerby/javascript Pier 1 : Pier1/javascript Qotto : Qotto/javascript-style-guide React : reactjs.org/docs/how-to-contribute.html#style-guide REI : reidev/js-style-guide Ripple : ripple/javascript-style-guide Sainsbury’s Supermarkets : jsainsburyplc Shutterfly : shutterfly/javascript Sourcetoad : sourcetoad/javascript Springload : springload StratoDem Analytics : stratodem/javascript SteelKiwi Development : steelkiwi/javascript StudentSphere : studentsphere/javascript SwoopApp : swoopapp/javascript SysGarage : sysgarage/javascript-style-guide Syzygy Warsaw : syzygypl/javascript Target : target/javascript Terra : terra TheLadders : TheLadders/javascript The Nerdery : thenerdery/javascript-standards Tomify : tomprats Traitify : traitify/eslint-config-traitify T4R Technology : T4R-Technology/javascript UrbanSim : urbansim VoxFeed : VoxFeed/javascript-style-guide WeBox Studio : weboxstudio/javascript Weggo : Weggo/javascript Zillow : zillow/javascript ZocDoc : ZocDoc/javascript ⬆ back to top Translation This style guide is also available in other languages: Brazilian Portuguese : armoucar/javascript-style-guide Bulgarian : borislavvv/javascript Catalan : fpmweb/javascript-style-guide Chinese (Simplified) : lin-123/javascript Chinese (Traditional) : jigsawye/javascript French : nmussy/javascript-style-guide German : timofurrer/javascript-style-guide Italian : sinkswim/javascript-style-guide Japanese : mitsuruog/javascript-style-guide Korean : ParkSB/javascript-style-guide Russian : leonidlebedev/javascript-airbnb Spanish : paolocarrasco/javascript-style-guide Thai : lvarayut/javascript-style-guide Turkish : eraycetinay/javascript Ukrainian : ivanzusko/javascript Vietnam : dangkyokhoang/javascript-style-guide The JavaScript Style Guide Guide Reference Chat With Us About JavaScript Find us on gitter . Contributors View Contributors License (The MIT License) Copyright (c) 2012 Airbnb Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the'Software'), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions: The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANYCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THESOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ⬆ back to top Amendments We encourage you to fork this guide and change the rules to fit your team’s style guide. Below, you may list some amendments to the style guide. This allows you to periodically update your style guide without having to deal with merge conflicts. }; To restore the repository download the bundle wget https://archive.org/download/github.com-airbnb-javascript_-_2023-05-15_21-29-30/airbnb-javascript_-_2023-05-15_21-29-30.bundle and run: git clone airbnb-javascript_-_2023-05-15_21-29-30.bundle Source: https://github.com/airbnb/javascript Uploader: airbnb Upload date: 2023-05-15

“Github.com-airbnb-javascript_-_2023-05-15_21-29-30” Metadata:

  • Title: ➤  Github.com-airbnb-javascript_-_2023-05-15_21-29-30
  • Author:

“Github.com-airbnb-javascript_-_2023-05-15_21-29-30” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 4.15 Mbs, the file-s for this book were downloaded 42 times, the file-s went public at Wed May 17 2023.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-airbnb-javascript_-_2023-05-15_21-29-30 at online marketplaces:


32Github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57

By

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings JavaScript Algorithms and Data Structures 🇺🇦 UKRAINE IS BEING ATTACKED BY RUSSIAN ARMY. CIVILIANS ARE GETTING KILLED. RESIDENTIAL AREAS ARE GETTING BOMBED. - Help Ukraine via National Bank of Ukraine - Help Ukraine via SaveLife fund - More info on war.ukraine.ua This repository contains JavaScript based examples of manypopular algorithms and data structures. Each algorithm and data structure has its own separate READMEwith related explanations and links for further reading (including onesto YouTube videos). Read this in other languages: 简体中文 , 繁體中文 , 한국어 , 日本語 , Polski , Français , Español , Português , Русский , Türk , Italiana , Bahasa Indonesia , Українська , Arabic , Tiếng Việt , Deutsch ☝ Note that this project is meant to be used for learning and researching purposesonly, and it is not meant to be used for production. Data Structures A data structure is a particular way of organizing and storing data in a computer so that it canbe accessed and modified efficiently. More precisely, a data structure is a collection of datavalues, the relationships among them, and the functions or operations that can be applied tothe data. B - Beginner, A - Advanced B Linked List B Doubly Linked List B Queue B Stack B Hash Table B Heap - max and min heap versions B Priority Queue A Trie A Tree A Binary Search Tree A AVL Tree A Red-Black Tree A Segment Tree - with min/max/sum range queries examples A Fenwick Tree (Binary Indexed Tree) A Graph (both directed and undirected) A Disjoint Set A Bloom Filter Algorithms An algorithm is an unambiguous specification of how to solve a class of problems. It isa set of rules that precisely define a sequence of operations. B - Beginner, A - Advanced Algorithms by Topic Math B Bit Manipulation - set/get/update/clear bits, multiplication/division by two, make negative etc. B Binary Floating Point - binary representation of the floating-point numbers. B Factorial B Fibonacci Number - classic and closed-form versions B Prime Factors - finding prime factors and counting them using Hardy-Ramanujan's theorem B Primality Test (trial division method) B Euclidean Algorithm - calculate the Greatest Common Divisor (GCD) B Least Common Multiple (LCM) B Sieve of Eratosthenes - finding all prime numbers up to any given limit B Is Power of Two - check if the number is power of two (naive and bitwise algorithms) B Pascal's Triangle B Complex Number - complex numbers and basic operations with them B Radian & Degree - radians to degree and backwards conversion B Fast Powering B Horner's method - polynomial evaluation B Matrices - matrices and basic matrix operations (multiplication, transposition, etc.) B Euclidean Distance - distance between two points/vectors/matrices A Integer Partition A Square Root - Newton's method A Liu Hui π Algorithm - approximate π calculations based on N-gons A Discrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up Sets B Cartesian Product - product of multiple sets B Fisher–Yates Shuffle - random permutation of a finite sequence A Power Set - all subsets of a set (bitwise and backtracking solutions) A Permutations (with and without repetitions) A Combinations (with and without repetitions) A Longest Common Subsequence (LCS) A Longest Increasing Subsequence A Shortest Common Supersequence (SCS) A Knapsack Problem - "0/1" and "Unbound" ones A Maximum Subarray - "Brute Force" and "Dynamic Programming" (Kadane's) versions A Combination Sum - find all combinations that form specific sum Strings B Hamming Distance - number of positions at which the symbols are different B Palindrome - check if the string is the same in reverse A Levenshtein Distance - minimum edit distance between two sequences A Knuth–Morris–Pratt Algorithm (KMP Algorithm) - substring search (pattern matching) A Z Algorithm - substring search (pattern matching) A Rabin Karp Algorithm - substring search A Longest Common Substring A Regular Expression Matching Searches B Linear Search B Jump Search (or Block Search) - search in sorted array B Binary Search - search in sorted array B Interpolation Search - search in uniformly distributed sorted array Sorting B Bubble Sort B Selection Sort B Insertion Sort B Heap Sort B Merge Sort B Quicksort - in-place and non-in-place implementations B Shellsort B Counting Sort B Radix Sort Linked Lists B Straight Traversal B Reverse Traversal Trees B Depth-First Search (DFS) B Breadth-First Search (BFS) Graphs B Depth-First Search (DFS) B Breadth-First Search (BFS) B Kruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph A Dijkstra Algorithm - finding the shortest paths to all graph vertices from single vertex A Bellman-Ford Algorithm - finding the shortest paths to all graph vertices from single vertex A Floyd-Warshall Algorithm - find the shortest paths between all pairs of vertices A Detect Cycle - for both directed and undirected graphs (DFS and Disjoint Set based versions) A Prim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph A Topological Sorting - DFS method A Articulation Points - Tarjan's algorithm (DFS based) A Bridges - DFS based algorithm A Eulerian Path and Eulerian Circuit - Fleury's algorithm - Visit every edge exactly once A Hamiltonian Cycle - Visit every vertex exactly once A Strongly Connected Components - Kosaraju's algorithm A Travelling Salesman Problem - shortest possible route that visits each city and returns to the origin city Cryptography B Polynomial Hash - rolling hash function based on polynomial B Rail Fence Cipher - a transposition cipher algorithm for encoding messages B Caesar Cipher - simple substitution cipher B Hill Cipher - substitution cipher based on linear algebra Machine Learning B NanoNeuron - 7 simple JS functions that illustrate how machines can actually learn (forward/backward propagation) B k-NN - k-nearest neighbors classification algorithm B k-Means - k-Means clustering algorithm Image Processing B Seam Carving - content-aware image resizing algorithm Statistics B Weighted Random - select the random item from the list based on items' weights Evolutionary algorithms A Genetic algorithm - example of how the genetic algorithm may be applied for training the self-parking cars Uncategorized B Tower of Hanoi B Square Matrix Rotation - in-place algorithm B Jump Game - backtracking, dynamic programming (top-down + bottom-up) and greedy examples B Unique Paths - backtracking, dynamic programming and Pascal's Triangle based examples B Rain Terraces - trapping rain water problem (dynamic programming and brute force versions) B Recursive Staircase - count the number of ways to reach to the top (4 solutions) B Best Time To Buy Sell Stocks - divide and conquer and one-pass examples A N-Queens Problem A Knight's Tour Algorithms by Paradigm An algorithmic paradigm is a generic method or approach which underlies the design of a classof algorithms. It is an abstraction higher than the notion of an algorithm, just as analgorithm is an abstraction higher than a computer program. Brute Force - look at all the possibilities and selects the best solution B Linear Search B Rain Terraces - trapping rain water problem B Recursive Staircase - count the number of ways to reach to the top A Maximum Subarray A Travelling Salesman Problem - shortest possible route that visits each city and returns to the origin city A Discrete Fourier Transform - decompose a function of time (a signal) into the frequencies that make it up Greedy - choose the best option at the current time, without any consideration for the future B Jump Game A Unbound Knapsack Problem A Dijkstra Algorithm - finding the shortest path to all graph vertices A Prim’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph A Kruskal’s Algorithm - finding Minimum Spanning Tree (MST) for weighted undirected graph Divide and Conquer - divide the problem into smaller parts and then solve those parts B Binary Search B Tower of Hanoi B Pascal's Triangle B Euclidean Algorithm - calculate the Greatest Common Divisor (GCD) B Merge Sort B Quicksort B Tree Depth-First Search (DFS) B Graph Depth-First Search (DFS) B Matrices - generating and traversing the matrices of different shapes B Jump Game B Fast Powering B Best Time To Buy Sell Stocks - divide and conquer and one-pass examples A Permutations (with and without repetitions) A Combinations (with and without repetitions) A Maximum Subarray Dynamic Programming - build up a solution using previously found sub-solutions B Fibonacci Number B Jump Game B Unique Paths B Rain Terraces - trapping rain water problem B Recursive Staircase - count the number of ways to reach to the top B Seam Carving - content-aware image resizing algorithm A Levenshtein Distance - minimum edit distance between two sequences A Longest Common Subsequence (LCS) A Longest Common Substring A Longest Increasing Subsequence A Shortest Common Supersequence A 0/1 Knapsack Problem A Integer Partition A Maximum Subarray A Bellman-Ford Algorithm - finding the shortest path to all graph vertices A Floyd-Warshall Algorithm - find the shortest paths between all pairs of vertices A Regular Expression Matching Backtracking - similarly to brute force, try to generate all possible solutions, but each time you generate next solution you testif it satisfies all conditions, and only then continue generating subsequent solutions. Otherwise, backtrack, and go on adifferent path of finding a solution. Normally the DFS traversal of state-space is being used. B Jump Game B Unique Paths B Power Set - all subsets of a set A Hamiltonian Cycle - Visit every vertex exactly once A N-Queens Problem A Knight's Tour A Combination Sum - find all combinations that form specific sum Branch & Bound - remember the lowest-cost solution found at each stage of the backtrackingsearch, and use the cost of the lowest-cost solution found so far as a lower bound on the cost ofa least-cost solution to the problem, in order to discard partial solutions with costs larger than thelowest-cost solution found so far. Normally BFS traversal in combination with DFS traversal of state-spacetree is being used. How to use this repository Install all dependencies npm install Run ESLint You may want to run it to check code quality. npm run lint Run all tests npm test Run tests by name npm test -- 'LinkedList' Troubleshooting In case if linting or testing is failing try to delete the node_modules folder and re-install npm packages: rm -rf ./node_modulesnpm i Also make sure that you're using a correct Node version ( >=14.16.0 ). If you're using nvm for Node version management you may run nvm use from the root folder of the project and the correct version will be picked up. Playground You may play with data-structures and algorithms in ./src/playground/playground.js file and writetests for it in ./src/playground/__test__/playground.test.js . Then just simply run the following command to test if your playground code works as expected: npm test -- 'playground' Useful Information References ▶ Data Structures and Algorithms on YouTube Big O Notation Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.On the chart below you may find most common orders of growth of algorithms specified in Big O notation. Source: Big O Cheat Sheet . Below is the list of some of the most used Big O notations and their performance comparisons against different sizes of the input data. | Big O Notation | Type | Computations for 10 elements | Computations for 100 elements | Computations for 1000 elements || -------------- | ----------- | ---------------------------- | ----------------------------- | ------------------------------- || O(1) | Constant | 1 | 1 | 1 || O(log N) | Logarithmic | 3 | 6 | 9 || O(N) | Linear | 10 | 100 | 1000 || O(N log N) | n log(n) | 30 | 600 | 9000 || O(N^2) | Quadratic | 100 | 10000 | 1000000 || O(2^N) | Exponential | 1024 | 1.26e+29 | 1.07e+301 || O(N!) | Factorial | 3628800 | 9.3e+157 | 4.02e+2567 | Data Structure Operations Complexity | Data Structure | Access | Search | Insertion | Deletion | Comments || ----------------------- | :-------: | :-------: | :-------: | :-------: | :-------- || Array | 1 | n | n | n | || Stack | n | n | 1 | 1 | || Queue | n | n | 1 | 1 | || Linked List | n | n | 1 | n | || Hash Table | - | n | n | n | In case of perfect hash function costs would be O(1) || Binary Search Tree | n | n | n | n | In case of balanced tree costs would be O(log(n)) || B-Tree | log(n) | log(n) | log(n) | log(n) | || Red-Black Tree | log(n) | log(n) | log(n) | log(n) | || AVL Tree | log(n) | log(n) | log(n) | log(n) | || Bloom Filter | - | 1 | 1 | - | False positives are possible while searching | Array Sorting Algorithms Complexity | Name | Best | Average | Worst | Memory | Stable | Comments || --------------------- | :-------------: | :-----------------: | :-----------------: | :-------: | :-------: | :-------- || Bubble sort | n | n 2 | n 2 | 1 | Yes | || Insertion sort | n | n 2 | n 2 | 1 | Yes | || Selection sort | n 2 | n 2 | n 2 | 1 | No | || Heap sort | n log(n) | n log(n) | n log(n) | 1 | No | || Merge sort | n log(n) | n log(n) | n log(n) | n | Yes | || Quick sort | n log(n) | n log(n) | n 2 | log(n) | No | Quicksort is usually done in-place with O(log(n)) stack space || Shell sort | n log(n) | depends on gap sequence | n (log(n)) 2 | 1 | No | || Counting sort | n + r | n + r | n + r | n + r | Yes | r - biggest number in array || Radix sort | n * k | n * k | n * k | n + k | Yes | k - length of longest key | Project Backers You may support this project via ❤️️ GitHub or ❤️️ Patreon . Folks who are backing this project ∑ = 0 ℹ️ A few more projects and articles about JavaScript and algorithms on trekhleb.dev To restore the repository download the bundle wget https://archive.org/download/github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57/trekhleb-javascript-algorithms_-_2022-06-26_06-51-57.bundle and run: git clone trekhleb-javascript-algorithms_-_2022-06-26_06-51-57.bundle Source: https://github.com/trekhleb/javascript-algorithms Uploader: trekhleb Upload date: 2022-06-26

“Github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57” Metadata:

  • Title: ➤  Github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57
  • Author:

“Github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 4.47 Mbs, the file-s for this book were downloaded 21 times, the file-s went public at Mon Jun 27 2022.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-trekhleb-javascript-algorithms_-_2022-06-26_06-51-57 at online marketplaces:


33Github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41

By

:bathtub: Clean Code concepts adapted for JavaScript clean-code-javascript Table of Contents Introduction Variables Functions Objects and Data Structures Classes SOLID Testing Concurrency Error Handling Formatting Comments Translation Introduction Software engineering principles, from Robert C. Martin's book Clean Code ,adapted for JavaScript. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in JavaScript. Not every principle herein has to be strictly followed, and even fewer will beuniversally agreed upon. These are guidelines and nothing more, but they areones codified over many years of collective experience by the authors of Clean Code . Our craft of software engineering is just a bit over 50 years old, and we arestill learning a lot. When software architecture is as old as architectureitself, maybe then we will have harder rules to follow. For now, let theseguidelines serve as a touchstone by which to assess the quality of theJavaScript code that you and your team produce. One more thing: knowing these won't immediately make you a better softwaredeveloper, and working with them for many years doesn't mean you won't makemistakes. Every piece of code starts as a first draft, like wet clay gettingshaped into its final form. Finally, we chisel away the imperfections whenwe review it with our peers. Don't beat yourself up for first drafts that needimprovement. Beat up the code instead! Variables Use meaningful and pronounceable variable names Bad: javascriptconst yyyymmdstr = moment().format("YYYY/MM/DD"); Good: javascriptconst currentDate = moment().format("YYYY/MM/DD"); ⬆ back to top Use the same vocabulary for the same type of variable Bad: javascriptgetUserInfo();getClientData();getCustomerRecord(); Good: javascriptgetUser(); ⬆ back to top Use searchable names We will read more code than we will ever write. It's important that the code wedo write is readable and searchable. By not naming variables that end upbeing meaningful for understanding our program, we hurt our readers.Make your names searchable. Tools like buddy.js and ESLint can help identify unnamed constants. Bad: javascript// What the heck is 86400000 for?setTimeout(blastOff, 86400000); Good: ```javascript// Declare them as capitalized named constants.const MILLISECONDS PER DAY = 60 * 60 * 24 * 1000; //86400000; setTimeout(blastOff, MILLISECONDS PER DAY);``` ⬆ back to top Use explanatory variables Bad: javascriptconst address = "One Infinite Loop, Cupertino 95014";const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;saveCityZipCode( address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]); Good: javascriptconst address = "One Infinite Loop, Cupertino 95014";const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];saveCityZipCode(city, zipCode); ⬆ back to top Avoid Mental Mapping Explicit is better than implicit. Bad: javascriptconst locations = ["Austin", "New York", "San Francisco"];locations.forEach(l => { doStuff(); doSomeOtherStuff(); // ... // ... // ... // Wait, what is `l` for again? dispatch(l);}); Good: javascriptconst locations = ["Austin", "New York", "San Francisco"];locations.forEach(location => { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch(location);}); ⬆ back to top Don't add unneeded context If your class/object name tells you something, don't repeat that in yourvariable name. Bad: ```javascriptconst Car = { carMake: "Honda", carModel: "Accord", carColor: "Blue"}; function paintCar(car, color) { car.carColor = color;}``` Good: ```javascriptconst Car = { make: "Honda", model: "Accord", color: "Blue"}; function paintCar(car, color) { car.color = color;}``` ⬆ back to top Use default parameters instead of short circuiting or conditionals Default parameters are often cleaner than short circuiting. Be aware that if youuse them, your function will only provide default values for undefined arguments. Other "falsy" values such as '' , "" , false , null , 0 , and NaN , will not be replaced by a default value. Bad: javascriptfunction createMicrobrewery(name) { const breweryName = name || "Hipster Brew Co."; // ...} Good: javascriptfunction createMicrobrewery(name = "Hipster Brew Co.") { // ...} ⬆ back to top Functions Function arguments (2 or fewer ideally) Limiting the amount of function parameters is incredibly important because itmakes testing your function easier. Having more than three leads to acombinatorial explosion where you have to test tons of different cases witheach separate argument. One or two arguments is the ideal case, and three should be avoided if possible.Anything more than that should be consolidated. Usually, if you havemore than two arguments then your function is trying to do too much. In caseswhere it's not, most of the time a higher-level object will suffice as anargument. Since JavaScript allows you to make objects on the fly, without a lot of classboilerplate, you can use an object if you are finding yourself needing alot of arguments. To make it obvious what properties the function expects, you can use the ES2015/ES6destructuring syntax. This has a few advantages: When someone looks at the function signature, it's immediately clear whatproperties are being used. It can be used to simulate named parameters. Destructuring also clones the specified primitive values of the argumentobject passed into the function. This can help prevent side effects. Note:objects and arrays that are destructured from the argument object are NOTcloned. Linters can warn you about unused properties, which would be impossiblewithout destructuring. Bad: ```javascriptfunction createMenu(title, body, buttonText, cancellable) { // ...} createMenu("Foo", "Bar", "Baz", true); ``` Good: ```javascriptfunction createMenu({ title, body, buttonText, cancellable }) { // ...} createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true});``` ⬆ back to top Functions should do one thing This is by far the most important rule in software engineering. When functionsdo more than one thing, they are harder to compose, test, and reason about.When you can isolate a function to just one action, it can be refactoredeasily and your code will read much cleaner. If you take nothing else away fromthis guide other than this, you'll be ahead of many developers. Bad: javascriptfunction emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } });} Good: ```javascriptfunction emailActiveClients(clients) { clients.filter(isActiveClient).forEach(email);} function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive();}``` ⬆ back to top Function names should say what they do Bad: ```javascriptfunction addToDate(date, month) { // ...} const date = new Date(); // It's hard to tell from the function name what is addedaddToDate(date, 1);``` Good: ```javascriptfunction addMonthToDate(month, date) { // ...} const date = new Date();addMonthToDate(1, date);``` ⬆ back to top Functions should only be one level of abstraction When you have more than one level of abstraction your function is usuallydoing too much. Splitting up functions leads to reusability and easiertesting. Bad: ```javascriptfunction parseBetterJSAlternative(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { // ... }); }); const ast = []; tokens.forEach(token => { // lex... }); ast.forEach(node => { // parse... });}``` Good: ```javascriptfunction parseBetterJSAlternative(code) { const tokens = tokenize(code); const syntaxTree = parse(tokens); syntaxTree.forEach(node => { // parse... });} function tokenize(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { tokens.push(/* ... */); }); }); return tokens;} function parse(tokens) { const syntaxTree = []; tokens.forEach(token => { syntaxTree.push(/* ... */); }); return syntaxTree;}``` ⬆ back to top Remove duplicate code Do your absolute best to avoid duplicate code. Duplicate code is bad because itmeans that there's more than one place to alter something if you need to changesome logic. Imagine if you run a restaurant and you keep track of your inventory: all yourtomatoes, onions, garlic, spices, etc. If you have multiple lists thatyou keep this on, then all have to be updated when you serve a dish withtomatoes in them. If you only have one list, there's only one place to update! Oftentimes you have duplicate code because you have two or more slightlydifferent things, that share a lot in common, but their differences force youto have two or more separate functions that do much of the same things. Removingduplicate code means creating an abstraction that can handle this set ofdifferent things with just one function/module/class. Getting the abstraction right is critical, that's why you should follow theSOLID principles laid out in the Classes section. Bad abstractions can beworse than duplicate code, so be careful! Having said this, if you can makea good abstraction, do it! Don't repeat yourself, otherwise you'll find yourselfupdating multiple places anytime you want to change one thing. Bad: ```javascriptfunction showDeveloperList(developers) { developers.forEach(developer => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); const data = { expectedSalary, experience, githubLink }; render(data); });} function showManagerList(managers) { managers.forEach(manager => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); const data = { expectedSalary, experience, portfolio }; render(data); });}``` Good: ```javascriptfunction showEmployeeList(employees) { employees.forEach(employee => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); const data = { expectedSalary, experience};switch (employee.type) { case "manager": data.portfolio = employee.getMBAProjects(); break; case "developer": data.githubLink = employee.getGithubLink(); break;}render(data); });}``` ⬆ back to top Set default objects with Object.assign Bad: ```javascriptconst menuConfig = { title: null, body: "Bar", buttonText: null, cancellable: true}; function createMenu(config) { config.title = config.title || "Foo"; config.body = config.body || "Bar"; config.buttonText = config.buttonText || "Baz"; config.cancellable = config.cancellable !== undefined ? config.cancellable : true;} createMenu(menuConfig);``` Good: ```javascriptconst menuConfig = { title: "Order", // User did not include 'body' key buttonText: "Send", cancellable: true}; function createMenu(config) { let finalConfig = Object.assign( { title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }, config ); return finalConfig // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ...} createMenu(menuConfig);``` ⬆ back to top Don't use flags as function parameters Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean. Bad: javascriptfunction createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); }} Good: ```javascriptfunction createFile(name) { fs.create(name);} function createTempFile(name) { createFile( ./temp/${name} );}``` ⬆ back to top Avoid Side Effects (part 1) A function produces a side effect if it does anything other than take a value inand return another value or values. A side effect could be writing to a file,modifying some global variable, or accidentally wiring all your money to astranger. Now, you do need to have side effects in a program on occasion. Like the previousexample, you might need to write to a file. What you want to do is tocentralize where you are doing this. Don't have several functions and classesthat write to a particular file. Have one service that does it. One and only one. The main point is to avoid common pitfalls like sharing state between objectswithout any structure, using mutable data types that can be written to by anything,and not centralizing where your side effects occur. If you can do this, you willbe happier than the vast majority of other programmers. Bad: ```javascript// Global variable referenced by following function.// If we had another function that used this name, now it'd be an array and it could break it.let name = "Ryan McDermott"; function splitIntoFirstAndLastName() { name = name.split(" ");} splitIntoFirstAndLastName(); console.log(name); // ['Ryan', 'McDermott'];``` Good: ```javascriptfunction splitIntoFirstAndLastName(name) { return name.split(" ");} const name = "Ryan McDermott";const newName = splitIntoFirstAndLastName(name); console.log(name); // 'Ryan McDermott';console.log(newName); // ['Ryan', 'McDermott'];``` ⬆ back to top Avoid Side Effects (part 2) In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere. Suppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same cart array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation: The user clicks the "Purchase" button which calls a purchase function thatspawns a network request and sends the cart array to the server. Becauseof a bad network connection, the purchase function has to keep retrying therequest. Now, what if in the meantime the user accidentally clicks an "Add to Cart"button on an item they don't actually want before the network request begins?If that happens and the network request begins, then that purchase functionwill send the accidentally added item because the cart array was modified. A great solution would be for the addItemToCart function to always clone the cart , edit it, and return the clone. This would ensure that functions that are stillusing the old shopping cart wouldn't be affected by the changes. Two caveats to mention to this approach: There might be cases where you actually want to modify the input object,but when you adopt this programming practice you will find that those casesare pretty rare. Most things can be refactored to have no side effects! Cloning big objects can be very expensive in terms of performance. Luckily,this isn't a big issue in practice because there are great libraries that allowthis kind of programming approach to be fast and not as memory intensive asit would be for you to manually clone objects and arrays. Bad: javascriptconst addItemToCart = (cart, item) => { cart.push({ item, date: Date.now() });}; Good: javascriptconst addItemToCart = (cart, item) => { return [...cart, { item, date: Date.now() }];}; ⬆ back to top Don't write to global functions Polluting globals is a bad practice in JavaScript because you could clash with anotherlibrary and the user of your API would be none-the-wiser until they get anexception in production. Let's think about an example: what if you wanted toextend JavaScript's native Array method to have a diff method that couldshow the difference between two arrays? You could write your new functionto the Array.prototype , but it could clash with another library that triedto do the same thing. What if that other library was just using diff to findthe difference between the first and last elements of an array? This is why itwould be much better to just use ES2015/ES6 classes and simply extend the Array global. Bad: javascriptArray.prototype.diff = function diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem));}; Good: javascriptclass SuperArray extends Array { diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem)); }} ⬆ back to top Favor functional programming over imperative programming JavaScript isn't a functional language in the way that Haskell is, but it hasa functional flavor to it. Functional languages can be cleaner and easier to test.Favor this style of programming when you can. Bad: ```javascriptconst programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 }]; let totalOutput = 0; for (let i = 0; i < programmerOutput.length; i++) { totalOutput += programmerOutput[i].linesOfCode;}``` Good: ```javascriptconst programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 }]; const totalOutput = programmerOutput.reduce( (totalLines, output) => totalLines + output.linesOfCode, 0);``` ⬆ back to top Encapsulate conditionals Bad: javascriptif (fsm.state === "fetching" && isEmpty(listNode)) { // ...} Good: ```javascriptfunction shouldShowSpinner(fsm, listNode) { return fsm.state === "fetching" && isEmpty(listNode);} if (shouldShowSpinner(fsmInstance, listNodeInstance)) { // ...}``` ⬆ back to top Avoid negative conditionals Bad: ```javascriptfunction isDOMNodeNotPresent(node) { // ...} if (!isDOMNodeNotPresent(node)) { // ...}``` Good: ```javascriptfunction isDOMNodePresent(node) { // ...} if (isDOMNodePresent(node)) { // ...}``` ⬆ back to top Avoid conditionals This seems like an impossible task. Upon first hearing this, most people say,"how am I supposed to do anything without an if statement?" The answer is thatyou can use polymorphism to achieve the same task in many cases. The secondquestion is usually, "well that's great but why would I want to do that?" Theanswer is a previous clean code concept we learned: a function should only doone thing. When you have classes and functions that have if statements, youare telling your user that your function does more than one thing. Remember,just do one thing. Bad: javascriptclass Airplane { // ... getCruisingAltitude() { switch (this.type) { case "777": return this.getMaxAltitude() - this.getPassengerCount(); case "Air Force One": return this.getMaxAltitude(); case "Cessna": return this.getMaxAltitude() - this.getFuelExpenditure(); } }} Good: ```javascriptclass Airplane { // ...} class Boeing777 extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getPassengerCount(); }} class AirForceOne extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude(); }} class Cessna extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getFuelExpenditure(); }}``` ⬆ back to top Avoid type-checking (part 1) JavaScript is untyped, which means your functions can take any type of argument.Sometimes you are bitten by this freedom and it becomes tempting to dotype-checking in your functions. There are many ways to avoid having to do this.The first thing to consider is consistent APIs. Bad: javascriptfunction travelToTexas(vehicle) { if (vehicle instanceof Bicycle) { vehicle.pedal(this.currentLocation, new Location("texas")); } else if (vehicle instanceof Car) { vehicle.drive(this.currentLocation, new Location("texas")); }} Good: javascriptfunction travelToTexas(vehicle) { vehicle.move(this.currentLocation, new Location("texas"));} ⬆ back to top Avoid type-checking (part 2) If you are working with basic primitive values like strings and integers,and you can't use polymorphism but you still feel the need to type-check,you should consider using TypeScript. It is an excellent alternative to normalJavaScript, as it provides you with static typing on top of standard JavaScriptsyntax. The problem with manually type-checking normal JavaScript is thatdoing it well requires so much extra verbiage that the faux "type-safety" you getdoesn't make up for the lost readability. Keep your JavaScript clean, writegood tests, and have good code reviews. Otherwise, do all of that but withTypeScript (which, like I said, is a great alternative!). Bad: ```javascriptfunction combine(val1, val2) { if ( (typeof val1 === "number" && typeof val2 === "number") || (typeof val1 === "string" && typeof val2 === "string") ) { return val1 + val2; } throw new Error("Must be of type String or Number");}``` Good: javascriptfunction combine(val1, val2) { return val1 + val2;} ⬆ back to top Don't over-optimize Modern browsers do a lot of optimization under-the-hood at runtime. A lot oftimes, if you are optimizing then you are just wasting your time. There are goodresources for seeing where optimization is lacking. Target those in the meantime, untilthey are fixed if they can be. Bad: javascript// On old browsers, each iteration with uncached `list.length` would be costly// because of `list.length` recomputation. In modern browsers, this is optimized.for (let i = 0, len = list.length; i < len; i++) { // ...} Good: javascriptfor (let i = 0; i < list.length; i++) { // ...} ⬆ back to top Remove dead code Dead code is just as bad as duplicate code. There's no reason to keep it inyour codebase. If it's not being called, get rid of it! It will still be safein your version history if you still need it. Bad: ```javascriptfunction oldRequestModule(url) { // ...} function newRequestModule(url) { // ...} const req = newRequestModule;inventoryTracker("apples", req, "www.inventory-awesome.io");``` Good: ```javascriptfunction newRequestModule(url) { // ...} const req = newRequestModule;inventoryTracker("apples", req, "www.inventory-awesome.io");``` ⬆ back to top Objects and Data Structures Use getters and setters Using getters and setters to access data on objects could be better than simplylooking for a property on an object. "Why?" you might ask. Well, here's anunorganized list of reasons why: When you want to do more beyond getting an object property, you don't haveto look up and change every accessor in your codebase. Makes adding validation simple when doing a set . Encapsulates the internal representation. Easy to add logging and error handling when getting and setting. You can lazy load your object's properties, let's say getting it from aserver. Bad: ```javascriptfunction makeBankAccount() { // ... return { balance: 0 // ... };} const account = makeBankAccount();account.balance = 100;``` Good: ```javascriptfunction makeBankAccount() { // this one is private let balance = 0; // a "getter", made public via the returned object below function getBalance() { return balance; } // a "setter", made public via the returned object below function setBalance(amount) { // ... validate before updating the balance balance = amount; } return { // ... getBalance, setBalance };} const account = makeBankAccount();account.setBalance(100);``` ⬆ back to top Make objects have private members This can be accomplished through closures (for ES5 and below). Bad: ```javascriptconst Employee = function(name) { this.name = name;}; Employee.prototype.getName = function getName() { return this.name;}; const employee = new Employee("John Doe");console.log( Employee name: ${employee.getName()} ); // Employee name: John Doedelete employee.name;console.log( Employee name: ${employee.getName()} ); // Employee name: undefined``` Good: ```javascriptfunction makeEmployee(name) { return { getName() { return name; } };} const employee = makeEmployee("John Doe");console.log( Employee name: ${employee.getName()} ); // Employee name: John Doedelete employee.name;console.log( Employee name: ${employee.getName()} ); // Employee name: John Doe``` ⬆ back to top Classes Prefer ES2015/ES6 classes over ES5 plain functions It's very difficult to get readable class inheritance, construction, and methoddefinitions for classical ES5 classes. If you need inheritance (and be awarethat you might not), then prefer ES2015/ES6 classes. However, prefer small functions overclasses until you find yourself needing larger and more complex objects. Bad: `` javascriptconst Animal = function(age) { if (!(this instanceof Animal)) { throw new Error("Instantiate Animal with new`"); } this.age = age;}; Animal.prototype.move = function move() {}; const Mammal = function(age, furColor) { if (!(this instanceof Mammal)) { throw new Error("Instantiate Mammal with new "); } Animal.call(this, age); this.furColor = furColor;}; Mammal.prototype = Object.create(Animal.prototype);Mammal.prototype.constructor = Mammal;Mammal.prototype.liveBirth = function liveBirth() {}; const Human = function(age, furColor, languageSpoken) { if (!(this instanceof Human)) { throw new Error("Instantiate Human with new "); } Mammal.call(this, age, furColor); this.languageSpoken = languageSpoken;}; Human.prototype = Object.create(Mammal.prototype);Human.prototype.constructor = Human;Human.prototype.speak = function speak() {};``` Good: ```javascriptclass Animal { constructor(age) { this.age = age; } move() { /* ... */ }} class Mammal extends Animal { constructor(age, furColor) { super(age); this.furColor = furColor; } liveBirth() { /* ... */ }} class Human extends Mammal { constructor(age, furColor, languageSpoken) { super(age, furColor); this.languageSpoken = languageSpoken; } speak() { /* ... */ }}``` ⬆ back to top Use method chaining This pattern is very useful in JavaScript and you see it in many libraries suchas jQuery and Lodash. It allows your code to be expressive, and less verbose.For that reason, I say, use method chaining and take a look at how clean your codewill be. In your class functions, simply return this at the end of every function,and you can chain further class methods onto it. Bad: ```javascriptclass Car { constructor(make, model, color) { this.make = make; this.model = model; this.color = color; } setMake(make) { this.make = make; } setModel(model) { this.model = model; } setColor(color) { this.color = color; } save() { console.log(this.make, this.model, this.color); }} const car = new Car("Ford", "F-150", "red");car.setColor("pink");car.save();``` Good: ```javascriptclass Car { constructor(make, model, color) { this.make = make; this.model = model; this.color = color; } setMake(make) { this.make = make; // NOTE: Returning this for chaining return this; } setModel(model) { this.model = model; // NOTE: Returning this for chaining return this; } setColor(color) { this.color = color; // NOTE: Returning this for chaining return this; } save() { console.log(this.make, this.model, this.color); // NOTE: Returning this for chaining return this; }} const car = new Car("Ford", "F-150", "red").setColor("pink").save();``` ⬆ back to top Prefer composition over inheritance As stated famously in Design Patterns by the Gang of Four,you should prefer composition over inheritance where you can. There are lots ofgood reasons to use inheritance and lots of good reasons to use composition.The main point for this maxim is that if your mind instinctively goes forinheritance, try to think if composition could model your problem better. In somecases it can. You might be wondering then, "when should I use inheritance?" Itdepends on your problem at hand, but this is a decent list of when inheritancemakes more sense than composition: Your inheritance represents an "is-a" relationship and not a "has-a"relationship (Human->Animal vs. User->UserDetails). You can reuse code from the base classes (Humans can move like all animals). You want to make global changes to derived classes by changing a base class.(Change the caloric expenditure of all animals when they move). Bad: ```javascriptclass Employee { constructor(name, email) { this.name = name; this.email = email; } // ...} // Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employeeclass EmployeeTaxData extends Employee { constructor(ssn, salary) { super(); this.ssn = ssn; this.salary = salary; } // ...}``` Good: ```javascriptclass EmployeeTaxData { constructor(ssn, salary) { this.ssn = ssn; this.salary = salary; } // ...} class Employee { constructor(name, email) { this.name = name; this.email = email; } setTaxData(ssn, salary) { this.taxData = new EmployeeTaxData(ssn, salary); } // ...}``` ⬆ back to top SOLID Single Responsibility Principle (SRP) As stated in Clean Code, "There should never be more than one reason for a classto change". It's tempting to jam-pack a class with a lot of functionality, likewhen you can only take one suitcase on your flight. The issue with this isthat your class won't be conceptually cohesive and it will give it many reasonsto change. Minimizing the amount of times you need to change a class is important.It's important because if too much functionality is in one class and you modifya piece of it, it can be difficult to understand how that will affect otherdependent modules in your codebase. Bad: ```javascriptclass UserSettings { constructor(user) { this.user = user; } changeSettings(settings) { if (this.verifyCredentials()) { // ... } } verifyCredentials() { // ... }}``` Good: ```javascriptclass UserAuth { constructor(user) { this.user = user; } verifyCredentials() { // ... }} class UserSettings { constructor(user) { this.user = user; this.auth = new UserAuth(user); } changeSettings(settings) { if (this.auth.verifyCredentials()) { // ... } }}``` ⬆ back to top Open/Closed Principle (OCP) As stated by Bertrand Meyer, "software entities (classes, modules, functions,etc.) should be open for extension, but closed for modification." What does thatmean though? This principle basically states that you should allow users toadd new functionalities without changing existing code. Bad: ```javascriptclass AjaxAdapter extends Adapter { constructor() { super(); this.name = "ajaxAdapter"; }} class NodeAdapter extends Adapter { constructor() { super(); this.name = "nodeAdapter"; }} class HttpRequester { constructor(adapter) { this.adapter = adapter; } fetch(url) { if (this.adapter.name === "ajaxAdapter") { return makeAjaxCall(url).then(response => { // transform response and return }); } else if (this.adapter.name === "nodeAdapter") { return makeHttpCall(url).then(response => { // transform response and return }); } }} function makeAjaxCall(url) { // request and return promise} function makeHttpCall(url) { // request and return promise}``` Good: ```javascriptclass AjaxAdapter extends Adapter { constructor() { super(); this.name = "ajaxAdapter"; } request(url) { // request and return promise }} class NodeAdapter extends Adapter { constructor() { super(); this.name = "nodeAdapter"; } request(url) { // request and return promise }} class HttpRequester { constructor(adapter) { this.adapter = adapter; } fetch(url) { return this.adapter.request(url).then(response => { // transform response and return }); }}``` ⬆ back to top Liskov Substitution Principle (LSP) This is a scary term for a very simple concept. It's formally defined as "If Sis a subtype of T, then objects of type T may be replaced with objects of type S(i.e., objects of type S may substitute objects of type T) without altering anyof the desirable properties of that program (correctness, task performed,etc.)." That's an even scarier definition. The best explanation for this is if you have a parent class and a child class,then the base class and child class can be used interchangeably without gettingincorrect results. This might still be confusing, so let's take a look at theclassic Square-Rectangle example. Mathematically, a square is a rectangle, butif you model it using the "is-a" relationship via inheritance, you quicklyget into trouble. Bad: ```javascriptclass Rectangle { constructor() { this.width = 0; this.height = 0; } setColor(color) { // ... } render(area) { // ... } setWidth(width) { this.width = width; } setHeight(height) { this.height = height; } getArea() { return this.width * this.height; }} class Square extends Rectangle { setWidth(width) { this.width = width; this.height = width; } setHeight(height) { this.width = height; this.height = height; }} function renderLargeRectangles(rectangles) { rectangles.forEach(rectangle => { rectangle.setWidth(4); rectangle.setHeight(5); const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. rectangle.render(area); });} const rectangles = [new Rectangle(), new Rectangle(), new Square()];renderLargeRectangles(rectangles);``` Good: ```javascriptclass Shape { setColor(color) { // ... } render(area) { // ... }} class Rectangle extends Shape { constructor(width, height) { super(); this.width = width; this.height = height; } getArea() { return this.width * this.height; }} class Square extends Shape { constructor(length) { super(); this.length = length; } getArea() { return this.length * this.length; }} function renderLargeShapes(shapes) { shapes.forEach(shape => { const area = shape.getArea(); shape.render(area); });} const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];renderLargeShapes(shapes);``` ⬆ back to top Interface Segregation Principle (ISP) JavaScript doesn't have interfaces so this principle doesn't apply as strictlyas others. However, it's important and relevant even with JavaScript's lack oftype system. ISP states that "Clients should not be forced to depend upon interfaces thatthey do not use." Interfaces are implicit contracts in JavaScript because ofduck typing. A good example to look at that demonstrates this principle in JavaScript is forclasses that require large settings objects. Not requiring clients to setuphuge amounts of options is beneficial, because most of the time they won't needall of the settings. Making them optional helps prevent having a"fat interface". Bad: ```javascriptclass DOMTraverser { constructor(settings) { this.settings = settings; this.setup(); } setup() { this.rootNode = this.settings.rootNode; this.settings.animationModule.setup(); } traverse() { // ... }} const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), animationModule() {} // Most of the time, we won't need to animate when traversing. // ...});``` Good: ```javascriptclass DOMTraverser { constructor(settings) { this.settings = settings; this.options = settings.options; this.setup(); } setup() { this.rootNode = this.settings.rootNode; this.setupOptions(); } setupOptions() { if (this.options.animationModule) { // ... } } traverse() { // ... }} const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), options: { animationModule() {} }});``` ⬆ back to top Dependency Inversion Principle (DIP) This principle states two essential things: High-level modules should not depend on low-level modules. Both shoulddepend on abstractions. Abstractions should not depend upon details. Details should depend onabstractions. This can be hard to understand at first, but if you've worked with AngularJS,you've seen an implementation of this principle in the form of DependencyInjection (DI). While they are not identical concepts, DIP keeps high-levelmodules from knowing the details of its low-level modules and setting them up.It can accomplish this through DI. A huge benefit of this is that it reducesthe coupling between modules. Coupling is a very bad development pattern becauseit makes your code hard to refactor. As stated previously, JavaScript doesn't have interfaces so the abstractionsthat are depended upon are implicit contracts. That is to say, the methodsand properties that an object/class exposes to another object/class. In theexample below, the implicit contract is that any Request module for an InventoryTracker will have a requestItems method. Bad: ```javascriptclass InventoryRequester { constructor() { this.REQ_METHODS = ["HTTP"]; } requestItem(item) { // ... }} class InventoryTracker { constructor(items) { this.items = items; // BAD: We have created a dependency on a specific request implementation.// We should just have requestItems depend on a request method: `request`this.requester = new InventoryRequester(); } requestItems() { this.items.forEach(item => { this.requester.requestItem(item); }); }} const inventoryTracker = new InventoryTracker(["apples", "bananas"]);inventoryTracker.requestItems();``` Good: ```javascriptclass InventoryTracker { constructor(items, requester) { this.items = items; this.requester = requester; } requestItems() { this.items.forEach(item => { this.requester.requestItem(item); }); }} class InventoryRequesterV1 { constructor() { this.REQ_METHODS = ["HTTP"]; } requestItem(item) { // ... }} class InventoryRequesterV2 { constructor() { this.REQ_METHODS = ["WS"]; } requestItem(item) { // ... }} // By constructing our dependencies externally and injecting them, we can easily// substitute our request module for a fancy new one that uses WebSockets.const inventoryTracker = new InventoryTracker( ["apples", "bananas"], new InventoryRequesterV2());inventoryTracker.requestItems();``` ⬆ back to top Testing Testing is more important than shipping. If you have no tests or aninadequate amount, then every time you ship code you won't be sure that youdidn't break anything. Deciding on what constitutes an adequate amount is upto your team, but having 100% coverage (all statements and branches) is howyou achieve very high confidence and developer peace of mind. This means thatin addition to having a great testing framework, you also need to use a good coverage tool . There's no excuse to not write tests. There are plenty of good JS test frameworks , so find one that your team prefers.When you find one that works for your team, then aim to always write testsfor every new feature/module you introduce. If your preferred method isTest Driven Development (TDD), that is great, but the main point is to justmake sure you are reaching your coverage goals before launching any feature,or refactoring an existing one. Single concept per test Bad: ```javascriptimport assert from "assert"; describe("MomentJS", () => { it("handles date boundaries", () => { let date; date = new MomentJS("1/1/2015");date.addDays(30);assert.equal("1/31/2015", date);date = new MomentJS("2/1/2016");date.addDays(28);assert.equal("02/29/2016", date);date = new MomentJS("2/1/2015");date.addDays(28);assert.equal("03/01/2015", date); });});``` Good: ```javascriptimport assert from "assert"; describe("MomentJS", () => { it("handles 30-day months", () => { const date = new MomentJS("1/1/2015"); date.addDays(30); assert.equal("1/31/2015", date); }); it("handles leap year", () => { const date = new MomentJS("2/1/2016"); date.addDays(28); assert.equal("02/29/2016", date); }); it("handles non-leap year", () => { const date = new MomentJS("2/1/2015"); date.addDays(28); assert.equal("03/01/2015", date); });});``` ⬆ back to top Concurrency Use Promises, not callbacks Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,Promises are a built-in global type. Use them! Bad: ```javascriptimport { get } from "request";import { writeFile } from "fs"; get( "https://en.wikipedia.org/wiki/Robert Cecil Martin", (requestErr, response, body) => { if (requestErr) { console.error(requestErr); } else { writeFile("article.html", body, writeErr => { if (writeErr) { console.error(writeErr); } else { console.log("File written"); } }); } });``` Good: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert Cecil Martin") .then(body => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) .catch(err => { console.error(err); });``` ⬆ back to top Async/Await are even cleaner than Promises Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and awaitwhich offer an even cleaner solution. All you need is a function that is prefixedin an async keyword, and then you can write your logic imperatively withouta then chain of functions. Use this if you can take advantage of ES2017/ES8 featurestoday! Bad: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert Cecil Martin") .then(body => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) .catch(err => { console.error(err); });``` Good: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; async function getCleanCodeArticle() { try { const body = await get( "https://en.wikipedia.org/wiki/Robert Cecil Martin" ); await writeFile("article.html", body); console.log("File written"); } catch (err) { console.error(err); }} getCleanCodeArticle()``` ⬆ back to top Error Handling Thrown errors are a good thing! They mean the runtime has successfullyidentified when something in your program has gone wrong and it's lettingyou know by stopping function execution on the current stack, killing theprocess (in Node), and notifying you in the console with a stack trace. Don't ignore caught errors Doing nothing with a caught error doesn't give you the ability to ever fixor react to said error. Logging the error to the console ( console.log )isn't much better as often times it can get lost in a sea of things printedto the console. If you wrap any bit of code in a try/catch it means youthink an error may occur there and therefore you should have a plan,or create a code path, for when it occurs. Bad: javascripttry { functionThatMightThrow();} catch (error) { console.log(error);} Good: javascripttry { functionThatMightThrow();} catch (error) { // One option (more noisy than console.log): console.error(error); // Another option: notifyUserOfError(error); // Another option: reportErrorToService(error); // OR do all three!} Don't ignore rejected promises For the same reason you shouldn't ignore caught errorsfrom try/catch . Bad: javascriptgetdata() .then(data => { functionThatMightThrow(data); }) .catch(error => { console.log(error); }); Good: javascriptgetdata() .then(data => { functionThatMightThrow(data); }) .catch(error => { // One option (more noisy than console.log): console.error(error); // Another option: notifyUserOfError(error); // Another option: reportErrorToService(error); // OR do all three! }); ⬆ back to top Formatting Formatting is subjective. Like many rules herein, there is no hard and fastrule that you must follow. The main point is DO NOT ARGUE over formatting.There are tons of tools to automate this.Use one! It's a waste of time and money for engineers to argue over formatting. For things that don't fall under the purview of automatic formatting(indentation, tabs vs. spaces, double vs. single quotes, etc.) look herefor some guidance. Use consistent capitalization JavaScript is untyped, so capitalization tells you a lot about your variables,functions, etc. These rules are subjective, so your team can choose whateverthey want. The point is, no matter what you all choose, just be consistent. Bad: ```javascriptconst DAYS IN WEEK = 7;const daysInMonth = 30; const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"];const Artists = ["ACDC", "Led Zeppelin", "The Beatles"]; function eraseDatabase() {}function restore_database() {} class animal {}class Alpaca {}``` Good: ```javascriptconst DAYS IN WEEK = 7;const DAYS IN MONTH = 30; const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"];const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"]; function eraseDatabase() {}function restoreDatabase() {} class Animal {}class Alpaca {}``` ⬆ back to top Function callers and callees should be close If a function calls another, keep those functions vertically close in the sourcefile. Ideally, keep the caller right above the callee. We tend to read code fromtop-to-bottom, like a newspaper. Because of this, make your code read that way. Bad: ```javascriptclass PerformanceReview { constructor(employee) { this.employee = employee; } lookupPeers() { return db.lookup(this.employee, "peers"); } lookupManager() { return db.lookup(this.employee, "manager"); } getPeerReviews() { const peers = this.lookupPeers(); // ... } perfReview() { this.getPeerReviews(); this.getManagerReview(); this.getSelfReview(); } getManagerReview() { const manager = this.lookupManager(); } getSelfReview() { // ... }} const review = new PerformanceReview(employee);review.perfReview();``` Good: ```javascriptclass PerformanceReview { constructor(employee) { this.employee = employee; } perfReview() { this.getPeerReviews(); this.getManagerReview(); this.getSelfReview(); } getPeerReviews() { const peers = this.lookupPeers(); // ... } lookupPeers() { return db.lookup(this.employee, "peers"); } getManagerReview() { const manager = this.lookupManager(); } lookupManager() { return db.lookup(this.employee, "manager"); } getSelfReview() { // ... }} const review = new PerformanceReview(employee);review.perfReview();``` ⬆ back to top Comments Only comment things that have business logic complexity. Comments are an apology, not a requirement. Good code mostly documents itself. Bad: ```javascriptfunction hashIt(data) { // The hash let hash = 0; // Length of string const length = data.length; // Loop through every character in data for (let i = 0; i < length; i++) { // Get character code. const char = data.charCodeAt(i); // Make the hash hash = (hash << 5) - hash + char; // Convert to 32-bit integer hash &= hash; }}``` Good: ```javascriptfunction hashIt(data) { let hash = 0; const length = data.length; for (let i = 0; i < length; i++) { const char = data.charCodeAt(i); hash = (hash << 5) - hash + char; // Convert to 32-bit integerhash &= hash; }}``` ⬆ back to top Don't leave commented out code in your codebase Version control exists for a reason. Leave old code in your history. Bad: javascriptdoStuff();// doOtherStuff();// doSomeMoreStuff();// doSoMuchStuff(); Good: javascriptdoStuff(); ⬆ back to top Don't have journal comments Remember, use version control! There's no need for dead code, commented code,and especially journal comments. Use git log to get history! Bad: javascript/** * 2016-12-20: Removed monads, didn't understand them (RM) * 2016-10-01: Improved using special monads (JP) * 2016-02-03: Removed type-checking (LI) * 2015-03-14: Added combine with type-checking (JR) */function combine(a, b) { return a + b;} Good: javascriptfunction combine(a, b) { return a + b;} ⬆ back to top Avoid positional markers They usually just add noise. Let the functions and variable names along with theproper indentation and formatting give the visual structure to your code. Bad: ```javascript////////////////////////////////////////////////////////////////////////////////// Scope Model Instantiation////////////////////////////////////////////////////////////////////////////////$scope.model = { menu: "foo", nav: "bar"}; ////////////////////////////////////////////////////////////////////////////////// Action setup////////////////////////////////////////////////////////////////////////////////const actions = function() { // ...};``` Good: ```javascript$scope.model = { menu: "foo", nav: "bar"}; const actions = function() { // ...};``` ⬆ back to top Translation This is also available in other languages: Armenian : hanumanum/clean-code-javascript/ Bangla(বাংলা) : InsomniacSabbir/clean-code-javascript/ Brazilian Portuguese : fesnt/clean-code-javascript Simplified Chinese : alivebao/clean-code-js beginor/clean-code-javascript Traditional Chinese : AllJointTW/clean-code-javascript French : eugene-augier/clean-code-javascript-fr German : marcbruederlin/clean-code-javascript Indonesia : andirkh/clean-code-javascript/ Italian : frappacchio/clean-code-javascript/ Japanese : mitsuruog/clean-code-javascript/ Korean : qkraudghgh/clean-code-javascript-ko Polish : greg-dev/clean-code-javascript-pl Russian : BoryaMogila/clean-code-javascript-ru/ maksugr/clean-code-javascript Spanish : tureey/clean-code-javascript Spanish : andersontr15/clean-code-javascript Serbian : doskovicmilos/clean-code-javascript/ Turkish : bsonmez/clean-code-javascript Ukrainian : mindfr1k/clean-code-javascript-ua Vietnamese : hienvd/clean-code-javascript/ Persian : hamettio/clean-code-javascript ⬆ back to top To restore the repository download the bundle wget https://archive.org/download/github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41/ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41.bundle and run: git clone ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41.bundle Source: https://github.com/ryanmcdermott/clean-code-javascript Uploader: ryanmcdermott Upload date: 2023-08-14

“Github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41” Metadata:

  • Title: ➤  Github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41
  • Author:

“Github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 0.85 Mbs, the file-s for this book were downloaded 25 times, the file-s went public at Thu Aug 31 2023.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41 at online marketplaces:


34Head First JavaScript

By

:bathtub: Clean Code concepts adapted for JavaScript clean-code-javascript Table of Contents Introduction Variables Functions Objects and Data Structures Classes SOLID Testing Concurrency Error Handling Formatting Comments Translation Introduction Software engineering principles, from Robert C. Martin's book Clean Code ,adapted for JavaScript. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in JavaScript. Not every principle herein has to be strictly followed, and even fewer will beuniversally agreed upon. These are guidelines and nothing more, but they areones codified over many years of collective experience by the authors of Clean Code . Our craft of software engineering is just a bit over 50 years old, and we arestill learning a lot. When software architecture is as old as architectureitself, maybe then we will have harder rules to follow. For now, let theseguidelines serve as a touchstone by which to assess the quality of theJavaScript code that you and your team produce. One more thing: knowing these won't immediately make you a better softwaredeveloper, and working with them for many years doesn't mean you won't makemistakes. Every piece of code starts as a first draft, like wet clay gettingshaped into its final form. Finally, we chisel away the imperfections whenwe review it with our peers. Don't beat yourself up for first drafts that needimprovement. Beat up the code instead! Variables Use meaningful and pronounceable variable names Bad: javascriptconst yyyymmdstr = moment().format("YYYY/MM/DD"); Good: javascriptconst currentDate = moment().format("YYYY/MM/DD"); ⬆ back to top Use the same vocabulary for the same type of variable Bad: javascriptgetUserInfo();getClientData();getCustomerRecord(); Good: javascriptgetUser(); ⬆ back to top Use searchable names We will read more code than we will ever write. It's important that the code wedo write is readable and searchable. By not naming variables that end upbeing meaningful for understanding our program, we hurt our readers.Make your names searchable. Tools like buddy.js and ESLint can help identify unnamed constants. Bad: javascript// What the heck is 86400000 for?setTimeout(blastOff, 86400000); Good: ```javascript// Declare them as capitalized named constants.const MILLISECONDS PER DAY = 60 * 60 * 24 * 1000; //86400000; setTimeout(blastOff, MILLISECONDS PER DAY);``` ⬆ back to top Use explanatory variables Bad: javascriptconst address = "One Infinite Loop, Cupertino 95014";const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;saveCityZipCode( address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]); Good: javascriptconst address = "One Infinite Loop, Cupertino 95014";const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];saveCityZipCode(city, zipCode); ⬆ back to top Avoid Mental Mapping Explicit is better than implicit. Bad: javascriptconst locations = ["Austin", "New York", "San Francisco"];locations.forEach(l => { doStuff(); doSomeOtherStuff(); // ... // ... // ... // Wait, what is `l` for again? dispatch(l);}); Good: javascriptconst locations = ["Austin", "New York", "San Francisco"];locations.forEach(location => { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch(location);}); ⬆ back to top Don't add unneeded context If your class/object name tells you something, don't repeat that in yourvariable name. Bad: ```javascriptconst Car = { carMake: "Honda", carModel: "Accord", carColor: "Blue"}; function paintCar(car, color) { car.carColor = color;}``` Good: ```javascriptconst Car = { make: "Honda", model: "Accord", color: "Blue"}; function paintCar(car, color) { car.color = color;}``` ⬆ back to top Use default parameters instead of short circuiting or conditionals Default parameters are often cleaner than short circuiting. Be aware that if youuse them, your function will only provide default values for undefined arguments. Other "falsy" values such as '' , "" , false , null , 0 , and NaN , will not be replaced by a default value. Bad: javascriptfunction createMicrobrewery(name) { const breweryName = name || "Hipster Brew Co."; // ...} Good: javascriptfunction createMicrobrewery(name = "Hipster Brew Co.") { // ...} ⬆ back to top Functions Function arguments (2 or fewer ideally) Limiting the amount of function parameters is incredibly important because itmakes testing your function easier. Having more than three leads to acombinatorial explosion where you have to test tons of different cases witheach separate argument. One or two arguments is the ideal case, and three should be avoided if possible.Anything more than that should be consolidated. Usually, if you havemore than two arguments then your function is trying to do too much. In caseswhere it's not, most of the time a higher-level object will suffice as anargument. Since JavaScript allows you to make objects on the fly, without a lot of classboilerplate, you can use an object if you are finding yourself needing alot of arguments. To make it obvious what properties the function expects, you can use the ES2015/ES6destructuring syntax. This has a few advantages: When someone looks at the function signature, it's immediately clear whatproperties are being used. It can be used to simulate named parameters. Destructuring also clones the specified primitive values of the argumentobject passed into the function. This can help prevent side effects. Note:objects and arrays that are destructured from the argument object are NOTcloned. Linters can warn you about unused properties, which would be impossiblewithout destructuring. Bad: ```javascriptfunction createMenu(title, body, buttonText, cancellable) { // ...} createMenu("Foo", "Bar", "Baz", true); ``` Good: ```javascriptfunction createMenu({ title, body, buttonText, cancellable }) { // ...} createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true});``` ⬆ back to top Functions should do one thing This is by far the most important rule in software engineering. When functionsdo more than one thing, they are harder to compose, test, and reason about.When you can isolate a function to just one action, it can be refactoredeasily and your code will read much cleaner. If you take nothing else away fromthis guide other than this, you'll be ahead of many developers. Bad: javascriptfunction emailClients(clients) { clients.forEach(client => { const clientRecord = database.lookup(client); if (clientRecord.isActive()) { email(client); } });} Good: ```javascriptfunction emailActiveClients(clients) { clients.filter(isActiveClient).forEach(email);} function isActiveClient(client) { const clientRecord = database.lookup(client); return clientRecord.isActive();}``` ⬆ back to top Function names should say what they do Bad: ```javascriptfunction addToDate(date, month) { // ...} const date = new Date(); // It's hard to tell from the function name what is addedaddToDate(date, 1);``` Good: ```javascriptfunction addMonthToDate(month, date) { // ...} const date = new Date();addMonthToDate(1, date);``` ⬆ back to top Functions should only be one level of abstraction When you have more than one level of abstraction your function is usuallydoing too much. Splitting up functions leads to reusability and easiertesting. Bad: ```javascriptfunction parseBetterJSAlternative(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { // ... }); }); const ast = []; tokens.forEach(token => { // lex... }); ast.forEach(node => { // parse... });}``` Good: ```javascriptfunction parseBetterJSAlternative(code) { const tokens = tokenize(code); const syntaxTree = parse(tokens); syntaxTree.forEach(node => { // parse... });} function tokenize(code) { const REGEXES = [ // ... ]; const statements = code.split(" "); const tokens = []; REGEXES.forEach(REGEX => { statements.forEach(statement => { tokens.push(/* ... */); }); }); return tokens;} function parse(tokens) { const syntaxTree = []; tokens.forEach(token => { syntaxTree.push(/* ... */); }); return syntaxTree;}``` ⬆ back to top Remove duplicate code Do your absolute best to avoid duplicate code. Duplicate code is bad because itmeans that there's more than one place to alter something if you need to changesome logic. Imagine if you run a restaurant and you keep track of your inventory: all yourtomatoes, onions, garlic, spices, etc. If you have multiple lists thatyou keep this on, then all have to be updated when you serve a dish withtomatoes in them. If you only have one list, there's only one place to update! Oftentimes you have duplicate code because you have two or more slightlydifferent things, that share a lot in common, but their differences force youto have two or more separate functions that do much of the same things. Removingduplicate code means creating an abstraction that can handle this set ofdifferent things with just one function/module/class. Getting the abstraction right is critical, that's why you should follow theSOLID principles laid out in the Classes section. Bad abstractions can beworse than duplicate code, so be careful! Having said this, if you can makea good abstraction, do it! Don't repeat yourself, otherwise you'll find yourselfupdating multiple places anytime you want to change one thing. Bad: ```javascriptfunction showDeveloperList(developers) { developers.forEach(developer => { const expectedSalary = developer.calculateExpectedSalary(); const experience = developer.getExperience(); const githubLink = developer.getGithubLink(); const data = { expectedSalary, experience, githubLink }; render(data); });} function showManagerList(managers) { managers.forEach(manager => { const expectedSalary = manager.calculateExpectedSalary(); const experience = manager.getExperience(); const portfolio = manager.getMBAProjects(); const data = { expectedSalary, experience, portfolio }; render(data); });}``` Good: ```javascriptfunction showEmployeeList(employees) { employees.forEach(employee => { const expectedSalary = employee.calculateExpectedSalary(); const experience = employee.getExperience(); const data = { expectedSalary, experience};switch (employee.type) { case "manager": data.portfolio = employee.getMBAProjects(); break; case "developer": data.githubLink = employee.getGithubLink(); break;}render(data); });}``` ⬆ back to top Set default objects with Object.assign Bad: ```javascriptconst menuConfig = { title: null, body: "Bar", buttonText: null, cancellable: true}; function createMenu(config) { config.title = config.title || "Foo"; config.body = config.body || "Bar"; config.buttonText = config.buttonText || "Baz"; config.cancellable = config.cancellable !== undefined ? config.cancellable : true;} createMenu(menuConfig);``` Good: ```javascriptconst menuConfig = { title: "Order", // User did not include 'body' key buttonText: "Send", cancellable: true}; function createMenu(config) { let finalConfig = Object.assign( { title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }, config ); return finalConfig // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} // ...} createMenu(menuConfig);``` ⬆ back to top Don't use flags as function parameters Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean. Bad: javascriptfunction createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); }} Good: ```javascriptfunction createFile(name) { fs.create(name);} function createTempFile(name) { createFile( ./temp/${name} );}``` ⬆ back to top Avoid Side Effects (part 1) A function produces a side effect if it does anything other than take a value inand return another value or values. A side effect could be writing to a file,modifying some global variable, or accidentally wiring all your money to astranger. Now, you do need to have side effects in a program on occasion. Like the previousexample, you might need to write to a file. What you want to do is tocentralize where you are doing this. Don't have several functions and classesthat write to a particular file. Have one service that does it. One and only one. The main point is to avoid common pitfalls like sharing state between objectswithout any structure, using mutable data types that can be written to by anything,and not centralizing where your side effects occur. If you can do this, you willbe happier than the vast majority of other programmers. Bad: ```javascript// Global variable referenced by following function.// If we had another function that used this name, now it'd be an array and it could break it.let name = "Ryan McDermott"; function splitIntoFirstAndLastName() { name = name.split(" ");} splitIntoFirstAndLastName(); console.log(name); // ['Ryan', 'McDermott'];``` Good: ```javascriptfunction splitIntoFirstAndLastName(name) { return name.split(" ");} const name = "Ryan McDermott";const newName = splitIntoFirstAndLastName(name); console.log(name); // 'Ryan McDermott';console.log(newName); // ['Ryan', 'McDermott'];``` ⬆ back to top Avoid Side Effects (part 2) In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere. Suppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same cart array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation: The user clicks the "Purchase" button which calls a purchase function thatspawns a network request and sends the cart array to the server. Becauseof a bad network connection, the purchase function has to keep retrying therequest. Now, what if in the meantime the user accidentally clicks an "Add to Cart"button on an item they don't actually want before the network request begins?If that happens and the network request begins, then that purchase functionwill send the accidentally added item because the cart array was modified. A great solution would be for the addItemToCart function to always clone the cart , edit it, and return the clone. This would ensure that functions that are stillusing the old shopping cart wouldn't be affected by the changes. Two caveats to mention to this approach: There might be cases where you actually want to modify the input object,but when you adopt this programming practice you will find that those casesare pretty rare. Most things can be refactored to have no side effects! Cloning big objects can be very expensive in terms of performance. Luckily,this isn't a big issue in practice because there are great libraries that allowthis kind of programming approach to be fast and not as memory intensive asit would be for you to manually clone objects and arrays. Bad: javascriptconst addItemToCart = (cart, item) => { cart.push({ item, date: Date.now() });}; Good: javascriptconst addItemToCart = (cart, item) => { return [...cart, { item, date: Date.now() }];}; ⬆ back to top Don't write to global functions Polluting globals is a bad practice in JavaScript because you could clash with anotherlibrary and the user of your API would be none-the-wiser until they get anexception in production. Let's think about an example: what if you wanted toextend JavaScript's native Array method to have a diff method that couldshow the difference between two arrays? You could write your new functionto the Array.prototype , but it could clash with another library that triedto do the same thing. What if that other library was just using diff to findthe difference between the first and last elements of an array? This is why itwould be much better to just use ES2015/ES6 classes and simply extend the Array global. Bad: javascriptArray.prototype.diff = function diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem));}; Good: javascriptclass SuperArray extends Array { diff(comparisonArray) { const hash = new Set(comparisonArray); return this.filter(elem => !hash.has(elem)); }} ⬆ back to top Favor functional programming over imperative programming JavaScript isn't a functional language in the way that Haskell is, but it hasa functional flavor to it. Functional languages can be cleaner and easier to test.Favor this style of programming when you can. Bad: ```javascriptconst programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 }]; let totalOutput = 0; for (let i = 0; i < programmerOutput.length; i++) { totalOutput += programmerOutput[i].linesOfCode;}``` Good: ```javascriptconst programmerOutput = [ { name: "Uncle Bobby", linesOfCode: 500 }, { name: "Suzie Q", linesOfCode: 1500 }, { name: "Jimmy Gosling", linesOfCode: 150 }, { name: "Gracie Hopper", linesOfCode: 1000 }]; const totalOutput = programmerOutput.reduce( (totalLines, output) => totalLines + output.linesOfCode, 0);``` ⬆ back to top Encapsulate conditionals Bad: javascriptif (fsm.state === "fetching" && isEmpty(listNode)) { // ...} Good: ```javascriptfunction shouldShowSpinner(fsm, listNode) { return fsm.state === "fetching" && isEmpty(listNode);} if (shouldShowSpinner(fsmInstance, listNodeInstance)) { // ...}``` ⬆ back to top Avoid negative conditionals Bad: ```javascriptfunction isDOMNodeNotPresent(node) { // ...} if (!isDOMNodeNotPresent(node)) { // ...}``` Good: ```javascriptfunction isDOMNodePresent(node) { // ...} if (isDOMNodePresent(node)) { // ...}``` ⬆ back to top Avoid conditionals This seems like an impossible task. Upon first hearing this, most people say,"how am I supposed to do anything without an if statement?" The answer is thatyou can use polymorphism to achieve the same task in many cases. The secondquestion is usually, "well that's great but why would I want to do that?" Theanswer is a previous clean code concept we learned: a function should only doone thing. When you have classes and functions that have if statements, youare telling your user that your function does more than one thing. Remember,just do one thing. Bad: javascriptclass Airplane { // ... getCruisingAltitude() { switch (this.type) { case "777": return this.getMaxAltitude() - this.getPassengerCount(); case "Air Force One": return this.getMaxAltitude(); case "Cessna": return this.getMaxAltitude() - this.getFuelExpenditure(); } }} Good: ```javascriptclass Airplane { // ...} class Boeing777 extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getPassengerCount(); }} class AirForceOne extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude(); }} class Cessna extends Airplane { // ... getCruisingAltitude() { return this.getMaxAltitude() - this.getFuelExpenditure(); }}``` ⬆ back to top Avoid type-checking (part 1) JavaScript is untyped, which means your functions can take any type of argument.Sometimes you are bitten by this freedom and it becomes tempting to dotype-checking in your functions. There are many ways to avoid having to do this.The first thing to consider is consistent APIs. Bad: javascriptfunction travelToTexas(vehicle) { if (vehicle instanceof Bicycle) { vehicle.pedal(this.currentLocation, new Location("texas")); } else if (vehicle instanceof Car) { vehicle.drive(this.currentLocation, new Location("texas")); }} Good: javascriptfunction travelToTexas(vehicle) { vehicle.move(this.currentLocation, new Location("texas"));} ⬆ back to top Avoid type-checking (part 2) If you are working with basic primitive values like strings and integers,and you can't use polymorphism but you still feel the need to type-check,you should consider using TypeScript. It is an excellent alternative to normalJavaScript, as it provides you with static typing on top of standard JavaScriptsyntax. The problem with manually type-checking normal JavaScript is thatdoing it well requires so much extra verbiage that the faux "type-safety" you getdoesn't make up for the lost readability. Keep your JavaScript clean, writegood tests, and have good code reviews. Otherwise, do all of that but withTypeScript (which, like I said, is a great alternative!). Bad: ```javascriptfunction combine(val1, val2) { if ( (typeof val1 === "number" && typeof val2 === "number") || (typeof val1 === "string" && typeof val2 === "string") ) { return val1 + val2; } throw new Error("Must be of type String or Number");}``` Good: javascriptfunction combine(val1, val2) { return val1 + val2;} ⬆ back to top Don't over-optimize Modern browsers do a lot of optimization under-the-hood at runtime. A lot oftimes, if you are optimizing then you are just wasting your time. There are goodresources for seeing where optimization is lacking. Target those in the meantime, untilthey are fixed if they can be. Bad: javascript// On old browsers, each iteration with uncached `list.length` would be costly// because of `list.length` recomputation. In modern browsers, this is optimized.for (let i = 0, len = list.length; i < len; i++) { // ...} Good: javascriptfor (let i = 0; i < list.length; i++) { // ...} ⬆ back to top Remove dead code Dead code is just as bad as duplicate code. There's no reason to keep it inyour codebase. If it's not being called, get rid of it! It will still be safein your version history if you still need it. Bad: ```javascriptfunction oldRequestModule(url) { // ...} function newRequestModule(url) { // ...} const req = newRequestModule;inventoryTracker("apples", req, "www.inventory-awesome.io");``` Good: ```javascriptfunction newRequestModule(url) { // ...} const req = newRequestModule;inventoryTracker("apples", req, "www.inventory-awesome.io");``` ⬆ back to top Objects and Data Structures Use getters and setters Using getters and setters to access data on objects could be better than simplylooking for a property on an object. "Why?" you might ask. Well, here's anunorganized list of reasons why: When you want to do more beyond getting an object property, you don't haveto look up and change every accessor in your codebase. Makes adding validation simple when doing a set . Encapsulates the internal representation. Easy to add logging and error handling when getting and setting. You can lazy load your object's properties, let's say getting it from aserver. Bad: ```javascriptfunction makeBankAccount() { // ... return { balance: 0 // ... };} const account = makeBankAccount();account.balance = 100;``` Good: ```javascriptfunction makeBankAccount() { // this one is private let balance = 0; // a "getter", made public via the returned object below function getBalance() { return balance; } // a "setter", made public via the returned object below function setBalance(amount) { // ... validate before updating the balance balance = amount; } return { // ... getBalance, setBalance };} const account = makeBankAccount();account.setBalance(100);``` ⬆ back to top Make objects have private members This can be accomplished through closures (for ES5 and below). Bad: ```javascriptconst Employee = function(name) { this.name = name;}; Employee.prototype.getName = function getName() { return this.name;}; const employee = new Employee("John Doe");console.log( Employee name: ${employee.getName()} ); // Employee name: John Doedelete employee.name;console.log( Employee name: ${employee.getName()} ); // Employee name: undefined``` Good: ```javascriptfunction makeEmployee(name) { return { getName() { return name; } };} const employee = makeEmployee("John Doe");console.log( Employee name: ${employee.getName()} ); // Employee name: John Doedelete employee.name;console.log( Employee name: ${employee.getName()} ); // Employee name: John Doe``` ⬆ back to top Classes Prefer ES2015/ES6 classes over ES5 plain functions It's very difficult to get readable class inheritance, construction, and methoddefinitions for classical ES5 classes. If you need inheritance (and be awarethat you might not), then prefer ES2015/ES6 classes. However, prefer small functions overclasses until you find yourself needing larger and more complex objects. Bad: `` javascriptconst Animal = function(age) { if (!(this instanceof Animal)) { throw new Error("Instantiate Animal with new`"); } this.age = age;}; Animal.prototype.move = function move() {}; const Mammal = function(age, furColor) { if (!(this instanceof Mammal)) { throw new Error("Instantiate Mammal with new "); } Animal.call(this, age); this.furColor = furColor;}; Mammal.prototype = Object.create(Animal.prototype);Mammal.prototype.constructor = Mammal;Mammal.prototype.liveBirth = function liveBirth() {}; const Human = function(age, furColor, languageSpoken) { if (!(this instanceof Human)) { throw new Error("Instantiate Human with new "); } Mammal.call(this, age, furColor); this.languageSpoken = languageSpoken;}; Human.prototype = Object.create(Mammal.prototype);Human.prototype.constructor = Human;Human.prototype.speak = function speak() {};``` Good: ```javascriptclass Animal { constructor(age) { this.age = age; } move() { /* ... */ }} class Mammal extends Animal { constructor(age, furColor) { super(age); this.furColor = furColor; } liveBirth() { /* ... */ }} class Human extends Mammal { constructor(age, furColor, languageSpoken) { super(age, furColor); this.languageSpoken = languageSpoken; } speak() { /* ... */ }}``` ⬆ back to top Use method chaining This pattern is very useful in JavaScript and you see it in many libraries suchas jQuery and Lodash. It allows your code to be expressive, and less verbose.For that reason, I say, use method chaining and take a look at how clean your codewill be. In your class functions, simply return this at the end of every function,and you can chain further class methods onto it. Bad: ```javascriptclass Car { constructor(make, model, color) { this.make = make; this.model = model; this.color = color; } setMake(make) { this.make = make; } setModel(model) { this.model = model; } setColor(color) { this.color = color; } save() { console.log(this.make, this.model, this.color); }} const car = new Car("Ford", "F-150", "red");car.setColor("pink");car.save();``` Good: ```javascriptclass Car { constructor(make, model, color) { this.make = make; this.model = model; this.color = color; } setMake(make) { this.make = make; // NOTE: Returning this for chaining return this; } setModel(model) { this.model = model; // NOTE: Returning this for chaining return this; } setColor(color) { this.color = color; // NOTE: Returning this for chaining return this; } save() { console.log(this.make, this.model, this.color); // NOTE: Returning this for chaining return this; }} const car = new Car("Ford", "F-150", "red").setColor("pink").save();``` ⬆ back to top Prefer composition over inheritance As stated famously in Design Patterns by the Gang of Four,you should prefer composition over inheritance where you can. There are lots ofgood reasons to use inheritance and lots of good reasons to use composition.The main point for this maxim is that if your mind instinctively goes forinheritance, try to think if composition could model your problem better. In somecases it can. You might be wondering then, "when should I use inheritance?" Itdepends on your problem at hand, but this is a decent list of when inheritancemakes more sense than composition: Your inheritance represents an "is-a" relationship and not a "has-a"relationship (Human->Animal vs. User->UserDetails). You can reuse code from the base classes (Humans can move like all animals). You want to make global changes to derived classes by changing a base class.(Change the caloric expenditure of all animals when they move). Bad: ```javascriptclass Employee { constructor(name, email) { this.name = name; this.email = email; } // ...} // Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employeeclass EmployeeTaxData extends Employee { constructor(ssn, salary) { super(); this.ssn = ssn; this.salary = salary; } // ...}``` Good: ```javascriptclass EmployeeTaxData { constructor(ssn, salary) { this.ssn = ssn; this.salary = salary; } // ...} class Employee { constructor(name, email) { this.name = name; this.email = email; } setTaxData(ssn, salary) { this.taxData = new EmployeeTaxData(ssn, salary); } // ...}``` ⬆ back to top SOLID Single Responsibility Principle (SRP) As stated in Clean Code, "There should never be more than one reason for a classto change". It's tempting to jam-pack a class with a lot of functionality, likewhen you can only take one suitcase on your flight. The issue with this isthat your class won't be conceptually cohesive and it will give it many reasonsto change. Minimizing the amount of times you need to change a class is important.It's important because if too much functionality is in one class and you modifya piece of it, it can be difficult to understand how that will affect otherdependent modules in your codebase. Bad: ```javascriptclass UserSettings { constructor(user) { this.user = user; } changeSettings(settings) { if (this.verifyCredentials()) { // ... } } verifyCredentials() { // ... }}``` Good: ```javascriptclass UserAuth { constructor(user) { this.user = user; } verifyCredentials() { // ... }} class UserSettings { constructor(user) { this.user = user; this.auth = new UserAuth(user); } changeSettings(settings) { if (this.auth.verifyCredentials()) { // ... } }}``` ⬆ back to top Open/Closed Principle (OCP) As stated by Bertrand Meyer, "software entities (classes, modules, functions,etc.) should be open for extension, but closed for modification." What does thatmean though? This principle basically states that you should allow users toadd new functionalities without changing existing code. Bad: ```javascriptclass AjaxAdapter extends Adapter { constructor() { super(); this.name = "ajaxAdapter"; }} class NodeAdapter extends Adapter { constructor() { super(); this.name = "nodeAdapter"; }} class HttpRequester { constructor(adapter) { this.adapter = adapter; } fetch(url) { if (this.adapter.name === "ajaxAdapter") { return makeAjaxCall(url).then(response => { // transform response and return }); } else if (this.adapter.name === "nodeAdapter") { return makeHttpCall(url).then(response => { // transform response and return }); } }} function makeAjaxCall(url) { // request and return promise} function makeHttpCall(url) { // request and return promise}``` Good: ```javascriptclass AjaxAdapter extends Adapter { constructor() { super(); this.name = "ajaxAdapter"; } request(url) { // request and return promise }} class NodeAdapter extends Adapter { constructor() { super(); this.name = "nodeAdapter"; } request(url) { // request and return promise }} class HttpRequester { constructor(adapter) { this.adapter = adapter; } fetch(url) { return this.adapter.request(url).then(response => { // transform response and return }); }}``` ⬆ back to top Liskov Substitution Principle (LSP) This is a scary term for a very simple concept. It's formally defined as "If Sis a subtype of T, then objects of type T may be replaced with objects of type S(i.e., objects of type S may substitute objects of type T) without altering anyof the desirable properties of that program (correctness, task performed,etc.)." That's an even scarier definition. The best explanation for this is if you have a parent class and a child class,then the base class and child class can be used interchangeably without gettingincorrect results. This might still be confusing, so let's take a look at theclassic Square-Rectangle example. Mathematically, a square is a rectangle, butif you model it using the "is-a" relationship via inheritance, you quicklyget into trouble. Bad: ```javascriptclass Rectangle { constructor() { this.width = 0; this.height = 0; } setColor(color) { // ... } render(area) { // ... } setWidth(width) { this.width = width; } setHeight(height) { this.height = height; } getArea() { return this.width * this.height; }} class Square extends Rectangle { setWidth(width) { this.width = width; this.height = width; } setHeight(height) { this.width = height; this.height = height; }} function renderLargeRectangles(rectangles) { rectangles.forEach(rectangle => { rectangle.setWidth(4); rectangle.setHeight(5); const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. rectangle.render(area); });} const rectangles = [new Rectangle(), new Rectangle(), new Square()];renderLargeRectangles(rectangles);``` Good: ```javascriptclass Shape { setColor(color) { // ... } render(area) { // ... }} class Rectangle extends Shape { constructor(width, height) { super(); this.width = width; this.height = height; } getArea() { return this.width * this.height; }} class Square extends Shape { constructor(length) { super(); this.length = length; } getArea() { return this.length * this.length; }} function renderLargeShapes(shapes) { shapes.forEach(shape => { const area = shape.getArea(); shape.render(area); });} const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];renderLargeShapes(shapes);``` ⬆ back to top Interface Segregation Principle (ISP) JavaScript doesn't have interfaces so this principle doesn't apply as strictlyas others. However, it's important and relevant even with JavaScript's lack oftype system. ISP states that "Clients should not be forced to depend upon interfaces thatthey do not use." Interfaces are implicit contracts in JavaScript because ofduck typing. A good example to look at that demonstrates this principle in JavaScript is forclasses that require large settings objects. Not requiring clients to setuphuge amounts of options is beneficial, because most of the time they won't needall of the settings. Making them optional helps prevent having a"fat interface". Bad: ```javascriptclass DOMTraverser { constructor(settings) { this.settings = settings; this.setup(); } setup() { this.rootNode = this.settings.rootNode; this.settings.animationModule.setup(); } traverse() { // ... }} const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), animationModule() {} // Most of the time, we won't need to animate when traversing. // ...});``` Good: ```javascriptclass DOMTraverser { constructor(settings) { this.settings = settings; this.options = settings.options; this.setup(); } setup() { this.rootNode = this.settings.rootNode; this.setupOptions(); } setupOptions() { if (this.options.animationModule) { // ... } } traverse() { // ... }} const $ = new DOMTraverser({ rootNode: document.getElementsByTagName("body"), options: { animationModule() {} }});``` ⬆ back to top Dependency Inversion Principle (DIP) This principle states two essential things: High-level modules should not depend on low-level modules. Both shoulddepend on abstractions. Abstractions should not depend upon details. Details should depend onabstractions. This can be hard to understand at first, but if you've worked with AngularJS,you've seen an implementation of this principle in the form of DependencyInjection (DI). While they are not identical concepts, DIP keeps high-levelmodules from knowing the details of its low-level modules and setting them up.It can accomplish this through DI. A huge benefit of this is that it reducesthe coupling between modules. Coupling is a very bad development pattern becauseit makes your code hard to refactor. As stated previously, JavaScript doesn't have interfaces so the abstractionsthat are depended upon are implicit contracts. That is to say, the methodsand properties that an object/class exposes to another object/class. In theexample below, the implicit contract is that any Request module for an InventoryTracker will have a requestItems method. Bad: ```javascriptclass InventoryRequester { constructor() { this.REQ_METHODS = ["HTTP"]; } requestItem(item) { // ... }} class InventoryTracker { constructor(items) { this.items = items; // BAD: We have created a dependency on a specific request implementation.// We should just have requestItems depend on a request method: `request`this.requester = new InventoryRequester(); } requestItems() { this.items.forEach(item => { this.requester.requestItem(item); }); }} const inventoryTracker = new InventoryTracker(["apples", "bananas"]);inventoryTracker.requestItems();``` Good: ```javascriptclass InventoryTracker { constructor(items, requester) { this.items = items; this.requester = requester; } requestItems() { this.items.forEach(item => { this.requester.requestItem(item); }); }} class InventoryRequesterV1 { constructor() { this.REQ_METHODS = ["HTTP"]; } requestItem(item) { // ... }} class InventoryRequesterV2 { constructor() { this.REQ_METHODS = ["WS"]; } requestItem(item) { // ... }} // By constructing our dependencies externally and injecting them, we can easily// substitute our request module for a fancy new one that uses WebSockets.const inventoryTracker = new InventoryTracker( ["apples", "bananas"], new InventoryRequesterV2());inventoryTracker.requestItems();``` ⬆ back to top Testing Testing is more important than shipping. If you have no tests or aninadequate amount, then every time you ship code you won't be sure that youdidn't break anything. Deciding on what constitutes an adequate amount is upto your team, but having 100% coverage (all statements and branches) is howyou achieve very high confidence and developer peace of mind. This means thatin addition to having a great testing framework, you also need to use a good coverage tool . There's no excuse to not write tests. There are plenty of good JS test frameworks , so find one that your team prefers.When you find one that works for your team, then aim to always write testsfor every new feature/module you introduce. If your preferred method isTest Driven Development (TDD), that is great, but the main point is to justmake sure you are reaching your coverage goals before launching any feature,or refactoring an existing one. Single concept per test Bad: ```javascriptimport assert from "assert"; describe("MomentJS", () => { it("handles date boundaries", () => { let date; date = new MomentJS("1/1/2015");date.addDays(30);assert.equal("1/31/2015", date);date = new MomentJS("2/1/2016");date.addDays(28);assert.equal("02/29/2016", date);date = new MomentJS("2/1/2015");date.addDays(28);assert.equal("03/01/2015", date); });});``` Good: ```javascriptimport assert from "assert"; describe("MomentJS", () => { it("handles 30-day months", () => { const date = new MomentJS("1/1/2015"); date.addDays(30); assert.equal("1/31/2015", date); }); it("handles leap year", () => { const date = new MomentJS("2/1/2016"); date.addDays(28); assert.equal("02/29/2016", date); }); it("handles non-leap year", () => { const date = new MomentJS("2/1/2015"); date.addDays(28); assert.equal("03/01/2015", date); });});``` ⬆ back to top Concurrency Use Promises, not callbacks Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,Promises are a built-in global type. Use them! Bad: ```javascriptimport { get } from "request";import { writeFile } from "fs"; get( "https://en.wikipedia.org/wiki/Robert Cecil Martin", (requestErr, response, body) => { if (requestErr) { console.error(requestErr); } else { writeFile("article.html", body, writeErr => { if (writeErr) { console.error(writeErr); } else { console.log("File written"); } }); } });``` Good: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert Cecil Martin") .then(body => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) .catch(err => { console.error(err); });``` ⬆ back to top Async/Await are even cleaner than Promises Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and awaitwhich offer an even cleaner solution. All you need is a function that is prefixedin an async keyword, and then you can write your logic imperatively withouta then chain of functions. Use this if you can take advantage of ES2017/ES8 featurestoday! Bad: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; get("https://en.wikipedia.org/wiki/Robert Cecil Martin") .then(body => { return writeFile("article.html", body); }) .then(() => { console.log("File written"); }) .catch(err => { console.error(err); });``` Good: ```javascriptimport { get } from "request-promise";import { writeFile } from "fs-extra"; async function getCleanCodeArticle() { try { const body = await get( "https://en.wikipedia.org/wiki/Robert Cecil Martin" ); await writeFile("article.html", body); console.log("File written"); } catch (err) { console.error(err); }} getCleanCodeArticle()``` ⬆ back to top Error Handling Thrown errors are a good thing! They mean the runtime has successfullyidentified when something in your program has gone wrong and it's lettingyou know by stopping function execution on the current stack, killing theprocess (in Node), and notifying you in the console with a stack trace. Don't ignore caught errors Doing nothing with a caught error doesn't give you the ability to ever fixor react to said error. Logging the error to the console ( console.log )isn't much better as often times it can get lost in a sea of things printedto the console. If you wrap any bit of code in a try/catch it means youthink an error may occur there and therefore you should have a plan,or create a code path, for when it occurs. Bad: javascripttry { functionThatMightThrow();} catch (error) { console.log(error);} Good: javascripttry { functionThatMightThrow();} catch (error) { // One option (more noisy than console.log): console.error(error); // Another option: notifyUserOfError(error); // Another option: reportErrorToService(error); // OR do all three!} Don't ignore rejected promises For the same reason you shouldn't ignore caught errorsfrom try/catch . Bad: javascriptgetdata() .then(data => { functionThatMightThrow(data); }) .catch(error => { console.log(error); }); Good: javascriptgetdata() .then(data => { functionThatMightThrow(data); }) .catch(error => { // One option (more noisy than console.log): console.error(error); // Another option: notifyUserOfError(error); // Another option: reportErrorToService(error); // OR do all three! }); ⬆ back to top Formatting Formatting is subjective. Like many rules herein, there is no hard and fastrule that you must follow. The main point is DO NOT ARGUE over formatting.There are tons of tools to automate this.Use one! It's a waste of time and money for engineers to argue over formatting. For things that don't fall under the purview of automatic formatting(indentation, tabs vs. spaces, double vs. single quotes, etc.) look herefor some guidance. Use consistent capitalization JavaScript is untyped, so capitalization tells you a lot about your variables,functions, etc. These rules are subjective, so your team can choose whateverthey want. The point is, no matter what you all choose, just be consistent. Bad: ```javascriptconst DAYS IN WEEK = 7;const daysInMonth = 30; const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"];const Artists = ["ACDC", "Led Zeppelin", "The Beatles"]; function eraseDatabase() {}function restore_database() {} class animal {}class Alpaca {}``` Good: ```javascriptconst DAYS IN WEEK = 7;const DAYS IN MONTH = 30; const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"];const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"]; function eraseDatabase() {}function restoreDatabase() {} class Animal {}class Alpaca {}``` ⬆ back to top Function callers and callees should be close If a function calls another, keep those functions vertically close in the sourcefile. Ideally, keep the caller right above the callee. We tend to read code fromtop-to-bottom, like a newspaper. Because of this, make your code read that way. Bad: ```javascriptclass PerformanceReview { constructor(employee) { this.employee = employee; } lookupPeers() { return db.lookup(this.employee, "peers"); } lookupManager() { return db.lookup(this.employee, "manager"); } getPeerReviews() { const peers = this.lookupPeers(); // ... } perfReview() { this.getPeerReviews(); this.getManagerReview(); this.getSelfReview(); } getManagerReview() { const manager = this.lookupManager(); } getSelfReview() { // ... }} const review = new PerformanceReview(employee);review.perfReview();``` Good: ```javascriptclass PerformanceReview { constructor(employee) { this.employee = employee; } perfReview() { this.getPeerReviews(); this.getManagerReview(); this.getSelfReview(); } getPeerReviews() { const peers = this.lookupPeers(); // ... } lookupPeers() { return db.lookup(this.employee, "peers"); } getManagerReview() { const manager = this.lookupManager(); } lookupManager() { return db.lookup(this.employee, "manager"); } getSelfReview() { // ... }} const review = new PerformanceReview(employee);review.perfReview();``` ⬆ back to top Comments Only comment things that have business logic complexity. Comments are an apology, not a requirement. Good code mostly documents itself. Bad: ```javascriptfunction hashIt(data) { // The hash let hash = 0; // Length of string const length = data.length; // Loop through every character in data for (let i = 0; i < length; i++) { // Get character code. const char = data.charCodeAt(i); // Make the hash hash = (hash << 5) - hash + char; // Convert to 32-bit integer hash &= hash; }}``` Good: ```javascriptfunction hashIt(data) { let hash = 0; const length = data.length; for (let i = 0; i < length; i++) { const char = data.charCodeAt(i); hash = (hash << 5) - hash + char; // Convert to 32-bit integerhash &= hash; }}``` ⬆ back to top Don't leave commented out code in your codebase Version control exists for a reason. Leave old code in your history. Bad: javascriptdoStuff();// doOtherStuff();// doSomeMoreStuff();// doSoMuchStuff(); Good: javascriptdoStuff(); ⬆ back to top Don't have journal comments Remember, use version control! There's no need for dead code, commented code,and especially journal comments. Use git log to get history! Bad: javascript/** * 2016-12-20: Removed monads, didn't understand them (RM) * 2016-10-01: Improved using special monads (JP) * 2016-02-03: Removed type-checking (LI) * 2015-03-14: Added combine with type-checking (JR) */function combine(a, b) { return a + b;} Good: javascriptfunction combine(a, b) { return a + b;} ⬆ back to top Avoid positional markers They usually just add noise. Let the functions and variable names along with theproper indentation and formatting give the visual structure to your code. Bad: ```javascript////////////////////////////////////////////////////////////////////////////////// Scope Model Instantiation////////////////////////////////////////////////////////////////////////////////$scope.model = { menu: "foo", nav: "bar"}; ////////////////////////////////////////////////////////////////////////////////// Action setup////////////////////////////////////////////////////////////////////////////////const actions = function() { // ...};``` Good: ```javascript$scope.model = { menu: "foo", nav: "bar"}; const actions = function() { // ...};``` ⬆ back to top Translation This is also available in other languages: Armenian : hanumanum/clean-code-javascript/ Bangla(বাংলা) : InsomniacSabbir/clean-code-javascript/ Brazilian Portuguese : fesnt/clean-code-javascript Simplified Chinese : alivebao/clean-code-js beginor/clean-code-javascript Traditional Chinese : AllJointTW/clean-code-javascript French : eugene-augier/clean-code-javascript-fr German : marcbruederlin/clean-code-javascript Indonesia : andirkh/clean-code-javascript/ Italian : frappacchio/clean-code-javascript/ Japanese : mitsuruog/clean-code-javascript/ Korean : qkraudghgh/clean-code-javascript-ko Polish : greg-dev/clean-code-javascript-pl Russian : BoryaMogila/clean-code-javascript-ru/ maksugr/clean-code-javascript Spanish : tureey/clean-code-javascript Spanish : andersontr15/clean-code-javascript Serbian : doskovicmilos/clean-code-javascript/ Turkish : bsonmez/clean-code-javascript Ukrainian : mindfr1k/clean-code-javascript-ua Vietnamese : hienvd/clean-code-javascript/ Persian : hamettio/clean-code-javascript ⬆ back to top To restore the repository download the bundle wget https://archive.org/download/github.com-ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41/ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41.bundle and run: git clone ryanmcdermott-clean-code-javascript_-_2023-08-14_18-12-41.bundle Source: https://github.com/ryanmcdermott/clean-code-javascript Uploader: ryanmcdermott Upload date: 2023-08-14

“Head First JavaScript” Metadata:

  • Title: Head First JavaScript
  • Author:
  • Language: English

“Head First JavaScript” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 1090.17 Mbs, the file-s for this book were downloaded 219 times, the file-s went public at Wed May 19 2021.

Available formats:
ACS Encrypted PDF - Cloth Cover Detection Log - DjVuTXT - Djvu XML - Dublin Core - EPUB - Item Tile - JPEG Thumb - JSON - LCP Encrypted EPUB - LCP Encrypted PDF - Log - MARC - MARC Binary - Metadata - OCR Page Index - OCR Search Text - PNG - Page Numbers JSON - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - Title Page Detection Log - chOCR - hOCR -

Related Links:

Online Marketplaces

Find Head First JavaScript at online marketplaces:


35Hak5 - Shannon Morse On Javascript With CodeAcademy, Hak5 1022.2

By

This time on the show, pound include programming dot h! We're going to void main and Hello World all up in this biznitch. Python, JavaScript, BASIC? It's time to learn to code! All that and more this time on Hak5............return zero Source: https://www.youtube.com/watch?v=tQBmdlz3sF4 Uploader: Hak5

“Hak5 - Shannon Morse On Javascript With CodeAcademy, Hak5 1022.2” Metadata:

  • Title: ➤  Hak5 - Shannon Morse On Javascript With CodeAcademy, Hak5 1022.2
  • Author:

“Hak5 - Shannon Morse On Javascript With CodeAcademy, Hak5 1022.2” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 97.19 Mbs, the file-s for this book were downloaded 133 times, the file-s went public at Tue Jul 09 2019.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - JSON - MPEG4 - Metadata - Ogg Video - Thumbnail - Unknown -

Related Links:

Online Marketplaces

Find Hak5 - Shannon Morse On Javascript With CodeAcademy, Hak5 1022.2 at online marketplaces:


36HTML5, JavaScript, And JQuery 24-hour Trainer

By

This time on the show, pound include programming dot h! We're going to void main and Hello World all up in this biznitch. Python, JavaScript, BASIC? It's time to learn to code! All that and more this time on Hak5............return zero Source: https://www.youtube.com/watch?v=tQBmdlz3sF4 Uploader: Hak5

“HTML5, JavaScript, And JQuery 24-hour Trainer” Metadata:

  • Title: ➤  HTML5, JavaScript, And JQuery 24-hour Trainer
  • Author:
  • Language: English

“HTML5, JavaScript, And JQuery 24-hour Trainer” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 1211.49 Mbs, the file-s for this book were downloaded 79 times, the file-s went public at Sat Jun 18 2022.

Available formats:
ACS Encrypted PDF - AVIF Thumbnails ZIP - Cloth Cover Detection Log - DjVuTXT - Djvu XML - Dublin Core - EPUB - Item Tile - JPEG Thumb - JSON - LCP Encrypted EPUB - LCP Encrypted PDF - Log - MARC - MARC Binary - Metadata - OCR Page Index - OCR Search Text - PNG - Page Numbers JSON - RePublisher Final Processing Log - RePublisher Initial Processing Log - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - Title Page Detection Log - chOCR - hOCR -

Related Links:

Online Marketplaces

Find HTML5, JavaScript, And JQuery 24-hour Trainer at online marketplaces:


37HTML, JavaScript

By

This time on the show, pound include programming dot h! We're going to void main and Hello World all up in this biznitch. Python, JavaScript, BASIC? It's time to learn to code! All that and more this time on Hak5............return zero Source: https://www.youtube.com/watch?v=tQBmdlz3sF4 Uploader: Hak5

“HTML, JavaScript” Metadata:

  • Title: HTML, JavaScript
  • Author:
  • Language: fre

“HTML, JavaScript” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 1016.52 Mbs, the file-s for this book were downloaded 82 times, the file-s went public at Wed Dec 02 2020.

Available formats:
ACS Encrypted PDF - Cloth Cover Detection Log - DjVuTXT - Djvu XML - Dublin Core - EPUB - Item Tile - JPEG Thumb - JSON - LCP Encrypted EPUB - LCP Encrypted PDF - Log - MARC - MARC Binary - Metadata - OCR Page Index - OCR Search Text - PNG - Page Numbers JSON - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - Title Page Detection Log - chOCR - hOCR -

Related Links:

Online Marketplaces

Find HTML, JavaScript at online marketplaces:


38Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 14. Orientação A Objetos PHP 1. Introdução

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 14. Orientação a objetos PHP 1. Introdução

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 14. Orientação A Objetos PHP 1. Introdução” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 14. Orientação A Objetos PHP 1. Introdução

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 5 times, the file-s went public at Fri May 14 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 14. Orientação A Objetos PHP 1. Introdução at online marketplaces:


39JavaScript, CSS3, HTML5 Logotype (4579069)

By

For all programmer Logotype of HTML5, CSS3 and JAVASCRIPT

“JavaScript, CSS3, HTML5 Logotype (4579069)” Metadata:

  • Title: ➤  JavaScript, CSS3, HTML5 Logotype (4579069)
  • Author: ➤  

“JavaScript, CSS3, HTML5 Logotype (4579069)” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.06 Mbs, the file-s for this book were downloaded 46 times, the file-s went public at Tue Jan 05 2021.

Available formats:
Archive BitTorrent - Metadata - ZIP -

Related Links:

Online Marketplaces

Find JavaScript, CSS3, HTML5 Logotype (4579069) at online marketplaces:


40Instant JavaScript

By

For all programmer Logotype of HTML5, CSS3 and JAVASCRIPT

“Instant JavaScript” Metadata:

  • Title: Instant JavaScript
  • Author:
  • Language: English

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 981.73 Mbs, the file-s for this book were downloaded 24 times, the file-s went public at Wed Apr 20 2022.

Available formats:
ACS Encrypted PDF - AVIF Thumbnails ZIP - Cloth Cover Detection Log - DjVuTXT - Djvu XML - Dublin Core - EPUB - Item Tile - JPEG Thumb - JSON - LCP Encrypted EPUB - LCP Encrypted PDF - Log - MARC - MARC Binary - Metadata - OCR Page Index - OCR Search Text - PNG - Page Numbers JSON - RePublisher Final Processing Log - RePublisher Initial Processing Log - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - Title Page Detection Log - chOCR - hOCR -

Related Links:

Online Marketplaces

Find Instant JavaScript at online marketplaces:


41Github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17

By

Algorithms and Data Structures implemented in JavaScript for beginners, following best practices. The Algorithms - JavaScript JavaScript Repository of TheAlgorithms, which implements various algorithms and data structures in JavaScript. [![JavaScript Banner][banner]](DIRECTORY.md) [![Language grade: JavaScript][grade]][lgtm] [![Checks][checks]][actions] [![Contributions Welcome][welcome]](CONTRIBUTING.md) [![standard.js][standard-logo]][standard-js] [![Discord chat][chat]][discord-server] These implementations are for demonstrative purposes only. Dedicated implementations of these algorithms and data structures are much better for performance and security reasons. We also do not provide any guarantee for api stability. Before contributing to this repository, make sure to read our Contribution Guidelines . You can lookat other TheAlgorithms Repositories or the issues with a "help wanted" label forinspiration regarding what to implement. Our maintainers will guide you through how to make your contribution properlyif you make any mistakes. The names of the maintainers of this repository is listed in the CODEOWNERS file . You can find a list of the algorithms currently in the repository in the directory . Explanations ofmany of the algorithms can be found in the wiki . To restore the repository download the bundle wget https://archive.org/download/github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17/TheAlgorithms-JavaScript_-_2022-07-19_04-10-17.bundle and run: git clone TheAlgorithms-JavaScript_-_2022-07-19_04-10-17.bundle Source: https://github.com/TheAlgorithms/JavaScript Uploader: TheAlgorithms Upload date: 2022-07-19

“Github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17” Metadata:

  • Title: ➤  Github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17
  • Author:

“Github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 2.01 Mbs, the file-s for this book were downloaded 33 times, the file-s went public at Tue Jul 19 2022.

Available formats:
Archive BitTorrent - Item Tile - JPEG - JPEG Thumb - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Github.com-TheAlgorithms-JavaScript_-_2022-07-19_04-10-17 at online marketplaces:


4230+ Web Projects With HTML, CSS, And JavaScript

30+ Web Projects with HTML, CSS, and JavaScript

“30+ Web Projects With HTML, CSS, And JavaScript” Metadata:

  • Title: ➤  30+ Web Projects With HTML, CSS, And JavaScript

“30+ Web Projects With HTML, CSS, And JavaScript” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "movies" format, the size of the file-s is: 23339.96 Mbs, the file-s for this book were downloaded 241 times, the file-s went public at Sat Apr 23 2022.

Available formats:
Archive BitTorrent - Item Tile - MPEG4 - Metadata - Thumbnail - ZIP - h.264 IA -

Related Links:

Online Marketplaces

Find 30+ Web Projects With HTML, CSS, And JavaScript at online marketplaces:


43Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 2. Preparando Se Para O Desenvolvimento 6. Como Exibir As Extensões Dos Arquivos

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 2. Preparando-se para o desenvolvimento 6. Como exibir as extensões dos arquivos

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 2. Preparando Se Para O Desenvolvimento 6. Como Exibir As Extensões Dos Arquivos” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 2. Preparando Se Para O Desenvolvimento 6. Como Exibir As Extensões Dos Arquivos

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s for this book were downloaded 5 times, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 2. Preparando Se Para O Desenvolvimento 6. Como Exibir As Extensões Dos Arquivos at online marketplaces:


44What Should I Know As A First Time JavaScript Developer?

By

Video content can be found here: https://www.youtube.com/channel/UC0BAd8tPlDqFvDYBemHcQPQ/

“What Should I Know As A First Time JavaScript Developer?” Metadata:

  • Title: ➤  What Should I Know As A First Time JavaScript Developer?
  • Author:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 22.21 Mbs, the file-s for this book were downloaded 3 times, the file-s went public at Mon Jun 28 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find What Should I Know As A First Time JavaScript Developer? at online marketplaces:


45Javascript

javascript aulas

“Javascript” Metadata:

  • Title: Javascript
  • Language: English

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 0.01 Mbs, the file-s for this book were downloaded 83 times, the file-s went public at Tue Aug 15 2017.

Available formats:
Archive BitTorrent - Metadata - ZIP -

Related Links:

Online Marketplaces

Find Javascript at online marketplaces:


46JavaScript : The Definitive Guide

By

javascript aulas

“JavaScript : The Definitive Guide” Metadata:

  • Title: ➤  JavaScript : The Definitive Guide
  • Author:
  • Language: English

“JavaScript : The Definitive Guide” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 737.77 Mbs, the file-s for this book were downloaded 88 times, the file-s went public at Fri Jul 29 2011.

Available formats:
ACS Encrypted EPUB - ACS Encrypted PDF - Abbyy GZ - Animated GIF - Cloth Cover Detection Log - DjVu - DjVuTXT - Djvu XML - Dublin Core - EPUB - Grayscale PDF - Item Tile - JPEG-Compressed PDF - LCP Encrypted EPUB - LCP Encrypted PDF - MARC - MARC Binary - MARC Source - METS - Metadata - OCR Page Index - OCR Search Text - Page Numbers JSON - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - chOCR - hOCR -

Related Links:

Online Marketplaces

Find JavaScript : The Definitive Guide at online marketplaces:


47Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 16. Ajax ( Asynchronous Javascript And XML) 5. Requisições Síncronas Com Links

Curso completo de Desenvolvimento Web Crie 6 projetosHTML JAVASCRIPT CSS PHP 16. Ajax (Asynchronous Javascript and XML) 5. Requisições síncronas com links

“Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 16. Ajax ( Asynchronous Javascript And XML) 5. Requisições Síncronas Com Links” Metadata:

  • Title: ➤  Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 16. Ajax ( Asynchronous Javascript And XML) 5. Requisições Síncronas Com Links

Edition Identifiers:

Downloads Information:

The book is available for download in "data" format, the size of the file-s is: 0.02 Mbs, the file-s went public at Sat May 15 2021.

Available formats:
Metadata - Web Video Text Tracks -

Related Links:

Online Marketplaces

Find Curso Completo De Desenvolvimento Web Crie 6 Projetos HTML JAVASCRIPT CSS PHP 16. Ajax ( Asynchronous Javascript And XML) 5. Requisições Síncronas Com Links at online marketplaces:


48Should Websites Work Without JavaScript Enabled?

By

Video content can be found here: https://www.youtube.com/channel/UC0BAd8tPlDqFvDYBemHcQPQ/

“Should Websites Work Without JavaScript Enabled?” Metadata:

  • Title: ➤  Should Websites Work Without JavaScript Enabled?
  • Author:

Edition Identifiers:

Downloads Information:

The book is available for download in "audio" format, the size of the file-s is: 20.32 Mbs, the file-s for this book were downloaded 1 times, the file-s went public at Mon Jun 28 2021.

Available formats:
Archive BitTorrent - Columbia Peaks - Item Tile - Metadata - PNG - Spectrogram - VBR MP3 -

Related Links:

Online Marketplaces

Find Should Websites Work Without JavaScript Enabled? at online marketplaces:


49Javascript MESS/MAME Keyboard Collection Version 2

The goal is to provide a ubiquitous, flexible, comprehensive-as-possible emulator that will appear in as many browsers as possible without installing a plugin or runtime. While a number of emulation solutions exist that allow much of what is wanted, they nearly all require plugins and most are directed towards a single machine or small sets of machines. Currently, the most flexible runtime is current versions of Javascript, a horribly named runtime that utilizes a Turing-complete programming language to provide all manner of applications, effects and trickery to the browsing public. All major browsers support Javascript, and the language also allows support for cleanly informing end-users what is going on if something goes wrong. MESS and MAME were started over a decade ago to provide ubiquitous, universal emulation of arcade/gaming machines (MAME) and general computer hardware (MESS). While specific emulation implementations exist that do specific machines better than MAME/MESS, no other project has the comprehensiveness and modularity. Modifications are consistently coming in, and emulation breadth and quality increases over time. In the case of MAME, pages exist listing machines it does not emulate. The dream/goal is to provide access to computer software and artwork that would otherwise require the user to have the original hardware and software at hand to bring into existence. While nothing beats having vintage, well-maintained computer hardware to show what software "was", it requires advocacy and often physical presence to do so. Games like Pac-Man' or Super Mario have been re-done many times and provided in all manner of online and offline presentations... not so much examples of Wordperfect, Peachtree Accounting, or the Atari TOS. By providing this method of calling in software, historians and academics and the merely curious can get near-instantaneous access to the gist of these early programming works. As a side benefit, people with collections of old software will be more inclined to share or donate their piles of materials knowing that universal access will come shortly after.

“Javascript MESS/MAME Keyboard Collection Version 2” Metadata:

  • Title: ➤  Javascript MESS/MAME Keyboard Collection Version 2

Edition Identifiers:

Downloads Information:

The book is available for download in "software" format, the size of the file-s is: 0.09 Mbs, the file-s for this book were downloaded 6585640 times, the file-s went public at Tue Oct 21 2014.

Available formats:
Archive BitTorrent - Metadata - Unknown -

Related Links:

Online Marketplaces

Find Javascript MESS/MAME Keyboard Collection Version 2 at online marketplaces:


50JavaScript Essentials

By

The goal is to provide a ubiquitous, flexible, comprehensive-as-possible emulator that will appear in as many browsers as possible without installing a plugin or runtime. While a number of emulation solutions exist that allow much of what is wanted, they nearly all require plugins and most are directed towards a single machine or small sets of machines. Currently, the most flexible runtime is current versions of Javascript, a horribly named runtime that utilizes a Turing-complete programming language to provide all manner of applications, effects and trickery to the browsing public. All major browsers support Javascript, and the language also allows support for cleanly informing end-users what is going on if something goes wrong. MESS and MAME were started over a decade ago to provide ubiquitous, universal emulation of arcade/gaming machines (MAME) and general computer hardware (MESS). While specific emulation implementations exist that do specific machines better than MAME/MESS, no other project has the comprehensiveness and modularity. Modifications are consistently coming in, and emulation breadth and quality increases over time. In the case of MAME, pages exist listing machines it does not emulate. The dream/goal is to provide access to computer software and artwork that would otherwise require the user to have the original hardware and software at hand to bring into existence. While nothing beats having vintage, well-maintained computer hardware to show what software "was", it requires advocacy and often physical presence to do so. Games like Pac-Man' or Super Mario have been re-done many times and provided in all manner of online and offline presentations... not so much examples of Wordperfect, Peachtree Accounting, or the Atari TOS. By providing this method of calling in software, historians and academics and the merely curious can get near-instantaneous access to the gist of these early programming works. As a side benefit, people with collections of old software will be more inclined to share or donate their piles of materials knowing that universal access will come shortly after.

“JavaScript Essentials” Metadata:

  • Title: JavaScript Essentials
  • Author:
  • Language: English

“JavaScript Essentials” Subjects and Themes:

Edition Identifiers:

Downloads Information:

The book is available for download in "texts" format, the size of the file-s is: 1311.21 Mbs, the file-s for this book were downloaded 44 times, the file-s went public at Mon Dec 05 2022.

Available formats:
ACS Encrypted PDF - Cloth Cover Detection Log - DjVuTXT - Djvu XML - Dublin Core - EPUB - Item Tile - JPEG Thumb - JSON - LCP Encrypted EPUB - LCP Encrypted PDF - Log - MARC - MARC Binary - Metadata - Metadata Log - OCR Page Index - OCR Search Text - PNG - Page Numbers JSON - RePublisher Final Processing Log - RePublisher Initial Processing Log - Scandata - Single Page Original JP2 Tar - Single Page Processed JP2 ZIP - Text PDF - Title Page Detection Log - chOCR - hOCR -

Related Links:

Online Marketplaces

Find JavaScript Essentials at online marketplaces:


Source: The Open Library

The Open Library Search Results

Available books for downloads and borrow from The Open Library

1JavaScript

By

Book's cover

“JavaScript” Metadata:

  • Title: JavaScript
  • Author:
  • Language: English
  • Number of Pages: Median: 1014
  • Publisher: ➤  McGraw-Hill/Osborne Media - McGraw-Hill/Osborne - McGraw-Hill
  • Publish Date:
  • Publish Location: New York

“JavaScript” Subjects and Themes:

Edition Identifiers:

Access and General Info:

  • First Year Published: 2001
  • Is Full Text Available: Yes
  • Is The Book Public: No
  • Access Status: Borrowable

Online Access

Downloads Are Not Available:

The book is not public therefore the download links will not allow the download of the entire book, however, borrowing the book online is available.

Online Borrowing:

Online Marketplaces

Find JavaScript at online marketplaces:


Source: LibriVox

LibriVox Search Results

Available audio books for downloads from LibriVox

1Canyons of the Colorado

By

Book's cover

John Wesley Powell was a pioneer American explorer, ethnologist, and geologist in the 19th Century. In 1869 he set out to explore the Colorado and the Grand Canyon. He gathered nine men, four boats and food for ten months and set out from Green River, Wyoming, on May 24. Passing through dangerous rapids, the group passed down the Green River to its confluence with the Colorado River (then also known as the Grand River upriver from the junction), near present-day Moab, Utah.<br><br>The expedition's route traveled through the Utah canyons of the Colorado River, which Powell described in his published diary as having …wonderful features—carved walls, royal arches, glens, alcove gulches, mounds and monuments. From which of these features shall we select a name? We decide to call it Glen Canyon. (Ironically, now almost completely submerged by Lake Powell, behind the Glen Canyon Dam.)<br><br>One man (Goodman) quit after the first month and another three (Dunn and the Howland brothers) left at Separation Rapid in the third, only two days before the group reached the mouth of the Virgin River on August 30 after traversing almost 1,500 km. The three who left the group late in the trip were later killed—probably by Indians.<br><br>Powell retraced the route in 1871-1872 with another expedition, producing photographs, an accurate map, and various papers, including ethnographic reports of the area's Native Americans and a monograph on their languages. --adapted from Wikipedia

“Canyons of the Colorado” Metadata:

  • Title: Canyons of the Colorado
  • Author:
  • Language: English
  • Publish Date:

Edition Specifications:

  • Format: Audio
  • Number of Sections: 16
  • Total Time: 8:07:26

Edition Identifiers:

Links and information:

Online Access

Download the Audio Book:

  • File Name: canyons_colorado_0712_librivox
  • File Format: zip
  • Total Time: 8:07:26
  • Download Link: Download link

Online Marketplaces

Find Canyons of the Colorado at online marketplaces:


2Haunted Hangar

By

Book's cover

Second entry in series of teen aviation stories, filled with lots of scientific jargon, a jewel heist, and adventure. Van Powell is a pseudonym of early Hollywood screenwriter, Ardon Van Buren Powell (1886-1958). ( Matt Pierard)

“Haunted Hangar” Metadata:

  • Title: Haunted Hangar
  • Author:
  • Language: English
  • Publish Date:

Edition Specifications:

  • Format: Audio
  • Number of Sections: 34
  • Total Time: 05:44:05

Edition Identifiers:

Links and information:

  • LibriVox Link:
  • Text Source: - Download text file/s.
  • Number of Sections: 34 sections

Online Access

Download the Audio Book:

  • File Name: the_haunted_hangar_1806_librivox
  • File Format: zip
  • Total Time: 05:44:05
  • Download Link: Download link

Online Marketplaces

Find Haunted Hangar at online marketplaces:


3Titan Of Chasms: The Grand Canyon Of Arizona

By

Book's cover

This is a 1906 collection of three essays by men famously associated with The Grand Canyon: Charles A. Higgins, John Wesley Powell, and Charles F. Lummis. - Summary by david wales

“Titan Of Chasms: The Grand Canyon Of Arizona” Metadata:

  • Title: ➤  Titan Of Chasms: The Grand Canyon Of Arizona
  • Authors:
  • Language: English
  • Publish Date:

Edition Specifications:

  • Format: Audio
  • Number of Sections: 4
  • Total Time: 01:35:33

Edition Identifiers:

Links and information:

  • LibriVox Link:
  • Text Source: - Download text file/s.
  • Number of Sections: 4 sections

Online Access

Download the Audio Book:

  • File Name: titan_of_chasms_2108_librivox
  • File Format: zip
  • Total Time: 01:35:33
  • Download Link: Download link

Online Marketplaces

Find Titan Of Chasms: The Grand Canyon Of Arizona at online marketplaces:


4Whither

By

At long last, Zoe Bourne is moving. For years, she has yearned to leave her stifling, small hometown of Albon, and become a writer in Manhattan. She arrives in the city with the optimism of youth, and she’s greeted with a collective, acerbic shrug. Zoe soon learns she will need to fight harder than she ever imagined to carve out the literary niche she's been dreaming of. Otherwise, she faces the prospect of drudgery just as dull and uninspiring as her life in Albon had been.<br><br> Dawn Powell's debut novel crackles with the keenly-observed wit of her later work. Though she came to distance herself from this early effort, "Whither" is an important document in the development of her style, and it’s filled with comedic moments that will delight and entertain her admirers. - Summary by Jake Folsom

“Whither” Metadata:

  • Title: Whither
  • Author:
  • Language: English
  • Publish Date:

Edition Specifications:

  • Format: Audio
  • Number of Sections: 27

Edition Identifiers:

Links and information:

Online Access

Download the Audio Book:

    Online Marketplaces

    Find Whither at online marketplaces:


    Buy “Javascript” online:

    Shop for “Javascript” on popular online marketplaces.