SlideShare a Scribd company logo
JavaScript Best Practices
Jayanga V. Liyanage
Senior Software Engineer
email: jayangavliyanage@gmail.com
Producing Good Software
Superior coding techniques and good programming practices are hallmarks of a
professional programmer
Characteristics of good software
• Functional
• Measurable
• Robust
• Debuggable
• Maintainable
• Reusable
• Extensible
Best Practices
What are the best practices
• Best coding practices are a set of informal rules that the software development
community has learned over time which can help improve the quality of
software
List of best practices
1. Place scripts at the bottom of the Page
2. Readable and meaningful variable and function names
3. Comment as much as needed but not more
4. Avoid global variables
5. Namespace your JavaScript
6. Beware of “var”
7. Use === Instead of ==
List of best practices cont…
8. Avoid use of Eval
9. Don't pass a String to “SetInterval” or “SetTimeOut”
10. Don't use short-hand
11. Keep DOM access to a minimum
12. Optimize loops
13. Avoid mixing with other technologies
14. Use shortcut notation when it makes sense
List of best practices cont…
15. Avoid heavy nesting
16. Optimizing content for different browsers properly
17. Do not trust any data
18. Be cautious when creating too much content with JavaScript
19. Use self executing functions
20. Allow for configuration and translation
21. One function per task
22. Raw JavaScript can always be quicker than using a library
Place scripts at the bottom of the Page
• The primary goal is to make the page load as quickly as possible for the user.
When loading a script, the browser can't continue on until the entire file has
been loaded
Readable and meaningful variable and function names
Readable naming gives a clear idea what the code portion is
ought to do
Avoid
– e1
– xbqne
– incrementorForMainLoopWhichSpansFromTenToTwenty
– getIntegerElements()
Do
– employee
– counter
– MAX_CART_SIZE
Comment as much as needed but not more
– Comments let other developers to understand the purpose and
functionality of a code
– But over commenting only increase the line numbers and file size
No comments Over comments
Avoid global variables
• Every JavaScript file included in the page runs in the same scope
• If scripts included after the global variable, which contains the same variable
name and function names will overwrite it
Namespace your JavaScript
• Your JavaScript shouldn't be floating off in the global namespace, where it collides with other
stuff you've included
• Although JavaScript doesn't have built-in notions of namespaces, its object model is flexible
enough that you can emulate them
All the functions are
in global scope
Functions are
encapsulated using
a namespace
Beware of “var”
• Can be assign any type of data to the variables
• Always be cautious what type of data is assigned to the variable
Use === / !== instead of == / !=
• JavaScript utilizes two different kinds of equality operators: === | !== and == | !=
Avoid use of Eval
• Improper use of eval opens up your code for injection attacks
• Debugging can be more challenging (no line numbers, etc.)
• eval code executes slower
Don't pass a String to "SetInterval" or "SetTimeOut"
• String literals are evaluated in the global context, so local symbols in the context
where setTimeout() was called will not be available when the string is evaluated
as code
• Will execute in the same way as eval (global scope)
• Pass a function instead of string Ex: setInterval(someFunction, 3000)
Don't use short-hand
• Technically, you can get away with omitting curly braces and semi-colons
• The only time that curly braces should be omitted is with one-liners, and even
this is a highly debated topic
Omit braces and semicolon Actual result
Keep DOM access to a minimum
• The DOM is a very complex API and rendering in browsers can take up a lot of
time
• Accessing the DOM in browsers is very expensive
• Access DOM only when necessary
Access DOM through
out the loop
Access DOM only once
Optimize loops
• Loops can become very slow if they are not optimized properly
• Keep computation-heavy code outside loops
– This includes regular expressions and more importantly DOM manipulation
– It is ok to create the DOM nodes in the loop but avoid inserting them into the document
Always accessing the array
length
Accessing the array length
only once (Optimized)
Avoid mixing with other technologies
• Whilst it is possible to create everything you need in a document using
JavaScript and the DOM it is not necessarily the most effective way
Applying css directly
Add css class
Use shortcut notation when it makes sense
• It keeps the code small and simple
Avoid heavy nesting
• Nesting code explains its logic and makes it much easier to read, however
nesting it too far can also make it hard to follow what you are trying to do
Heavy nesting Use separate functions
Optimizing content for different browsers
• Writing code specific to a certain browser makes it hard to maintain and make it
get up to date really quickly
• Optimizing content for different browsers properly make it easier to maintain
and guarantee the stability
Detect feature availability
Version
compatibility
check
Do not trust any data
• Make sure that all the data that goes into the systems is clean and exactly what it expects
• This is most important on the back end when writing out parameters retrieved from the URL. In
JavaScript, it is very important to test the type of parameters sent to your functions
• Users can mistakenly or purposefully enter invalid data
Will fail if not an array Check data type
Be cautious when creating too much content with JavaScript
• Building a lot of HTML in JavaScript can be pretty daunting and flaky
• Internet Explorer can run into all kinds of trouble by altering the document while
it is still loading and manipulating the content with innerHTML
• Not every maintainer will have the same level of skill as you have and could
potentially really mess with your code
• Content creation depends on the nature of the project you are working on
– Static content
– Dynamic content loading (Ajax or PHP requests)
– Projects which use separate templates (Use ajax for template loading)
– Libraries and projects with dynamic content
Use self executing functions
• Rather than calling a function, it's quite simple to make a function run
automatically when a page loads, or a parent function is called
Allow for configuration and translation
• To make the code maintainable
and clean, create a configuration
object that contains all the things
that are likely to change over time
• These include any text used in
elements you create (including
button values and alternative text
for images), CSS class and ID names
and general parameters of the
interface you build
One function per task
• Make sure that you create functions that fulfill one job at a time.
• This will make it easy for other developers to debug and change your code
without having to scan through all the code to work out what code block
performs what function
• If you find yourself doing the same thing in several different functions then it is
a good idea to create a more generic helper function instead, and reuse that
functionality where it is needed
Raw JavaScript can always be quicker than using a library
• JavaScript libraries, such as jQuery and Mootools, can save an enormous amount
of time when coding -- especially with AJAX operations. Having said that, always
keep in mind that a library can never be as fast as raw JavaScript (assuming you
code correctly)
• jQuery's "each" method is great for looping, but using a native "for" statement
will always be an ounce quicker
ECMAScript
• ECMAScript (or ES) is a trademarked scripting-language specification
standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was
created to standardize JavaScript
• It specifies how a scripting language should look like.
• Releasing a new edition of ECMAScript does not mean that all JavaScript engines
in existence suddenly have those new features
• ECMAScript compatibility table
• Few of ES6 features
• default + rest + spread
• let + const
• iterators + for..of
• generators
• unicode
• arrows
• classes
• enhanced object literals
• template strings
• destructuring
Some ECMA implementations
page was last edited on 21 December 2017, at 03:02.
TypeScript
• An open-source programming language developed and maintained by Microsoft
• Superset of JavaScript that compiles to plain JavaScript.
• It offers classes, modules, and interfaces to help you build robust components
• Advantages
– Early Error Detection
– Large App Capabilities
– The ECMAScript Factor
– ‘Safer’ Refactoring
Library
• An entire toolkit which highly abstracts different layers, like browsers / DOM
models / etc
• It offers a lot of tools and neat stuff to work with, which in general, simplify your
coding experience
• A library offers functions to be called by its parent code
• Examples
– jQuery
– MooTools
– YUI
– Custom third party libraries
Minification
• Performed after the code for a web application is written, but before the application
is deployed
• When a user requests a webpage, the minified version is sent instead of the full
version, resulting in faster response times and lower bandwidth costs
• Analyze and rewrite the text-based parts of a website to reduce its overall file size
• Minification extends to scripts, style sheets, and other components that the web
browser uses to render the site
• Examples:
– YUI Compressor
– Google Closure Compiler
– JSMin
– Packer
– Dojo ShrinkSafe
Gzipping
• Gzipping finds all repetitive strings and replaces them with pointers to the first
instance of that string
• Servers support compressions as well
• Tools
– gzip
– YUI Compressor
– Apache
Linting
• Linting is the process of running a program that will analyze code for potential
errors
• Check whether the JS code is compliant with good coding practices
• Will warn you when the code uses any questionable language feature or any
feature in a questionable manner
• Recommended for all JS programmers because the language is actually that
dangerous
• Examples
– ESLint
– JSLint
– JSHint
– JSCS
Frameworks
• A framework defines the entire application design
• Describes a given structure of "how" you should present your code
• A developer does not call a framework, instead it is the framework that will call
and use the code in some particular way
• Examples
– Angular - Complex front end application that need just one modular framework for everything
– React
– Ember
– Babylon
JavaScript run-time environment
• The runtime environment provides the built-in libraries that are available to the
program at runtime (during execution)
– Web Browsers
– Node.js
• Node and web browsers, both executes JavaScript, but Node does that in server
side and browsers in client side
• What Can Node.js Do?
– Generate dynamic page content
– Create, open, read, write, delete, and close files on the server
– Collect form data
– Add, delete, modify data in database
Has run time environments
JavaScript Package Managers
• Responsibilities
– Project Dependencies
– Version Control
– Metadata
– Flat vs. Nested Dependency Structure
– Deterministic vs. Non-deterministic
dependency installation
• Examples
– NPM
– Yarn
– Bower
– JSPM
– Duo
Development IDEs / Editors
• Most used IDEs
– Visual Studio Code
– Atom
– Sublime
– WebStorm
• Sublime or Atom you might need to setup Babel and ESLint separately
• WebStorm comes with those out of the box. It also comes with a pretty powerful
code inspection and intelligent code completion system. But not free
VSCode
Pros
• JavaScript IntelliSense support
• Extendable through plugins
• TypeScript integration
• Embedded Git control
• Integrated debugging 
• Ready to use out of the box
• Extensions (aka plugins) are written in JavaScript
• Integrated terminal
• Great performance
• Updated frequently
• ESLint integration
• Active development
• Libre/open source
• Huge community behind it
• Fast and powerful
• Inline definition picking and usages finding
• JS typechecking
Cons
• The autocomplete and code check is not as
powerful as the one on WebStorm
• Project search limits results
• Embedded Git isn't powerful enough
• Very bad auto import
• No support for tiled/grid editor layouts
• Slow launch time
• Is not an IDE, is a text editor
• File search is extremely slow
References
• https://en.wikipedia.org/wiki/Best_coding_practices#Code_building
• https://www.codementor.io/learn-development/what-makes-good-software-
architecture-101
• https://www.w3.org/wiki/JavaScript_best_practices
• https://code.tutsplus.com/tutorials/24-javascript-best-practices-for-beginners--net-
5399
• https://github.com/ryanmcdermott/clean-code-javascript
• https://en.wikipedia.org/wiki/ECMAScript
• https://www.w3schools.com/
• https://en.wikipedia.org/wiki/JSLint
Thank you…

More Related Content

What's hot (20)

PDF
Angular
Lilia Sfaxi
 
PPTX
React Native
ASIMYILDIZ
 
PDF
Web Components Everywhere
Ilia Idakiev
 
PPTX
Why TypeScript?
FITC
 
PPTX
Introducing ASP.NET Core 2.0
Steven Smith
 
PPTX
Typescript ppt
akhilsreyas
 
PDF
Lets make a better react form
Yao Nien Chung
 
PPT
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
PDF
An introduction to React.js
Emanuele DelBono
 
PPTX
Angular 2.0 Dependency injection
Eyal Vardi
 
PPTX
Css floats
Webtech Learning
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
ODP
History of JavaScript
Rajat Saxena
 
PPTX
Une introduction à Javascript et ECMAScript 6
Jean-Baptiste Vigneron
 
PPTX
Angular Data Binding
Jennifer Estrada
 
PPTX
Domain-Driven Design
Andriy Buday
 
PPTX
Behavior driven development (bdd)
Rohit Bisht
 
PPT
ASP.NET MVC Presentation
ivpol
 
PDF
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
PPTX
Html5 and-css3-overview
Jacob Nelson
 
Angular
Lilia Sfaxi
 
React Native
ASIMYILDIZ
 
Web Components Everywhere
Ilia Idakiev
 
Why TypeScript?
FITC
 
Introducing ASP.NET Core 2.0
Steven Smith
 
Typescript ppt
akhilsreyas
 
Lets make a better react form
Yao Nien Chung
 
Angular Introduction By Surekha Gadkari
Surekha Gadkari
 
An introduction to React.js
Emanuele DelBono
 
Angular 2.0 Dependency injection
Eyal Vardi
 
Css floats
Webtech Learning
 
Introduction into ES6 JavaScript.
boyney123
 
History of JavaScript
Rajat Saxena
 
Une introduction à Javascript et ECMAScript 6
Jean-Baptiste Vigneron
 
Angular Data Binding
Jennifer Estrada
 
Domain-Driven Design
Andriy Buday
 
Behavior driven development (bdd)
Rohit Bisht
 
ASP.NET MVC Presentation
ivpol
 
Design Patterns Presentation - Chetan Gole
Chetan Gole
 
Html5 and-css3-overview
Jacob Nelson
 

Similar to Javascript best practices (20)

PPTX
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
PPTX
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
PDF
Apache Drill (ver. 0.2)
Camuel Gilyadov
 
PPTX
Welcome to React.pptx
PraveenKumar680401
 
PDF
Meetup. Technologies Intro for Non-Tech People
IT Arena
 
PDF
Let's Write Better Node Modules
Kevin Whinnery
 
PPT
Comp102 lec 3
Fraz Bakhsh
 
KEY
25 Real Life Tips In Ruby on Rails Development
Belighted
 
PPTX
Autoframework design
Forge Events
 
PPTX
Intro to Microsoft.NET
rchakra
 
PPTX
WTA-MODULE-4.pptx
ChayapathiAR
 
PPTX
.net Based Component Technologies
prakashk453625
 
PPT
Introduction to JavaScript
Andres Baravalle
 
PDF
Building iOS App Project & Architecture
Massimo Oliviero
 
PPTX
Frameworks Galore: A Pragmatic Review
netc2012
 
PDF
Instagram filters (8 24)
Ivy Rueb
 
PPTX
Full stack development using javascript what and why - ajay chandravadiya
ajayrcgmail
 
PPTX
Best Practices for Building WordPress Applications
Taylor Lovett
 
PPTX
TypeScript and Angular2 (Love at first sight)
Igor Talevski
 
PPT
JAVA object oriented programming (oop).ppt
AliyaJav
 
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Apache Drill (ver. 0.2)
Camuel Gilyadov
 
Welcome to React.pptx
PraveenKumar680401
 
Meetup. Technologies Intro for Non-Tech People
IT Arena
 
Let's Write Better Node Modules
Kevin Whinnery
 
Comp102 lec 3
Fraz Bakhsh
 
25 Real Life Tips In Ruby on Rails Development
Belighted
 
Autoframework design
Forge Events
 
Intro to Microsoft.NET
rchakra
 
WTA-MODULE-4.pptx
ChayapathiAR
 
.net Based Component Technologies
prakashk453625
 
Introduction to JavaScript
Andres Baravalle
 
Building iOS App Project & Architecture
Massimo Oliviero
 
Frameworks Galore: A Pragmatic Review
netc2012
 
Instagram filters (8 24)
Ivy Rueb
 
Full stack development using javascript what and why - ajay chandravadiya
ajayrcgmail
 
Best Practices for Building WordPress Applications
Taylor Lovett
 
TypeScript and Angular2 (Love at first sight)
Igor Talevski
 
JAVA object oriented programming (oop).ppt
AliyaJav
 
Ad

Recently uploaded (20)

DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Introduction to Probability(basic) .pptx
purohitanuj034
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Introduction to Probability(basic) .pptx
purohitanuj034
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Ad

Javascript best practices

  • 1. JavaScript Best Practices Jayanga V. Liyanage Senior Software Engineer email: [email protected]
  • 2. Producing Good Software Superior coding techniques and good programming practices are hallmarks of a professional programmer
  • 3. Characteristics of good software • Functional • Measurable • Robust • Debuggable • Maintainable • Reusable • Extensible Best Practices
  • 4. What are the best practices • Best coding practices are a set of informal rules that the software development community has learned over time which can help improve the quality of software
  • 5. List of best practices 1. Place scripts at the bottom of the Page 2. Readable and meaningful variable and function names 3. Comment as much as needed but not more 4. Avoid global variables 5. Namespace your JavaScript 6. Beware of “var” 7. Use === Instead of ==
  • 6. List of best practices cont… 8. Avoid use of Eval 9. Don't pass a String to “SetInterval” or “SetTimeOut” 10. Don't use short-hand 11. Keep DOM access to a minimum 12. Optimize loops 13. Avoid mixing with other technologies 14. Use shortcut notation when it makes sense
  • 7. List of best practices cont… 15. Avoid heavy nesting 16. Optimizing content for different browsers properly 17. Do not trust any data 18. Be cautious when creating too much content with JavaScript 19. Use self executing functions 20. Allow for configuration and translation 21. One function per task 22. Raw JavaScript can always be quicker than using a library
  • 8. Place scripts at the bottom of the Page • The primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded
  • 9. Readable and meaningful variable and function names Readable naming gives a clear idea what the code portion is ought to do Avoid – e1 – xbqne – incrementorForMainLoopWhichSpansFromTenToTwenty – getIntegerElements() Do – employee – counter – MAX_CART_SIZE
  • 10. Comment as much as needed but not more – Comments let other developers to understand the purpose and functionality of a code – But over commenting only increase the line numbers and file size No comments Over comments
  • 11. Avoid global variables • Every JavaScript file included in the page runs in the same scope • If scripts included after the global variable, which contains the same variable name and function names will overwrite it
  • 12. Namespace your JavaScript • Your JavaScript shouldn't be floating off in the global namespace, where it collides with other stuff you've included • Although JavaScript doesn't have built-in notions of namespaces, its object model is flexible enough that you can emulate them All the functions are in global scope Functions are encapsulated using a namespace
  • 13. Beware of “var” • Can be assign any type of data to the variables • Always be cautious what type of data is assigned to the variable
  • 14. Use === / !== instead of == / != • JavaScript utilizes two different kinds of equality operators: === | !== and == | !=
  • 15. Avoid use of Eval • Improper use of eval opens up your code for injection attacks • Debugging can be more challenging (no line numbers, etc.) • eval code executes slower
  • 16. Don't pass a String to "SetInterval" or "SetTimeOut" • String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code • Will execute in the same way as eval (global scope) • Pass a function instead of string Ex: setInterval(someFunction, 3000)
  • 17. Don't use short-hand • Technically, you can get away with omitting curly braces and semi-colons • The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic Omit braces and semicolon Actual result
  • 18. Keep DOM access to a minimum • The DOM is a very complex API and rendering in browsers can take up a lot of time • Accessing the DOM in browsers is very expensive • Access DOM only when necessary Access DOM through out the loop Access DOM only once
  • 19. Optimize loops • Loops can become very slow if they are not optimized properly • Keep computation-heavy code outside loops – This includes regular expressions and more importantly DOM manipulation – It is ok to create the DOM nodes in the loop but avoid inserting them into the document Always accessing the array length Accessing the array length only once (Optimized)
  • 20. Avoid mixing with other technologies • Whilst it is possible to create everything you need in a document using JavaScript and the DOM it is not necessarily the most effective way Applying css directly Add css class
  • 21. Use shortcut notation when it makes sense • It keeps the code small and simple
  • 22. Avoid heavy nesting • Nesting code explains its logic and makes it much easier to read, however nesting it too far can also make it hard to follow what you are trying to do Heavy nesting Use separate functions
  • 23. Optimizing content for different browsers • Writing code specific to a certain browser makes it hard to maintain and make it get up to date really quickly • Optimizing content for different browsers properly make it easier to maintain and guarantee the stability Detect feature availability Version compatibility check
  • 24. Do not trust any data • Make sure that all the data that goes into the systems is clean and exactly what it expects • This is most important on the back end when writing out parameters retrieved from the URL. In JavaScript, it is very important to test the type of parameters sent to your functions • Users can mistakenly or purposefully enter invalid data Will fail if not an array Check data type
  • 25. Be cautious when creating too much content with JavaScript • Building a lot of HTML in JavaScript can be pretty daunting and flaky • Internet Explorer can run into all kinds of trouble by altering the document while it is still loading and manipulating the content with innerHTML • Not every maintainer will have the same level of skill as you have and could potentially really mess with your code • Content creation depends on the nature of the project you are working on – Static content – Dynamic content loading (Ajax or PHP requests) – Projects which use separate templates (Use ajax for template loading) – Libraries and projects with dynamic content
  • 26. Use self executing functions • Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called
  • 27. Allow for configuration and translation • To make the code maintainable and clean, create a configuration object that contains all the things that are likely to change over time • These include any text used in elements you create (including button values and alternative text for images), CSS class and ID names and general parameters of the interface you build
  • 28. One function per task • Make sure that you create functions that fulfill one job at a time. • This will make it easy for other developers to debug and change your code without having to scan through all the code to work out what code block performs what function • If you find yourself doing the same thing in several different functions then it is a good idea to create a more generic helper function instead, and reuse that functionality where it is needed
  • 29. Raw JavaScript can always be quicker than using a library • JavaScript libraries, such as jQuery and Mootools, can save an enormous amount of time when coding -- especially with AJAX operations. Having said that, always keep in mind that a library can never be as fast as raw JavaScript (assuming you code correctly) • jQuery's "each" method is great for looping, but using a native "for" statement will always be an ounce quicker
  • 30. ECMAScript • ECMAScript (or ES) is a trademarked scripting-language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript • It specifies how a scripting language should look like. • Releasing a new edition of ECMAScript does not mean that all JavaScript engines in existence suddenly have those new features • ECMAScript compatibility table • Few of ES6 features • default + rest + spread • let + const • iterators + for..of • generators • unicode • arrows • classes • enhanced object literals • template strings • destructuring
  • 31. Some ECMA implementations page was last edited on 21 December 2017, at 03:02.
  • 32. TypeScript • An open-source programming language developed and maintained by Microsoft • Superset of JavaScript that compiles to plain JavaScript. • It offers classes, modules, and interfaces to help you build robust components • Advantages – Early Error Detection – Large App Capabilities – The ECMAScript Factor – ‘Safer’ Refactoring
  • 33. Library • An entire toolkit which highly abstracts different layers, like browsers / DOM models / etc • It offers a lot of tools and neat stuff to work with, which in general, simplify your coding experience • A library offers functions to be called by its parent code • Examples – jQuery – MooTools – YUI – Custom third party libraries
  • 34. Minification • Performed after the code for a web application is written, but before the application is deployed • When a user requests a webpage, the minified version is sent instead of the full version, resulting in faster response times and lower bandwidth costs • Analyze and rewrite the text-based parts of a website to reduce its overall file size • Minification extends to scripts, style sheets, and other components that the web browser uses to render the site • Examples: – YUI Compressor – Google Closure Compiler – JSMin – Packer – Dojo ShrinkSafe
  • 35. Gzipping • Gzipping finds all repetitive strings and replaces them with pointers to the first instance of that string • Servers support compressions as well • Tools – gzip – YUI Compressor – Apache
  • 36. Linting • Linting is the process of running a program that will analyze code for potential errors • Check whether the JS code is compliant with good coding practices • Will warn you when the code uses any questionable language feature or any feature in a questionable manner • Recommended for all JS programmers because the language is actually that dangerous • Examples – ESLint – JSLint – JSHint – JSCS
  • 37. Frameworks • A framework defines the entire application design • Describes a given structure of "how" you should present your code • A developer does not call a framework, instead it is the framework that will call and use the code in some particular way • Examples – Angular - Complex front end application that need just one modular framework for everything – React – Ember – Babylon
  • 38. JavaScript run-time environment • The runtime environment provides the built-in libraries that are available to the program at runtime (during execution) – Web Browsers – Node.js • Node and web browsers, both executes JavaScript, but Node does that in server side and browsers in client side • What Can Node.js Do? – Generate dynamic page content – Create, open, read, write, delete, and close files on the server – Collect form data – Add, delete, modify data in database Has run time environments
  • 39. JavaScript Package Managers • Responsibilities – Project Dependencies – Version Control – Metadata – Flat vs. Nested Dependency Structure – Deterministic vs. Non-deterministic dependency installation • Examples – NPM – Yarn – Bower – JSPM – Duo
  • 40. Development IDEs / Editors • Most used IDEs – Visual Studio Code – Atom – Sublime – WebStorm • Sublime or Atom you might need to setup Babel and ESLint separately • WebStorm comes with those out of the box. It also comes with a pretty powerful code inspection and intelligent code completion system. But not free
  • 41. VSCode Pros • JavaScript IntelliSense support • Extendable through plugins • TypeScript integration • Embedded Git control • Integrated debugging  • Ready to use out of the box • Extensions (aka plugins) are written in JavaScript • Integrated terminal • Great performance • Updated frequently • ESLint integration • Active development • Libre/open source • Huge community behind it • Fast and powerful • Inline definition picking and usages finding • JS typechecking Cons • The autocomplete and code check is not as powerful as the one on WebStorm • Project search limits results • Embedded Git isn't powerful enough • Very bad auto import • No support for tiled/grid editor layouts • Slow launch time • Is not an IDE, is a text editor • File search is extremely slow
  • 42. References • https://en.wikipedia.org/wiki/Best_coding_practices#Code_building • https://www.codementor.io/learn-development/what-makes-good-software- architecture-101 • https://www.w3.org/wiki/JavaScript_best_practices • https://code.tutsplus.com/tutorials/24-javascript-best-practices-for-beginners--net- 5399 • https://github.com/ryanmcdermott/clean-code-javascript • https://en.wikipedia.org/wiki/ECMAScript • https://www.w3schools.com/ • https://en.wikipedia.org/wiki/JSLint