SlideShare a Scribd company logo
1 of 22
JavaScript Gotchas
Recommendations
Pierre Nallet
www.javascriptgotchas.com
A good return
return ;
return x;
return {
x:2
};
Always terminate
statements with ;
Start the returned
expression on the same
line
switch and break
switch(dayOfWeek)
{
case 0: ... break;
case 1: case 2: return something;
...
default: throw new Error("invalid arg");
}
End your case statements
with break ...
… or return
Consider adding a default case
Don't let blocks block you
if (condition) doSomething();
doSomethingElse();
Consider one line if statements
if (condition){
doSomething();
}
doSomethingElse();
Consider adding braces
The old parseInt
parseInt("010", 10) // 10
parseFloat("010") // 10
Number("010") // 10
Always specify radix in parseInt
Consider using
parseFloat or Number
Number imprecision
for(var i = 0; i < 10; i = i + 0.1)
{
...
}
Terminate loops with inequalities, not equalities
var noTruth = 0.3 === 0.1 + 0.2
var truth = close(0.3, 0.1 + 0.2);
Remember number precision problems
Consider using tolerance
Not a number is a number
Remember: isNaN not the same as Number.isNaN
if(isFinite(n)){
// all is good
}
Use isFinite to protect against non finite values
if(isNaN(n)){
// Could be infinite
}
Consider using isNan
Do not write n === NaN
A bad date
var day = date.getDate(); // day of month
var month = date.getMonth() + 1 // month, o
Add 1 since months are zero based
Use getDate to get day of month, not getDay
+
2 + 3
"hello " + name
"the number is " + num // OK
1 + someString // problem
Add items of
the same type
Be careful
when adding
different types
Don't use + on objects
forEach for everyone
array.forEach( function(item) {
// ...
} );
use forEach for array iteration
Do not use for loops on arrays
push your array
myArray.push(post);
if (index < 0 || index >= posts.length) {
throw new Error('Invalid index');
}
posts[index] = post;
Use push to add new items to an array.
Verify array bounds before
writing to arrays via an index
splice, don't delete
var a = [1, 2, 3, 4, 5];
a.splice(2, 1);
// a contains 1,2,4,5
Use array.splice, to remove items from array
Do not delete on arrays
Sorting out array.sort
var numbers = [1, 5, 10]; // [1, 5, 10]
numbers.sort(ascending); // [1, 5, 10]
var ascending = function(x, y){
if (x > y)
return 1;
else if (x < y)
return -1;
return 0;
}
Use sort functions
for sorting arrays
You don't have to use a sort function if the array contains only strings
Arrays vs. dictionaries
var dict = {};
dict.name = value1;
dict.['age'] = value2;
Use empty JavaScript objects for
dictionaries, not arrays
var array = [1,2,3] ;
array[0];
Use only numbers to access array items
All equals are not equal
if (userChoice == "Purchase") {
// should purchase
}
Always be on guard against a missed = sign.
Equality expression is == or ===, not =
More equality is better
Use == and != only when you are sure you compare with the same type
if (x === 0){
//do something
}
Prefer === and !==
over == and !=
null is not undefined
typeof x === "undefined"
a.b === void 0
Checks for undefined
Consider setting valid
variables to null
x == null
Checks for null or
undefined
var p = {name:'Alice', age: null};
Missing the argument
function addToCart(productName, quantity){
if(quantity === void 0) quantity = 1;
…
}
Consider default parameters
var makes a difference
var setup = function (mode) {
var unload = mode === "Production";
// ...
}
Always use var when
declaring variables.
var setup = function (mode) {
window.unload =
// ...
}
Consider using window.
when accessing global
variables
namespaces
var app = app || {}
app.core = app.core || {}
app.core.log = function() {}
// ...
When (potentially) reinitializing a variable, use the ||
syntax.
this and that
function computeSum(array){
this.total = 0;
var that = this;
array.forEach(function(item){
that.total += item;
});
}
Capture this before
reaching callbacks
Stay up to date
www.javascriptgotchas.com

More Related Content

What's hot

Random stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbenchRandom stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbenchKashyap Adodariya
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsqlArun Sial
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentArun Sial
 
The Ring programming language version 1.5.1 book - Part 18 of 180
The Ring programming language version 1.5.1 book - Part 18 of 180The Ring programming language version 1.5.1 book - Part 18 of 180
The Ring programming language version 1.5.1 book - Part 18 of 180Mahmoud Samir Fayed
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
SQL Functions - Oracle SQL Fundamentals
SQL Functions - Oracle SQL FundamentalsSQL Functions - Oracle SQL Fundamentals
SQL Functions - Oracle SQL FundamentalsMuhammadWaheed44
 
PHP Traits
PHP TraitsPHP Traits
PHP Traitsmattbuzz
 
Refatoração + Design Patterns em Ruby
Refatoração + Design Patterns em RubyRefatoração + Design Patterns em Ruby
Refatoração + Design Patterns em RubyCássio Marques
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error HandlingGyooha Kim
 
C lecture 3 control statements slideshare
C lecture 3 control statements slideshareC lecture 3 control statements slideshare
C lecture 3 control statements slideshareGagan Deep
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196Mahmoud Samir Fayed
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksFelipe Prado
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 

What's hot (20)

Random stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbenchRandom stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbench
 
Operators
OperatorsOperators
Operators
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
 
Indeterminate forms
Indeterminate formsIndeterminate forms
Indeterminate forms
 
Database object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab AssignmentDatabase object, sub query, Join Commands & Lab Assignment
Database object, sub query, Join Commands & Lab Assignment
 
The Ring programming language version 1.5.1 book - Part 18 of 180
The Ring programming language version 1.5.1 book - Part 18 of 180The Ring programming language version 1.5.1 book - Part 18 of 180
The Ring programming language version 1.5.1 book - Part 18 of 180
 
PLSQL Note
PLSQL NotePLSQL Note
PLSQL Note
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
SQL Functions - Oracle SQL Fundamentals
SQL Functions - Oracle SQL FundamentalsSQL Functions - Oracle SQL Fundamentals
SQL Functions - Oracle SQL Fundamentals
 
PHP Traits
PHP TraitsPHP Traits
PHP Traits
 
Refatoração + Design Patterns em Ruby
Refatoração + Design Patterns em RubyRefatoração + Design Patterns em Ruby
Refatoração + Design Patterns em Ruby
 
Oracle: Basic SQL
Oracle: Basic SQLOracle: Basic SQL
Oracle: Basic SQL
 
Pure function And Functional Error Handling
Pure function And Functional Error HandlingPure function And Functional Error Handling
Pure function And Functional Error Handling
 
C lecture 3 control statements slideshare
C lecture 3 control statements slideshareC lecture 3 control statements slideshare
C lecture 3 control statements slideshare
 
The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196The Ring programming language version 1.7 book - Part 91 of 196
The Ring programming language version 1.7 book - Part 91 of 196
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliks
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 

Similar to JavaScript gotchas

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General IntroductionThomas Johnston
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxAbhimanyuChaure
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfAlexShon3
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 

Similar to JavaScript gotchas (20)

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Scala idioms
Scala idiomsScala idioms
Scala idioms
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPUR ESC 111M Lec12.pptx
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdfjavascript-variablesanddatatypes-130218094831-phpapp01.pdf
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
 
Arrays
ArraysArrays
Arrays
 
core java
 core java core java
core java
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Namespaces
NamespacesNamespaces
Namespaces
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 

JavaScript gotchas

  • 2. A good return return ; return x; return { x:2 }; Always terminate statements with ; Start the returned expression on the same line
  • 3. switch and break switch(dayOfWeek) { case 0: ... break; case 1: case 2: return something; ... default: throw new Error("invalid arg"); } End your case statements with break ... … or return Consider adding a default case
  • 4. Don't let blocks block you if (condition) doSomething(); doSomethingElse(); Consider one line if statements if (condition){ doSomething(); } doSomethingElse(); Consider adding braces
  • 5. The old parseInt parseInt("010", 10) // 10 parseFloat("010") // 10 Number("010") // 10 Always specify radix in parseInt Consider using parseFloat or Number
  • 6. Number imprecision for(var i = 0; i < 10; i = i + 0.1) { ... } Terminate loops with inequalities, not equalities var noTruth = 0.3 === 0.1 + 0.2 var truth = close(0.3, 0.1 + 0.2); Remember number precision problems Consider using tolerance
  • 7. Not a number is a number Remember: isNaN not the same as Number.isNaN if(isFinite(n)){ // all is good } Use isFinite to protect against non finite values if(isNaN(n)){ // Could be infinite } Consider using isNan Do not write n === NaN
  • 8. A bad date var day = date.getDate(); // day of month var month = date.getMonth() + 1 // month, o Add 1 since months are zero based Use getDate to get day of month, not getDay
  • 9. + 2 + 3 "hello " + name "the number is " + num // OK 1 + someString // problem Add items of the same type Be careful when adding different types Don't use + on objects
  • 10. forEach for everyone array.forEach( function(item) { // ... } ); use forEach for array iteration Do not use for loops on arrays
  • 11. push your array myArray.push(post); if (index < 0 || index >= posts.length) { throw new Error('Invalid index'); } posts[index] = post; Use push to add new items to an array. Verify array bounds before writing to arrays via an index
  • 12. splice, don't delete var a = [1, 2, 3, 4, 5]; a.splice(2, 1); // a contains 1,2,4,5 Use array.splice, to remove items from array Do not delete on arrays
  • 13. Sorting out array.sort var numbers = [1, 5, 10]; // [1, 5, 10] numbers.sort(ascending); // [1, 5, 10] var ascending = function(x, y){ if (x > y) return 1; else if (x < y) return -1; return 0; } Use sort functions for sorting arrays You don't have to use a sort function if the array contains only strings
  • 14. Arrays vs. dictionaries var dict = {}; dict.name = value1; dict.['age'] = value2; Use empty JavaScript objects for dictionaries, not arrays var array = [1,2,3] ; array[0]; Use only numbers to access array items
  • 15. All equals are not equal if (userChoice == "Purchase") { // should purchase } Always be on guard against a missed = sign. Equality expression is == or ===, not =
  • 16. More equality is better Use == and != only when you are sure you compare with the same type if (x === 0){ //do something } Prefer === and !== over == and !=
  • 17. null is not undefined typeof x === "undefined" a.b === void 0 Checks for undefined Consider setting valid variables to null x == null Checks for null or undefined var p = {name:'Alice', age: null};
  • 18. Missing the argument function addToCart(productName, quantity){ if(quantity === void 0) quantity = 1; … } Consider default parameters
  • 19. var makes a difference var setup = function (mode) { var unload = mode === "Production"; // ... } Always use var when declaring variables. var setup = function (mode) { window.unload = // ... } Consider using window. when accessing global variables
  • 20. namespaces var app = app || {} app.core = app.core || {} app.core.log = function() {} // ... When (potentially) reinitializing a variable, use the || syntax.
  • 21. this and that function computeSum(array){ this.total = 0; var that = this; array.forEach(function(item){ that.total += item; }); } Capture this before reaching callbacks
  • 22. Stay up to date www.javascriptgotchas.com