SlideShare a Scribd company logo
Stop Programming JavaScript by LuckIowa Code CampNovember 7th 2009Sergio Pereira	sergio@sergiopereira.com	http://sergiopereira.com/blog	@sergiopereira
null vs. undefinedSame thing, right?
null vs. undefinedThey're Different things
null vs. undefinednullvarparentNode = null;bartSimpson.homeState = null;null is intentional
null vs. undefinedundefinedvar list = ['a', 'b', 'c'];list[3]  undefinedfunction echo(p1, p2, p3){return [p1, p2, p3];}echo(11, 22)  [11, 22, undefined]
null vs. undefinedundefinedvar list;list  undefinedlist = ['a', 'b', 'c'];list.length 3list.count undefinedlist['count']  undefinedOmission or mistake
null vs. undefinedundefined vs. not declaredvar list, obj = new Object();alert(list)  undefinedalert(obj.bogusProp)  undefinedalert(bogusVar) error!alert(typeof list)  undefinedalert(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  falseundefined == 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  falseundefined === null false
Boolean ExpressionsAny expression will resolve to a boolean valueif( someValue ){  alert(someValue + 'resolved to true');} else {  alert(someValue + 'resolved to false');}
Boolean ExpressionsTruthy and FalsyValues that resolve to falsefalse, 0, null, undefined, NaN, ''They're Falsy
Boolean ExpressionsTruthy and FalsyValues that resolve to trueEverything else
Boolean ExpressionsTruthy and Falsytrue, new Object(), 123,'any string', 'false', '0'They're Truthy
Variable scope: functionif(condition){var v1 = 123;// ...while(something){var v2 = getNext();// ...  }}alert(v1 + v2);Watch out for bugs
Variable scope: functionfunction print(price){var tax = computeTaxes(price);function format(number){var dot = decSeparator();// ... tax visible here  }// ... dotnot visible herereturn format(price + tax);}
Variables: don't forget varfunction 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 varfunction 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 JSThey are 1st class objectsAssigned to variablesPassed to other functionsReturn value of other functionsThey have propertiesThey have methods
Function OverloadsNow that's a best practice!
Function OverloadsJavaScript doesn't have function overloads
Function OverloadsfunctionshowMessage(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 thisDeclarations and Call Sites
The problem with thisA Simple Functionfunction echo(p1, p2){return [this, p1, p2];}A Simple Invocationecho(10, 20)  [window, 10, 20]
The problem with thisMethod Invocationfunction echo(p1, p2){return [this, p1, p2];}var repeater = new Object();repeater.getData = echo;repeater.getData('a', 'b');  [repeater, 'a', 'b']
The problem with thisCall/Applyfunction 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 thisConstructorsfunctionFaderEffect(element, duration){this.target = element;this.duration = duration;this.start = function() {//...snip    }}var effect = newFaderEffect();
The problem with this5 Ways to Call A Functionecho(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 scaryUse a good library
Parsing numbers:Specify the radixparseInt('182')    182parseInt('0182')   1parseInt('0x182')  386parseInt('09')     0parseInt('182', 10)    182parseInt('0182', 10)   182parseInt('0x182', 16)  386parseInt('09', 10)     9parseInt('1101', 2)    13
Careful with Datesnew Date()              right nownew Date(2009, 11, 25)  Xmas 2009new Date(2009, 12, 25)  Jan 25th 2010new 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 formsSergio Pereira,  sergio@sergiopereira.comsergiopereira.com/blogTwitter: @sergiopereira

More Related Content

What's hot (20)

PDF
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Filipe Ximenes
 
PDF
Tasks: you gotta know how to run them
Filipe Ximenes
 
PDF
C++ Programming - 3rd Study
Chris Ohk
 
DOCX
Arduino light tracking code with 4 stepper motors
Jeff Apol
 
PPTX
EcmaScript unchained
Eduard Tomàs
 
PDF
C++ Programming - 4th Study
Chris Ohk
 
DOC
Labsheet_3
rohassanie
 
PDF
Haxe: What Makes It Cool
eddieSullivan
 
DOCX
Cs project
Dhairya Pant
 
PDF
Things to avoid in JavaScript
Brian Moschel
 
DOCX
Array using recursion
Swarup Boro
 
PPT
c++ Lecture 2
sajidpk92
 
PDF
Desenvolvendo em php cli
Thiago Paes
 
PPT
Lecture05
elearning_portal
 
PDF
Data Structure - 2nd Study
Chris Ohk
 
PDF
Regular Expressions: JavaScript And Beyond
Max Shirshin
 
PDF
Web app development_php_06
Hassen Poreya
 
PPTX
Python Programming Essentials - M11 - Comparison and Logical Operators
P3 InfoTech Solutions Pvt. Ltd.
 
KEY
Decent exposure: Controladores sin @ivars
Leonardo Soto
 
TXT
Program to find factorial of a number
Swarup Boro
 
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Filipe Ximenes
 
Tasks: you gotta know how to run them
Filipe Ximenes
 
C++ Programming - 3rd Study
Chris Ohk
 
Arduino light tracking code with 4 stepper motors
Jeff Apol
 
EcmaScript unchained
Eduard Tomàs
 
C++ Programming - 4th Study
Chris Ohk
 
Labsheet_3
rohassanie
 
Haxe: What Makes It Cool
eddieSullivan
 
Cs project
Dhairya Pant
 
Things to avoid in JavaScript
Brian Moschel
 
Array using recursion
Swarup Boro
 
c++ Lecture 2
sajidpk92
 
Desenvolvendo em php cli
Thiago Paes
 
Lecture05
elearning_portal
 
Data Structure - 2nd Study
Chris Ohk
 
Regular Expressions: JavaScript And Beyond
Max Shirshin
 
Web app development_php_06
Hassen Poreya
 
Python Programming Essentials - M11 - Comparison and Logical Operators
P3 InfoTech Solutions Pvt. Ltd.
 
Decent exposure: Controladores sin @ivars
Leonardo Soto
 
Program to find factorial of a number
Swarup Boro
 

Viewers also liked (16)

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

Similar to Stop Programming in JavaScript By Luck (20)

ODP
Beginning Perl
Dave Cross
 
PDF
JavaScript for PHP developers
Stoyan Stefanov
 
PDF
Stuff you didn't know about action script
Christophe Herreman
 
PPT
Javascript Primer
Adam Hepton
 
PPT
Exploiting Php With Php
Jeremy Coates
 
ODP
Modern Perl
Marcos Rebelo
 
PPT
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
ODP
Introduction to Perl
Dave Cross
 
DOC
Jsphp 110312161301-phpapp02
Seri Moth
 
ODP
Introduction to Perl - Day 1
Dave Cross
 
PPTX
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
PDF
Javascript - The Good, the Bad and the Ugly
Thorsten Suckow-Homberg
 
PPT
OO JS for AS3 Devs
Jason Hanson
 
ODP
Java Boilerplate Busters
HamletDRC
 
PDF
Short intro to ECMAScript
Jussi Pohjolainen
 
PPT
Web Technology_10.ppt
Aftabali702240
 
PPT
Php Crash Course
mussawir20
 
PDF
ES6 - Next Generation Javascript
RameshNair6
 
KEY
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Beginning Perl
Dave Cross
 
JavaScript for PHP developers
Stoyan Stefanov
 
Stuff you didn't know about action script
Christophe Herreman
 
Javascript Primer
Adam Hepton
 
Exploiting Php With Php
Jeremy Coates
 
Modern Perl
Marcos Rebelo
 
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
Introduction to Perl
Dave Cross
 
Jsphp 110312161301-phpapp02
Seri Moth
 
Introduction to Perl - Day 1
Dave Cross
 
PHP Powerpoint -- Teach PHP with this
Ian Macali
 
Javascript - The Good, the Bad and the Ugly
Thorsten Suckow-Homberg
 
OO JS for AS3 Devs
Jason Hanson
 
Java Boilerplate Busters
HamletDRC
 
Short intro to ECMAScript
Jussi Pohjolainen
 
Web Technology_10.ppt
Aftabali702240
 
Php Crash Course
mussawir20
 
ES6 - Next Generation Javascript
RameshNair6
 
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Ad

Recently uploaded (20)

PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 

Stop Programming in JavaScript By Luck

  • 1. Stop Programming JavaScript by LuckIowa Code CampNovember 7th 2009Sergio Pereira [email protected] http://sergiopereira.com/blog @sergiopereira
  • 2. null vs. undefinedSame thing, right?
  • 4. null vs. undefinednullvarparentNode = null;bartSimpson.homeState = null;null is intentional
  • 5. null vs. undefinedundefinedvar list = ['a', 'b', 'c'];list[3]  undefinedfunction echo(p1, p2, p3){return [p1, p2, p3];}echo(11, 22)  [11, 22, undefined]
  • 6. null vs. undefinedundefinedvar list;list  undefinedlist = ['a', 'b', 'c'];list.length 3list.count undefinedlist['count']  undefinedOmission or mistake
  • 7. null vs. undefinedundefined vs. not declaredvar list, obj = new Object();alert(list)  undefinedalert(obj.bogusProp)  undefinedalert(bogusVar) error!alert(typeof list)  undefinedalert(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  falseundefined == 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  falseundefined === null false
  • 12. Boolean ExpressionsAny expression will resolve to a boolean valueif( someValue ){ alert(someValue + 'resolved to true');} else { alert(someValue + 'resolved to false');}
  • 13. Boolean ExpressionsTruthy and FalsyValues that resolve to falsefalse, 0, null, undefined, NaN, ''They're Falsy
  • 14. Boolean ExpressionsTruthy and FalsyValues that resolve to trueEverything else
  • 15. Boolean ExpressionsTruthy and Falsytrue, new Object(), 123,'any string', 'false', '0'They're Truthy
  • 16. Variable scope: functionif(condition){var v1 = 123;// ...while(something){var v2 = getNext();// ... }}alert(v1 + v2);Watch out for bugs
  • 17. Variable scope: functionfunction print(price){var tax = computeTaxes(price);function format(number){var dot = decSeparator();// ... tax visible here }// ... dotnot visible herereturn format(price + tax);}
  • 18. Variables: don't forget varfunction 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 varfunction 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 JSThey are 1st class objectsAssigned to variablesPassed to other functionsReturn value of other functionsThey have propertiesThey have methods
  • 23. Function OverloadsfunctionshowMessage(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 thisDeclarations and Call Sites
  • 25. The problem with thisA Simple Functionfunction echo(p1, p2){return [this, p1, p2];}A Simple Invocationecho(10, 20)  [window, 10, 20]
  • 26. The problem with thisMethod Invocationfunction 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 thisCall/Applyfunction 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 thisConstructorsfunctionFaderEffect(element, duration){this.target = element;this.duration = duration;this.start = function() {//...snip }}var effect = newFaderEffect();
  • 29. The problem with this5 Ways to Call A Functionecho(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 scaryUse a good library
  • 32. Parsing numbers:Specify the radixparseInt('182')  182parseInt('0182')  1parseInt('0x182')  386parseInt('09')  0parseInt('182', 10)  182parseInt('0182', 10)  182parseInt('0x182', 16)  386parseInt('09', 10)  9parseInt('1101', 2)  13
  • 33. Careful with Datesnew Date()  right nownew Date(2009, 11, 25)  Xmas 2009new Date(2009, 12, 25)  Jan 25th 2010new Date('11/10/2009')  Nov 10th 2009
  • 36. if(questions){ // or comments}
  • 37. Thanks!Don't forget to fill the evaluation formsSergio Pereira, [email protected]/blogTwitter: @sergiopereira