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

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 

Último (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 

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