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
Ad

More Related Content

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
Filipe 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 them
Filipe Ximenes
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd Study
Chris 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 motors
Jeff Apol
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
Chris Ohk
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
rohassanie
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It Cool
eddieSullivan
 
Cs project
Cs projectCs project
Cs project
Dhairya Pant
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
Brian Moschel
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
Swarup Boro
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2
sajidpk92
 
Desenvolvendo em php cli
Desenvolvendo em php cliDesenvolvendo em php cli
Desenvolvendo em php cli
Thiago Paes
 
Lecture05
Lecture05Lecture05
Lecture05
elearning_portal
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
Chris Ohk
 
Regular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And BeyondRegular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And Beyond
Max Shirshin
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen 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 Operators
P3 InfoTech Solutions Pvt. Ltd.
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
Leonardo 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 number
Swarup Boro
 
[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
Filipe 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 them
Filipe Ximenes
 
C++ Programming - 3rd Study
C++ Programming - 3rd StudyC++ Programming - 3rd Study
C++ Programming - 3rd Study
Chris 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 motors
Jeff Apol
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
C++ Programming - 4th Study
C++ Programming - 4th StudyC++ Programming - 4th Study
C++ Programming - 4th Study
Chris Ohk
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It Cool
eddieSullivan
 
Things to avoid in JavaScript
Things to avoid in JavaScriptThings to avoid in JavaScript
Things to avoid in JavaScript
Brian Moschel
 
Array using recursion
Array using recursionArray using recursion
Array using recursion
Swarup Boro
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2
sajidpk92
 
Desenvolvendo em php cli
Desenvolvendo em php cliDesenvolvendo em php cli
Desenvolvendo em php cli
Thiago Paes
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
Chris Ohk
 
Regular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And BeyondRegular Expressions: JavaScript And Beyond
Regular Expressions: JavaScript And Beyond
Max Shirshin
 
Web app development_php_06
Web app development_php_06Web app development_php_06
Web app development_php_06
Hassen 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 Operators
P3 InfoTech Solutions Pvt. Ltd.
 
Decent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivarsDecent exposure: Controladores sin @ivars
Decent exposure: Controladores sin @ivars
Leonardo 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 number
Swarup Boro
 

Viewers also liked (16)

T.j.letterofrecommendation-1
T.j.letterofrecommendation-1T.j.letterofrecommendation-1
T.j.letterofrecommendation-1
Tyler 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 Diagnostics
Luigi 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 2015
Wolfgang Gottesheim
 
00005
0000500005
00005
Vaccin_for_stupidity
 
Експорт як бізнес. Снітівкер
Експорт як бізнес. СнітівкерЕкспорт як бізнес. Снітівкер
Експорт як бізнес. Снітівкер
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 Christ
Orlando 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 Brian
adoynan
 
Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)Instructivo Wireless (Laboratorio 1)
Instructivo Wireless (Laboratorio 1)
Marcel Aponte
 
00134
0013400134
00134
Vaccin_for_stupidity
 
Webinar Bridging The Experience Gap
Webinar Bridging The Experience GapWebinar Bridging The Experience Gap
Webinar Bridging The Experience Gap
Beyond Philosophy
 
PulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and HousingPulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and Housing
Valerie Dolenga
 
Invocacion Pantanjali
Invocacion PantanjaliInvocacion Pantanjali
Invocacion Pantanjali
Juan 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 environments
Alois Mayr
 
T.j.letterofrecommendation-1
T.j.letterofrecommendation-1T.j.letterofrecommendation-1
T.j.letterofrecommendation-1
Tyler 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 Diagnostics
Luigi 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 2015
Wolfgang 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 Christ
Orlando 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 Brian
adoynan
 
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 Gap
Beyond Philosophy
 
PulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and HousingPulteGroup Research: Millennials and Housing
PulteGroup Research: Millennials and Housing
Valerie Dolenga
 
Invocacion Pantanjali
Invocacion PantanjaliInvocacion Pantanjali
Invocacion Pantanjali
Juan 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 environments
Alois Mayr
 
Ad

Similar to Stop Programming in JavaScript By Luck (20)

Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
Dave Cross
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Php2
Php2Php2
Php2
Keennary Pungyera
 
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
Christophe Herreman
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
Adam Hepton
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
Jeremy Coates
 
Modern Perl
Modern PerlModern Perl
Modern Perl
Marcos Rebelo
 
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
Ismar Silveira
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian 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 Ugly
Thorsten Suckow-Homberg
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
Jason Hanson
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
HamletDRC
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
Jussi Pohjolainen
 
Web Technology_10.ppt
Web Technology_10.pptWeb Technology_10.ppt
Web Technology_10.ppt
Aftabali702240
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
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
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
Dave Cross
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan 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 script
Christophe Herreman
 
Javascript Primer
Javascript PrimerJavascript Primer
Javascript Primer
Adam Hepton
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
Jeremy 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 #4
Ismar Silveira
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
Dave Cross
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Seri Moth
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
Dave Cross
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
Ian 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 Ugly
Thorsten Suckow-Homberg
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
Jason Hanson
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
HamletDRC
 
Php Crash Course
Php Crash CoursePhp Crash Course
Php Crash Course
mussawir20
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
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
 
Ad

Recently uploaded (20)

HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Vibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdfVibe Coding_ Develop a web application using AI (1).pdf
Vibe Coding_ Develop a web application using AI (1).pdf
Baiju Muthukadan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
MINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PRMINDCTI revenue release Quarter 1 2025 PR
MINDCTI revenue release Quarter 1 2025 PR
MIND CTI
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 

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