SlideShare a Scribd company logo
1 of 37
Stop Programming JavaScript by Luck Iowa Code Camp November 7th 2009 Sergio Pereira 	sergio@sergiopereira.com 	http://sergiopereira.com/blog 	@sergiopereira
null vs. undefined Same thing, right?
null vs. undefined They're Different things
null vs. undefined null varparentNode = null; bartSimpson.homeState = null; null is intentional
null vs. undefined undefined var list = ['a', 'b', 'c']; list[3]  undefined function echo(p1, p2, p3){ return [p1, p2, p3]; } echo(11, 22)  [11, 22, undefined]
null vs. undefined undefined var list; list  undefined list = ['a', 'b', 'c']; list.length 3 list.count undefined list['count']  undefined Omission or mistake
null vs. undefined undefined vs.  not declared var list, obj = new Object(); alert(list)  undefined alert(obj.bogusProp)  undefined alert(bogusVar) error! alert(typeof list)  undefined alert(typeofbogusVar)  undefined
== , !=, ===, !== Triple equals? Seriously?
== , !=, ===, !== Watch out for  Type Coercion
== , !=, ===, !==  0 == falsetrue!  0 == ''true!  0 == '0'true! '' == '0' false     1 == true true!   100 == true  false     1 == '1'true! '1' == true true! '100' == true  false undefined == nulltrue!
== , !=, ===, !==  0 === false false  0 === '' false  0 === '0' false '' === '0' false     1 === true  false   100 === true  false     1 === '1' false '1' === true  false '100' === true  false undefined === null false
Boolean Expressions Any expression will resolve  to a boolean value if( someValue ){   alert(someValue + 'resolved to true'); } else {   alert(someValue + 'resolved to false'); }
Boolean Expressions Truthy and Falsy Values that resolve to false false, 0, null,  undefined, NaN, '' They're Falsy
Boolean Expressions Truthy and Falsy Values that resolve to true Everything else
Boolean Expressions Truthy and Falsy true, new Object(), 123, 'any string', 'false', '0' They're Truthy
Variable scope: function if(condition){ var v1 = 123; // ... while(something){ var v2 = getNext(); // ...   } } alert(v1 + v2); Watch out for bugs
Variable scope: function function print(price){ var tax = computeTaxes(price); function format(number){ var dot = decSeparator(); // ... tax visible here   } // ... dotnot visible here return format(price + tax); }
Variables: don't forget var function getTotal(items){   weight = getTotalWeight(items);   sum = 0; for(i=0; i<items.length; i++){     sum += items[i].price;   } shipCost = getShipCost(weight);   return sum + shipCost; }
Variables: don't forget var function getTotal(items){ var weight = getTotalWeight(items); var sum = 0; for(vari=0; i<items.length; i++){     sum += items[i].price;   } varshipCost = getShipCost(weight);   return sum + shipCost; }
Functions rock in JS They are 1st class objects Assigned to variables Passed to other functions Return value of other functions They have properties They have methods
Function Overloads Now that's a best practice!
Function Overloads JavaScript doesn't have function overloads
Function Overloads functionshowMessage(msg){ showMessage(msg, false); } functionshowMessage(msg, isHtml){ if(isHtml) { 		$('#message').html(msg); 	} else { 		$('#message').text(msg); 	} } showMessage('plain text'); showMessage('<b>formatted</b>');
The problem with this Declarations  and  Call Sites
The problem with this A Simple Function function echo(p1, p2){ return [this, p1, p2]; } A Simple Invocation echo(10, 20)  [window, 10, 20]
The problem with this Method Invocation function echo(p1, p2){ return [this, p1, p2]; } var repeater = new Object(); repeater.getData = echo; repeater.getData('a', 'b');   [repeater, 'a', 'b']
The problem with this Call/Apply function echo(p1, p2){ return [this, p1, p2]; } var today = new Date(); echo.call(today, 'a', 'b');   [today, 'a', 'b']  echo.apply(today, ['a', 'b']);   [today, 'a', 'b']
The problem with this Constructors functionFaderEffect(element, duration){ this.target = element; this.duration = duration; this.start = function() { //...snip     } } var effect = newFaderEffect();
The problem with this 5 Ways to Call A Function echo(10, 20); repeater.getData('a', 'b');  echo.call(today, 'a', 'b');  echo.apply(today, ['a', 'b']);  var effect = newFaderEffect(); 5 Bindings FOR this
Some Advice
The DOM IS scary Use a good library
Parsing numbers: Specify the radix parseInt('182')    182 parseInt('0182')   1 parseInt('0x182')  386 parseInt('09')     0 parseInt('182', 10)    182 parseInt('0182', 10)   182 parseInt('0x182', 16)  386 parseInt('09', 10)     9 parseInt('1101', 2)    13
Careful with Dates new Date()              right now new Date(2009, 11, 25)  Xmas 2009 new Date(2009, 12, 25)  Jan 25th 2010 new Date('11/10/2009')  Nov 10th 2009
Any good books?
Yes, the newer ones
if(questions){     // or comments }
Thanks! Don't forget to fill the evaluation forms Sergio Pereira,  sergio@sergiopereira.com sergiopereira.com/blog Twitter: @sergiopereira

More Related Content

What's hot

[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronasFilipe Ximenes
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd StudyChris Ohk
 
Arduino light tracking code with 4 stepper motors
Arduino light tracking code with 4 stepper motorsArduino light tracking code with 4 stepper motors
Arduino light tracking code with 4 stepper motorsJeff Apol
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th StudyChris Ohk
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It CooleddieSullivan
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScriptBrian Moschel
 
Array using recursion
Array using recursionArray using recursion
Array using recursionSwarup Boro
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2sajidpk92
 
Desenvolvendo em php cli
Desenvolvendo em php cliDesenvolvendo em php cli
Desenvolvendo em php cliThiago Paes
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd StudyChris Ohk
 
Regular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And BeyondRegular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And BeyondMax Shirshin
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06Hassen Poreya
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsP3 InfoTech Solutions Pvt. Ltd.
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsLeonardo Soto
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a numberSwarup Boro
 

What's hot (20)

[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd Study
 
Arduino light tracking code with 4 stepper motors
Arduino light tracking code with 4 stepper motorsArduino light tracking code with 4 stepper motors
Arduino light tracking code with 4 stepper motors
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It Cool
 
Cs project
Cs projectCs project
Cs project
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2
 
Desenvolvendo em php cli
Desenvolvendo em php cliDesenvolvendo em php cli
Desenvolvendo em php cli
 
Lecture05
Lecture05Lecture05
Lecture05
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
 
Regular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And BeyondRegular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And Beyond
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
 
Python Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical OperatorsPython Programming Essentials - M11 - Comparison and Logical Operators
Python Programming Essentials - M11 - Comparison and Logical Operators
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
 
Program to find factorial of a number
Program to find factorial of a numberProgram to find factorial of a number
Program to find factorial of a number
 

Viewers also liked

T.j.letterofrecommendation-1
T.j.letterofrecommendation-1T.j.letterofrecommendation-1
T.j.letterofrecommendation-1Tyler Gossard
 
Luigi Giubbolini | Time/Space-Probing Interferometer for Plasma Diagnostics
Luigi Giubbolini  | Time/Space-Probing Interferometer for Plasma DiagnosticsLuigi Giubbolini  | Time/Space-Probing Interferometer for Plasma Diagnostics
Luigi Giubbolini | Time/Space-Probing Interferometer for Plasma DiagnosticsLuigi Giubbolini
 
Industry Keynote at Large Scale Testing Workshop 2015
Industry Keynote at Large Scale Testing Workshop 2015Industry Keynote at Large Scale Testing Workshop 2015
Industry Keynote at Large Scale Testing Workshop 2015Wolfgang Gottesheim
 
Експорт як бізнес. Снітівкер
Експорт як бізнес. СнітівкерЕкспорт як бізнес. Снітівкер
Експорт як бізнес. Снітівкерmaturqirim
 
Mindanao Church Planting Mission of Churches of Christ
Mindanao Church Planting Mission of Churches of ChristMindanao Church Planting Mission of Churches of Christ
Mindanao Church Planting Mission of Churches of ChristOrlando Calimpitan
 
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...iosrjce
 
Використання інформаційно-комунікативних технологій на уроках історії для роз...
Використання інформаційно-комунікативних технологій на уроках історії для роз...Використання інформаційно-комунікативних технологій на уроках історії для роз...
Використання інформаційно-комунікативних технологій на уроках історії для роз...Ирина Дерусова
 
Ariana Y Brian
Ariana Y BrianAriana Y Brian
Ariana Y Brianadoynan
 
Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)Marcel Aponte
 
Webinar Bridging The Experience Gap
Webinar Bridging The Experience GapWebinar Bridging The Experience Gap
Webinar Bridging The Experience GapBeyond Philosophy
 
PulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and HousingPulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and HousingValerie Dolenga
 
Invocacion Pantanjali
Invocacion PantanjaliInvocacion Pantanjali
Invocacion PantanjaliJuan Carlos
 
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...magdy eldaly
 
Lessons learned running large real-world Docker environments
Lessons learned running large real-world Docker environmentsLessons learned running large real-world Docker environments
Lessons learned running large real-world Docker environmentsAlois Mayr
 

Viewers also liked (16)

T.j.letterofrecommendation-1
T.j.letterofrecommendation-1T.j.letterofrecommendation-1
T.j.letterofrecommendation-1
 
Luigi Giubbolini | Time/Space-Probing Interferometer for Plasma Diagnostics
Luigi Giubbolini  | Time/Space-Probing Interferometer for Plasma DiagnosticsLuigi Giubbolini  | Time/Space-Probing Interferometer for Plasma Diagnostics
Luigi Giubbolini | Time/Space-Probing Interferometer for Plasma Diagnostics
 
Industry Keynote at Large Scale Testing Workshop 2015
Industry Keynote at Large Scale Testing Workshop 2015Industry Keynote at Large Scale Testing Workshop 2015
Industry Keynote at Large Scale Testing Workshop 2015
 
00005
0000500005
00005
 
Експорт як бізнес. Снітівкер
Експорт як бізнес. СнітівкерЕкспорт як бізнес. Снітівкер
Експорт як бізнес. Снітівкер
 
Mindanao Church Planting Mission of Churches of Christ
Mindanao Church Planting Mission of Churches of ChristMindanao Church Planting Mission of Churches of Christ
Mindanao Church Planting Mission of Churches of Christ
 
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...
Prevalence of Intestinal Helminths and Protozoa Parasites of Ruminants in Min...
 
Використання інформаційно-комунікативних технологій на уроках історії для роз...
Використання інформаційно-комунікативних технологій на уроках історії для роз...Використання інформаційно-комунікативних технологій на уроках історії для роз...
Використання інформаційно-комунікативних технологій на уроках історії для роз...
 
Ariana Y Brian
Ariana Y BrianAriana Y Brian
Ariana Y Brian
 
Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)
 
00134
0013400134
00134
 
Webinar Bridging The Experience Gap
Webinar Bridging The Experience GapWebinar Bridging The Experience Gap
Webinar Bridging The Experience Gap
 
PulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and HousingPulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and Housing
 
Invocacion Pantanjali
Invocacion PantanjaliInvocacion Pantanjali
Invocacion Pantanjali
 
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...
Hepatitis B Infection- A major Infectious Disease - Dr Magdy Eldalyدكتور مجدى...
 
Lessons learned running large real-world Docker environments
Lessons learned running large real-world Docker environmentsLessons learned running large real-world Docker environments
Lessons learned running large real-world Docker environments
 

Similar to Stop Programming in JavaScript By Luck

Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript PrimerAdam Hepton
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With PhpJeremy Coates
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisIan Macali
 
Javascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyJavascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyThorsten Suckow-Homberg
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Coursemussawir20
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 

Similar to Stop Programming in JavaScript By Luck (20)

Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Php2
Php2Php2
Php2
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Javascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the UglyJavascript - The Good, the Bad and the Ugly
Javascript - The Good, the Bad and the Ugly
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Stop Programming in JavaScript By Luck

  • 1. Stop Programming JavaScript by Luck Iowa Code Camp November 7th 2009 Sergio Pereira sergio@sergiopereira.com http://sergiopereira.com/blog @sergiopereira
  • 2. null vs. undefined Same thing, right?
  • 3. null vs. undefined They're Different things
  • 4. null vs. undefined null varparentNode = null; bartSimpson.homeState = null; null is intentional
  • 5. null vs. undefined undefined var list = ['a', 'b', 'c']; list[3]  undefined function echo(p1, p2, p3){ return [p1, p2, p3]; } echo(11, 22)  [11, 22, undefined]
  • 6. null vs. undefined undefined var list; list  undefined list = ['a', 'b', 'c']; list.length 3 list.count undefined list['count']  undefined Omission or mistake
  • 7. null vs. undefined undefined vs. not declared var list, obj = new Object(); alert(list)  undefined alert(obj.bogusProp)  undefined alert(bogusVar) error! alert(typeof list)  undefined alert(typeofbogusVar)  undefined
  • 8. == , !=, ===, !== Triple equals? Seriously?
  • 9. == , !=, ===, !== Watch out for Type Coercion
  • 10. == , !=, ===, !== 0 == falsetrue! 0 == ''true! 0 == '0'true! '' == '0' false 1 == true true! 100 == true  false 1 == '1'true! '1' == true true! '100' == true  false undefined == nulltrue!
  • 11. == , !=, ===, !== 0 === false false 0 === '' false 0 === '0' false '' === '0' false 1 === true  false 100 === true  false 1 === '1' false '1' === true  false '100' === true  false undefined === null false
  • 12. Boolean Expressions Any expression will resolve to a boolean value if( someValue ){ alert(someValue + 'resolved to true'); } else { alert(someValue + 'resolved to false'); }
  • 13. Boolean Expressions Truthy and Falsy Values that resolve to false false, 0, null, undefined, NaN, '' They're Falsy
  • 14. Boolean Expressions Truthy and Falsy Values that resolve to true Everything else
  • 15. Boolean Expressions Truthy and Falsy true, new Object(), 123, 'any string', 'false', '0' They're Truthy
  • 16. Variable scope: function if(condition){ var v1 = 123; // ... while(something){ var v2 = getNext(); // ... } } alert(v1 + v2); Watch out for bugs
  • 17. Variable scope: function function print(price){ var tax = computeTaxes(price); function format(number){ var dot = decSeparator(); // ... tax visible here } // ... dotnot visible here return format(price + tax); }
  • 18. Variables: don't forget var function getTotal(items){ weight = getTotalWeight(items); sum = 0; for(i=0; i<items.length; i++){ sum += items[i].price; } shipCost = getShipCost(weight); return sum + shipCost; }
  • 19. Variables: don't forget var function getTotal(items){ var weight = getTotalWeight(items); var sum = 0; for(vari=0; i<items.length; i++){ sum += items[i].price; } varshipCost = getShipCost(weight); return sum + shipCost; }
  • 20. Functions rock in JS They are 1st class objects Assigned to variables Passed to other functions Return value of other functions They have properties They have methods
  • 21. Function Overloads Now that's a best practice!
  • 22. Function Overloads JavaScript doesn't have function overloads
  • 23. Function Overloads functionshowMessage(msg){ showMessage(msg, false); } functionshowMessage(msg, isHtml){ if(isHtml) { $('#message').html(msg); } else { $('#message').text(msg); } } showMessage('plain text'); showMessage('<b>formatted</b>');
  • 24. The problem with this Declarations and Call Sites
  • 25. The problem with this A Simple Function function echo(p1, p2){ return [this, p1, p2]; } A Simple Invocation echo(10, 20)  [window, 10, 20]
  • 26. The problem with this Method Invocation function echo(p1, p2){ return [this, p1, p2]; } var repeater = new Object(); repeater.getData = echo; repeater.getData('a', 'b');  [repeater, 'a', 'b']
  • 27. The problem with this Call/Apply function echo(p1, p2){ return [this, p1, p2]; } var today = new Date(); echo.call(today, 'a', 'b');  [today, 'a', 'b'] echo.apply(today, ['a', 'b']);  [today, 'a', 'b']
  • 28. The problem with this Constructors functionFaderEffect(element, duration){ this.target = element; this.duration = duration; this.start = function() { //...snip } } var effect = newFaderEffect();
  • 29. The problem with this 5 Ways to Call A Function echo(10, 20); repeater.getData('a', 'b'); echo.call(today, 'a', 'b'); echo.apply(today, ['a', 'b']); var effect = newFaderEffect(); 5 Bindings FOR this
  • 31. The DOM IS scary Use a good library
  • 32. Parsing numbers: Specify the radix parseInt('182')  182 parseInt('0182')  1 parseInt('0x182')  386 parseInt('09')  0 parseInt('182', 10)  182 parseInt('0182', 10)  182 parseInt('0x182', 16)  386 parseInt('09', 10)  9 parseInt('1101', 2)  13
  • 33. Careful with Dates new Date()  right now new Date(2009, 11, 25)  Xmas 2009 new Date(2009, 12, 25)  Jan 25th 2010 new Date('11/10/2009')  Nov 10th 2009
  • 36. if(questions){ // or comments }
  • 37. Thanks! Don't forget to fill the evaluation forms Sergio Pereira, sergio@sergiopereira.com sergiopereira.com/blog Twitter: @sergiopereira