SlideShare uma empresa Scribd logo
1 de 9
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For LoopSukrit Gupta
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programmingPrabhu Govind
 
C++ Programming - 5th Study
C++ Programming - 5th StudyC++ Programming - 5th Study
C++ Programming - 5th StudyChris Ohk
 
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 2alish sha
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)yap_raiza
 
Looping Statement And Flow Chart
 Looping Statement And Flow Chart Looping Statement And Flow Chart
Looping Statement And Flow ChartRahul Sahu
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingSabik T S
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8REHAN IJAZ
 
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 AnalyzerAndrey Karpov
 
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 cmohdshanu
 

Mais procurados (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
 

Semelhante a Things to avoid in JavaScript

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; jumpingMomenMostafa
 
JavaScript Basics And DOM Manipulation
JavaScript Basics And DOM ManipulationJavaScript Basics And DOM Manipulation
JavaScript Basics And DOM ManipulationSiarhei Barysiuk
 
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.docxjacksnathalie
 
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.pdfmeerobertsonheyde608
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By LuckStop Programming in JavaScript By Luck
Stop Programming in JavaScript By Lucksergioafp
 
Javascript Common Mistakes
Javascript Common MistakesJavascript Common Mistakes
Javascript Common Mistakes동수 장
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIAtsushi Tadokoro
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developersbrweber2
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using CBilal Mirza
 
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.pdfallystraders
 
C programs
C programsC programs
C programsMinu S
 

Semelhante a 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
 

Mais de Brian Moschel

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 LibrariesBrian Moschel
 
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 JabbifyBrian Moschel
 
Comet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceComet, Simplified, with Jabbify Comet Service
Comet, Simplified, with Jabbify Comet ServiceBrian Moschel
 
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 JAXERBrian Moschel
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsBrian Moschel
 
Basic inheritance in JavaScript
Basic inheritance in JavaScriptBasic inheritance in JavaScript
Basic inheritance in JavaScriptBrian Moschel
 

Mais de 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
 

Último

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 

Último (20)

Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 

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