SlideShare a Scribd company logo
1 of 9
Download to read offline
Traps to avoid in JavaScript:
the short list

Vlad Didenko      December 18th, 2008
Global Variables
     <script type=quot;text/javascriptquot;>
        var count;
        // ………Hundreds of lines of code later………
        ………function ( tag ) {
             count = getElementsByTagName( tag );
             ………
        }
     </script>



Name collisions, hard to understand code, extra documentation and
maintenance.

Re-factor, make sure to use «var» in inner scopes.
The quot;+quot; operation
Adds if both operands are
numbers.

Runs toString() on all
operands and concatenates if
one of the operands is not a
number.


   <input id=quot;in1quot; /><input id=quot;in2quot; />
   <button onclick=quot;alert( [ 0, '-' ] +
   getElementById('in1').value + getElementById('in2').value
   );quot;>Add</button>
Default parseInt() base
If string starts with «0», parseInt expects an octal number. As
«9» is not an octal digit, parseInt stops at «0».



      month = parseInt( '09/03/2008'.split( '/' )[0] );

      0



Solution: ALWAYS use explicit base, like in:

          parseInt( value, 10 )
New-line and quot;;quot; insertions
Browsers made to
quot;correctquot; user errors.

Syntax becomes
unpredictable - semicolon
inserted after the «return»
in the example.

Do not begin objects on a
new line as a habit.
Bad scope assumptions
                         var arr = [quot;firstquot;, quot;lastquot;];
Functions DO create
                         var v = 20;
scope.
                         function test(){
                           var v = true;
Other blocks in curly      alert(v);
braces do NOT create     };
scope.                   test();             // true
                         for (i in arr) {
                           var v = arr[i];
This is different from   };
most other languages.    alert( v );         // quot;lastquot;
typeof() ambiguity
             Avoid:                            Use instead:

var a = null; typeof( a );              var a = null; a === null;
quot;objectquot;                                true
var b = [1,2,3]; typeof( b );           Object.prototype.toString.apply( [1,2,3] );
quot;objectquot;                                quot;[object Array]quot;
[ typeof( NaN ), typeof( Infinity ) ];   [ isNaN( NaN ), Infinity === Infinity ]
quot;numberquot;, quot;numberquot;                      true, true
Fun with falsy
NaN, 0, '', false, null, and
undefined evaluate to false in
conditional statements:                                                 undefin
                                 x==y     0   NaN   ''   false   null
                                                                          ed

if ( null || false )
                                               F
                                   0      T         T     T       F       F
  { alert( quot;Truthyquot; ); }
else

✓ { alert( quot;Falsyquot; ); }                        F
                                  NaN     F         F     F       F       F


Be careful, though, when           ''     T         T     T       F       F
                                               F
comparing them to each other:
                                  false   T    F    T     T       F       F
if ( null == false )
  { alert( quot;Expected.quot; ); }
else                              null    F    F    F     F       T       T

✓ { alert( quot;Gotcha!!!quot; ) };
                                 undefin
                                          F    F    F     F       T       T
Use the «===» operator !           ed
O'REILLY MEDIA, INC.
MAY 2008
ISBN-10: 0596517742
ISBN-13: 978-0596517748




JavaScript: The Good Parts
by Douglas Crockford

More Related Content

What's hot

Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
alish sha
 

What's hot (20)

C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For Loop
 
Arm code arduino
Arm code arduinoArm code arduino
Arm code arduino
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
 
For Loop
For LoopFor Loop
For Loop
 
Mauro yaguachi
Mauro yaguachiMauro yaguachi
Mauro yaguachi
 
2 data and c
2 data and c2 data and c
2 data and c
 
C++ Programming - 5th Study
C++ Programming - 5th StudyC++ Programming - 5th Study
C++ Programming - 5th Study
 
C programming
C programmingC programming
C programming
 
Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2Dti2143 chap 4 control statement part 2
Dti2143 chap 4 control statement part 2
 
First c program
First c programFirst c program
First c program
 
Loops in c
Loops in cLoops in c
Loops in c
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Looping Statement And Flow Chart
 Looping Statement And Flow Chart Looping Statement And Flow Chart
Looping Statement And Flow Chart
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
02 Jo P Feb 07
02 Jo P Feb 0702 Jo P Feb 07
02 Jo P Feb 07
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
 
Positive (2)
Positive (2)Positive (2)
Positive (2)
 
Checking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static AnalyzerChecking Wine with PVS-Studio and Clang Static Analyzer
Checking Wine with PVS-Studio and Clang Static Analyzer
 
Tu1
Tu1Tu1
Tu1
 
print even or odd number in c
print even or odd number in cprint even or odd number in c
print even or odd number in c
 

Similar to Things to avoid in JavaScript

E1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docxE1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docx
jacksnathalie
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdf
meerobertsonheyde608
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
mrkurt
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
Atsushi Tadokoro
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
allystraders
 
C programs
C programsC programs
C programs
Minu S
 

Similar to Things to avoid in JavaScript (20)

Presentation1
Presentation1Presentation1
Presentation1
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping
 
JavaScript Basics And DOM Manipulation
JavaScript Basics And DOM ManipulationJavaScript Basics And DOM Manipulation
JavaScript Basics And DOM Manipulation
 
E1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docxE1 – FundamentalsPlease refer to announcements for details about.docx
E1 – FundamentalsPlease refer to announcements for details about.docx
 
My C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdfMy C proggram is having trouble in the switch in main. Also the a co.pdf
My C proggram is having trouble in the switch in main. Also the a co.pdf
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Binary tree
Binary treeBinary tree
Binary tree
 
Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By LuckStop Programming in JavaScript By Luck
Stop Programming in JavaScript By Luck
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
C lab manaual
C lab manaualC lab manaual
C lab manaual
 
Javascript Common Mistakes
Javascript Common MistakesJavascript Common Mistakes
Javascript Common Mistakes
 
C tutorial
C tutorialC tutorial
C tutorial
 
Perl_Part2
Perl_Part2Perl_Part2
Perl_Part2
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
 
C programs
C programsC programs
C programs
 

More from Brian Moschel

Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet Service
Brian Moschel
 

More from Brian Moschel (12)

A Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC LibrariesA Very Biased Comparison of MVC Libraries
A Very Biased Comparison of MVC Libraries
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
Bottom Up
Bottom UpBottom Up
Bottom Up
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Comet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called JabbifyComet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called Jabbify
 
Web 2.0 Expo Notes
Web 2.0 Expo NotesWeb 2.0 Expo Notes
Web 2.0 Expo Notes
 
Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet Service
 
Building an App with jQuery and JAXER
Building an App with jQuery and JAXERBuilding an App with jQuery and JAXER
Building an App with jQuery and JAXER
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Ajax3
Ajax3Ajax3
Ajax3
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScript
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Things to avoid in JavaScript

  • 1. Traps to avoid in JavaScript: the short list Vlad Didenko December 18th, 2008
  • 2. Global Variables <script type=quot;text/javascriptquot;> var count; // ………Hundreds of lines of code later……… ………function ( tag ) { count = getElementsByTagName( tag ); ……… } </script> Name collisions, hard to understand code, extra documentation and maintenance. Re-factor, make sure to use «var» in inner scopes.
  • 3. The quot;+quot; operation Adds if both operands are numbers. Runs toString() on all operands and concatenates if one of the operands is not a number. <input id=quot;in1quot; /><input id=quot;in2quot; /> <button onclick=quot;alert( [ 0, '-' ] + getElementById('in1').value + getElementById('in2').value );quot;>Add</button>
  • 4. Default parseInt() base If string starts with «0», parseInt expects an octal number. As «9» is not an octal digit, parseInt stops at «0». month = parseInt( '09/03/2008'.split( '/' )[0] ); 0 Solution: ALWAYS use explicit base, like in: parseInt( value, 10 )
  • 5. New-line and quot;;quot; insertions Browsers made to quot;correctquot; user errors. Syntax becomes unpredictable - semicolon inserted after the «return» in the example. Do not begin objects on a new line as a habit.
  • 6. Bad scope assumptions var arr = [quot;firstquot;, quot;lastquot;]; Functions DO create var v = 20; scope. function test(){ var v = true; Other blocks in curly alert(v); braces do NOT create }; scope. test(); // true for (i in arr) { var v = arr[i]; This is different from }; most other languages. alert( v ); // quot;lastquot;
  • 7. typeof() ambiguity Avoid: Use instead: var a = null; typeof( a ); var a = null; a === null; quot;objectquot; true var b = [1,2,3]; typeof( b ); Object.prototype.toString.apply( [1,2,3] ); quot;objectquot; quot;[object Array]quot; [ typeof( NaN ), typeof( Infinity ) ]; [ isNaN( NaN ), Infinity === Infinity ] quot;numberquot;, quot;numberquot; true, true
  • 8. Fun with falsy NaN, 0, '', false, null, and undefined evaluate to false in conditional statements: undefin x==y 0 NaN '' false null ed if ( null || false ) F 0 T T T F F { alert( quot;Truthyquot; ); } else ✓ { alert( quot;Falsyquot; ); } F NaN F F F F F Be careful, though, when '' T T T F F F comparing them to each other: false T F T T F F if ( null == false ) { alert( quot;Expected.quot; ); } else null F F F F T T ✓ { alert( quot;Gotcha!!!quot; ) }; undefin F F F F T T Use the «===» operator ! ed
  • 9. O'REILLY MEDIA, INC. MAY 2008 ISBN-10: 0596517742 ISBN-13: 978-0596517748 JavaScript: The Good Parts by Douglas Crockford