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

DOCX
Code sources des fonctions table cp
TXT
PDF
Javascript Styles and some tips
PPT
C++basics
PPT
C++basics
DOC
Virtual inheritance
TXT
PDF
C++ Programming - 2nd Study
Code sources des fonctions table cp
Javascript Styles and some tips
C++basics
C++basics
Virtual inheritance
C++ Programming - 2nd Study

What's hot (20)

PDF
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
PDF
Tasks: you gotta know how to run them
PDF
C++ Programming - 3rd Study
DOCX
Arduino light tracking code with 4 stepper motors
PPTX
EcmaScript unchained
PDF
C++ Programming - 4th Study
DOC
Labsheet_3
PDF
Haxe: What Makes It Cool
DOCX
Cs project
PDF
Things to avoid in JavaScript
DOCX
Array using recursion
PPT
c++ Lecture 2
PDF
Desenvolvendo em php cli
PPT
Lecture05
PDF
Data Structure - 2nd Study
PDF
Regular Expressions: JavaScript And Beyond
PDF
Web app development_php_06
PPTX
Python Programming Essentials - M11 - Comparison and Logical Operators
KEY
Decent exposure: Controladores sin @ivars
TXT
Program to find factorial of a number
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
Tasks: you gotta know how to run them
C++ Programming - 3rd Study
Arduino light tracking code with 4 stepper motors
EcmaScript unchained
C++ Programming - 4th Study
Labsheet_3
Haxe: What Makes It Cool
Cs project
Things to avoid in JavaScript
Array using recursion
c++ Lecture 2
Desenvolvendo em php cli
Lecture05
Data Structure - 2nd Study
Regular Expressions: JavaScript And Beyond
Web app development_php_06
Python Programming Essentials - M11 - Comparison and Logical Operators
Decent exposure: Controladores sin @ivars
Program to find factorial of a number
Ad

Viewers also liked (16)

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

Similar to Stop Programming in JavaScript By Luck (20)

ODP
Beginning Perl
PDF
JavaScript for PHP developers
PDF
Stuff you didn't know about action script
PPT
Javascript Primer
PPT
Exploiting Php With Php
ODP
Modern Perl
PPT
Paradigmas de Linguagens de Programacao - Aula #4
ODP
Introduction to Perl
DOC
Jsphp 110312161301-phpapp02
ODP
Introduction to Perl - Day 1
PPTX
PHP Powerpoint -- Teach PHP with this
PDF
Javascript - The Good, the Bad and the Ugly
PPT
OO JS for AS3 Devs
ODP
Java Boilerplate Busters
PDF
Short intro to ECMAScript
PPT
Web Technology_10.ppt
PPT
Php Crash Course
PDF
ES6 - Next Generation Javascript
KEY
Good Evils In Perl (Yapc Asia)
Beginning Perl
JavaScript for PHP developers
Stuff you didn't know about action script
Javascript Primer
Exploiting Php With Php
Modern Perl
Paradigmas de Linguagens de Programacao - Aula #4
Introduction to Perl
Jsphp 110312161301-phpapp02
Introduction to Perl - Day 1
PHP Powerpoint -- Teach PHP with this
Javascript - The Good, the Bad and the Ugly
OO JS for AS3 Devs
Java Boilerplate Busters
Short intro to ECMAScript
Web Technology_10.ppt
Php Crash Course
ES6 - Next Generation Javascript
Good Evils In Perl (Yapc Asia)

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Newfamily of error-correcting codes based on genetic algorithms
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
KodekX | Application Modernization Development
PDF
Electronic commerce courselecture one. Pdf
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Omni-Path Integration Expertise Offered by Nor-Tech
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
SAP855240_ALP - Defining the Global Template PUBLIC.pdf
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
DevOps & Developer Experience Summer BBQ
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Newfamily of error-correcting codes based on genetic algorithms
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Reimagining Insurance: Connected Data for Confident Decisions.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Chapter 3 Spatial Domain Image Processing.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
20250228 LYD VKU AI Blended-Learning.pptx
KodekX | Application Modernization Development
Electronic commerce courselecture one. Pdf
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Omni-Path Integration Expertise Offered by Nor-Tech
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Review of recent advances in non-invasive hemoglobin estimation
SAP855240_ALP - Defining the Global Template PUBLIC.pdf
Telecom Fraud Prevention Guide | Hyperlink InfoSystem

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