SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler offline
Ten Groovy Little
JavaScript Tips
So Cal Code Camp, July 28, 2013
Thursday, July 25, 13
Who am I?
Hi, I’m Troy. I have been developing software for over 30
years. For the last 10 years I have been focused on web,
mobile web, and mobile development. I currently work at
Kelley Blue Book as a senior software engineer. My
opinions are my own.
I can be reached rockncoder@gmail.com
Thursday, July 25, 13
The Rock n Coder
• http://therockncoder.blogspot.com
• http://www.youtube.com/user/rockncoder
• https://github.com/Rockncoder
• http://www.slideshare.net/rockncoder
Thursday, July 25, 13
Please RateThisTalk
http://spkr8.com/t/22971
Thursday, July 25, 13
The Browser Wars
• ActionScript
• Java
• JavaScript
• JScript
• VBScript
Thursday, July 25, 13
The browser wars are over.
Thursday, July 25, 13
JavaScript won.
Thursday, July 25, 13
Get used to it.
Thursday, July 25, 13
Get better at it.
Thursday, July 25, 13
Our Goal
To provide you with some simple to follow, easy to
remember tips, which can improve your JavaScript.
Thursday, July 25, 13
The Tips
• Code
• Conditionals
• Conversions
• jQuery
Thursday, July 25, 13
Code
Thursday, July 25, 13
Tip #1
Use protection
Thursday, July 25, 13
Use Protection
• The Browser is a very dirty environment
• Protect your code by wrapping it in a
function
/* using protection */
(function (doc, win) {
/* put all of your precious code here to keep it safe */
/* extra bonus, parameters passed in become local, minor performance boost */
}(document, window));
Thursday, July 25, 13
Tip #2
debugger is your friend
Thursday, July 25, 13
debugger is your friend
• At times it can be difficult to set a
breakpoint
• The debugger statement allows you to set
a breakpoint any where you like
app.post("/clientadmin", function (req, res) {
var clientId = req.body.client;
console.log("/clientadmin POST: " + JSON.stringify(req.body));
if (clientId) {
mongodb.getClientModel().findOne({_id: clientId }, function (err, client) {
mongodb.getCampaignModel().find({clientId: clientId}, function (err, campaigns) {
debugger;
console.log("Campaigns: " + JSON.stringify(campaigns));
/* set the client id */
res.cookie('clientId', clientId);
res.cookie('client', JSON.stringify(client));
res.render("clientadmin.hbs", {client: client, campaigns: campaigns, user: extractUser(res)});
});
});
}
});
Thursday, July 25, 13
Conditionals
Thursday, July 25, 13
Tip #3
Always Use ===
Thursday, July 25, 13
Always Use ===
• Double equals (==) does automatic type
conversion
• The results of this conversion is not logical
or obvious
• Avoid this by using triple equals (===)
• There is no good reason to ever use ==
• Same goes for !=
Thursday, July 25, 13
Tip #4
Learn to love falsey
Thursday, July 25, 13
Learn to Love Falsey
• When coming from C# or Java it is
tempting to use C-like conditionals
• JavaScript conditionals can be more
succinct and performant
1 /* C-style conditional */
2 if (val != null && val.length > 0){
3 ...
4 }
5
6 /* JavaScript style conditional */
7 if (val) {
8 ...
9 }
10
Thursday, July 25, 13
Falsey
Type Results
Null FALSE
Undefined FALSE
Number if 0 or NaN, FALSE
String if length = 0, FALSE
Object TRUE
Thursday, July 25, 13
Conversions
Thursday, July 25, 13
JavaScript’s Conversion
Shortcuts
• DefaultValue
• To Binary
• To Number
• To String
Thursday, July 25, 13
Tip #5
Getting default value
Thursday, July 25, 13
Getting a default value
• At times it is nice to have a default value
• JavaScript has a kind of default value operator
/* Conversions */
var defaultValue = defaultValue || 16;
var defaultString = inputValue || “Here is the default value”;
console.log(defaultValue);
Thursday, July 25, 13
Tip #6
Convert to boolean
Thursday, July 25, 13
To Binary
• Double exclamation (!!) converts a value to
its boolean representation (true/false)
/* convert to boolean */
var toBinary = !!null;
console.log(toBinary);
Thursday, July 25, 13
Tip #7
Convert string to
number
Thursday, July 25, 13
To Number
• The plus sign (+) before a numeric string
converts it to a numeric value
/* convert to number */
var toNumber = +"42";
console.log(toNumber);
Thursday, July 25, 13
Tip #8
Convert value to string
Thursday, July 25, 13
To String
• Add an empty string (“”) to a value
converts it to a string
var toString = 42 + "";
console.log(toString);
Thursday, July 25, 13
jQuery
Thursday, July 25, 13
Thursday, July 25, 13
Tip #9
jQuery isn’t always the
answer
Thursday, July 25, 13
jQuery Isn’t Always the
Answer
• For many tasks plain JavaScript is better
than jQuery
• For example, finding an element by its id,
jQuery calls document.getElementById()
/* get element by Id is faster than... */
var el = document.getElementById("myDiv");
/* $('#myDiv'), which calls it */
var $el = $('#myDiv').eq(0);
Thursday, July 25, 13
Tip #10
Cache Selectors
Thursday, July 25, 13
Cache Selectors
• jQuery Selectors are method calls, not
operators
• The method calls interrogate the DOM
• Method calls are slow
• Interrogating the DOM isVERY slow
• Caching selectors can dramatically improve
the speed of your code
Thursday, July 25, 13
Cache Selectors
/*
jQuery Demo
*/
RocknCoder.plugInSlow = function() {
var i, val;
for(i=0; i < 50; i++) {
val = $('#styleMe').html();
}
}
RocknCoder.plugInFast = function() {
var i, val, $styleMe = $('#styleMe');
for(i=0; i < 50; i++) {
val = $styleMe.html();
}
}
Thursday, July 25, 13
Bonus Tip #1
Use
event.preventDefault
Thursday, July 25, 13
Use
event.preventDefault
• If your code completely handles an event,
you should be sure to event.preventDefault
• This will stop unnecessary code from
executing
$('#usRank').on('click', function(evt){
evt.preventDefault();
showChart('US Rank', filterUSRank);
});
Thursday, July 25, 13
Summary
• JavaScript is the most important language of
web development
• But it is a quirky language
• Use these tips to speed up your code
• And make your JavaScript code groovier
Thursday, July 25, 13
Please RateThisTalk
http://spkr8.com/t/22971
Thursday, July 25, 13

Mais conteúdo relacionado

Semelhante a Ten Groovy Little JavaScript Tips

Slides changes symfony23
Slides changes symfony23Slides changes symfony23
Slides changes symfony23
Javier López
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
Ignacio Martín
 
Fluent Refactoring (Cascadia Ruby Conf 2013)
Fluent Refactoring (Cascadia Ruby Conf 2013)Fluent Refactoring (Cascadia Ruby Conf 2013)
Fluent Refactoring (Cascadia Ruby Conf 2013)
Sam Livingston-Gray
 
Lessons from my work on WordPress.com
Lessons from my work on WordPress.comLessons from my work on WordPress.com
Lessons from my work on WordPress.com
Veselin Nikolov
 

Semelhante a Ten Groovy Little JavaScript Tips (20)

And the Greatest of These Is ... Space
And the Greatest of These Is ... SpaceAnd the Greatest of These Is ... Space
And the Greatest of These Is ... Space
 
Slides changes symfony23
Slides changes symfony23Slides changes symfony23
Slides changes symfony23
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
 
Playing With The Web
Playing With The WebPlaying With The Web
Playing With The Web
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and Tricks
 
Spock Framework
Spock FrameworkSpock Framework
Spock Framework
 
Teaching Programming Online
Teaching Programming OnlineTeaching Programming Online
Teaching Programming Online
 
Lone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New AngleLone StarPHP 2013 - Building Web Apps from a New Angle
Lone StarPHP 2013 - Building Web Apps from a New Angle
 
Open Source Monitoring for Java with JMX and Graphite (GeeCON 2013)
Open Source Monitoring for Java with JMX and Graphite (GeeCON 2013)Open Source Monitoring for Java with JMX and Graphite (GeeCON 2013)
Open Source Monitoring for Java with JMX and Graphite (GeeCON 2013)
 
Dynamic documentation - SRECON 2017
Dynamic documentation - SRECON 2017Dynamic documentation - SRECON 2017
Dynamic documentation - SRECON 2017
 
Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2Lecture 6: Client Side Programming 2
Lecture 6: Client Side Programming 2
 
Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015Why Your Test Suite Sucks - PHPCon PL 2015
Why Your Test Suite Sucks - PHPCon PL 2015
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Symfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
 
Fluent Refactoring (Cascadia Ruby Conf 2013)
Fluent Refactoring (Cascadia Ruby Conf 2013)Fluent Refactoring (Cascadia Ruby Conf 2013)
Fluent Refactoring (Cascadia Ruby Conf 2013)
 
Lessons from my work on WordPress.com
Lessons from my work on WordPress.comLessons from my work on WordPress.com
Lessons from my work on WordPress.com
 

Mais de Troy Miles

Mais de Troy Miles (20)

Fast C++ Web Servers
Fast C++ Web ServersFast C++ Web Servers
Fast C++ Web Servers
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
AWS Lambda Function with Kotlin
AWS Lambda Function with KotlinAWS Lambda Function with Kotlin
AWS Lambda Function with Kotlin
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
ReactJS.NET
ReactJS.NETReactJS.NET
ReactJS.NET
 
What is Angular version 4?
What is Angular version 4?What is Angular version 4?
What is Angular version 4?
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN Stack
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in Clojure
 
MEAN Stack Warm-up
MEAN Stack Warm-upMEAN Stack Warm-up
MEAN Stack Warm-up
 
The JavaScript You Wished You Knew
The JavaScript You Wished You KnewThe JavaScript You Wished You Knew
The JavaScript You Wished You Knew
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
Build a Game in 60 minutes
Build a Game in 60 minutesBuild a Game in 60 minutes
Build a Game in 60 minutes
 
Quick & Dirty & MEAN
Quick & Dirty & MEANQuick & Dirty & MEAN
Quick & Dirty & MEAN
 
A Quick Intro to ReactiveX
A Quick Intro to ReactiveXA Quick Intro to ReactiveX
A Quick Intro to ReactiveX
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Ten Groovy Little JavaScript Tips

  • 1. Ten Groovy Little JavaScript Tips So Cal Code Camp, July 28, 2013 Thursday, July 25, 13
  • 2. Who am I? Hi, I’m Troy. I have been developing software for over 30 years. For the last 10 years I have been focused on web, mobile web, and mobile development. I currently work at Kelley Blue Book as a senior software engineer. My opinions are my own. I can be reached rockncoder@gmail.com Thursday, July 25, 13
  • 3. The Rock n Coder • http://therockncoder.blogspot.com • http://www.youtube.com/user/rockncoder • https://github.com/Rockncoder • http://www.slideshare.net/rockncoder Thursday, July 25, 13
  • 5. The Browser Wars • ActionScript • Java • JavaScript • JScript • VBScript Thursday, July 25, 13
  • 6. The browser wars are over. Thursday, July 25, 13
  • 8. Get used to it. Thursday, July 25, 13
  • 9. Get better at it. Thursday, July 25, 13
  • 10. Our Goal To provide you with some simple to follow, easy to remember tips, which can improve your JavaScript. Thursday, July 25, 13
  • 11. The Tips • Code • Conditionals • Conversions • jQuery Thursday, July 25, 13
  • 14. Use Protection • The Browser is a very dirty environment • Protect your code by wrapping it in a function /* using protection */ (function (doc, win) { /* put all of your precious code here to keep it safe */ /* extra bonus, parameters passed in become local, minor performance boost */ }(document, window)); Thursday, July 25, 13
  • 15. Tip #2 debugger is your friend Thursday, July 25, 13
  • 16. debugger is your friend • At times it can be difficult to set a breakpoint • The debugger statement allows you to set a breakpoint any where you like app.post("/clientadmin", function (req, res) { var clientId = req.body.client; console.log("/clientadmin POST: " + JSON.stringify(req.body)); if (clientId) { mongodb.getClientModel().findOne({_id: clientId }, function (err, client) { mongodb.getCampaignModel().find({clientId: clientId}, function (err, campaigns) { debugger; console.log("Campaigns: " + JSON.stringify(campaigns)); /* set the client id */ res.cookie('clientId', clientId); res.cookie('client', JSON.stringify(client)); res.render("clientadmin.hbs", {client: client, campaigns: campaigns, user: extractUser(res)}); }); }); } }); Thursday, July 25, 13
  • 18. Tip #3 Always Use === Thursday, July 25, 13
  • 19. Always Use === • Double equals (==) does automatic type conversion • The results of this conversion is not logical or obvious • Avoid this by using triple equals (===) • There is no good reason to ever use == • Same goes for != Thursday, July 25, 13
  • 20. Tip #4 Learn to love falsey Thursday, July 25, 13
  • 21. Learn to Love Falsey • When coming from C# or Java it is tempting to use C-like conditionals • JavaScript conditionals can be more succinct and performant 1 /* C-style conditional */ 2 if (val != null && val.length > 0){ 3 ... 4 } 5 6 /* JavaScript style conditional */ 7 if (val) { 8 ... 9 } 10 Thursday, July 25, 13
  • 22. Falsey Type Results Null FALSE Undefined FALSE Number if 0 or NaN, FALSE String if length = 0, FALSE Object TRUE Thursday, July 25, 13
  • 24. JavaScript’s Conversion Shortcuts • DefaultValue • To Binary • To Number • To String Thursday, July 25, 13
  • 25. Tip #5 Getting default value Thursday, July 25, 13
  • 26. Getting a default value • At times it is nice to have a default value • JavaScript has a kind of default value operator /* Conversions */ var defaultValue = defaultValue || 16; var defaultString = inputValue || “Here is the default value”; console.log(defaultValue); Thursday, July 25, 13
  • 27. Tip #6 Convert to boolean Thursday, July 25, 13
  • 28. To Binary • Double exclamation (!!) converts a value to its boolean representation (true/false) /* convert to boolean */ var toBinary = !!null; console.log(toBinary); Thursday, July 25, 13
  • 29. Tip #7 Convert string to number Thursday, July 25, 13
  • 30. To Number • The plus sign (+) before a numeric string converts it to a numeric value /* convert to number */ var toNumber = +"42"; console.log(toNumber); Thursday, July 25, 13
  • 31. Tip #8 Convert value to string Thursday, July 25, 13
  • 32. To String • Add an empty string (“”) to a value converts it to a string var toString = 42 + ""; console.log(toString); Thursday, July 25, 13
  • 35. Tip #9 jQuery isn’t always the answer Thursday, July 25, 13
  • 36. jQuery Isn’t Always the Answer • For many tasks plain JavaScript is better than jQuery • For example, finding an element by its id, jQuery calls document.getElementById() /* get element by Id is faster than... */ var el = document.getElementById("myDiv"); /* $('#myDiv'), which calls it */ var $el = $('#myDiv').eq(0); Thursday, July 25, 13
  • 38. Cache Selectors • jQuery Selectors are method calls, not operators • The method calls interrogate the DOM • Method calls are slow • Interrogating the DOM isVERY slow • Caching selectors can dramatically improve the speed of your code Thursday, July 25, 13
  • 39. Cache Selectors /* jQuery Demo */ RocknCoder.plugInSlow = function() { var i, val; for(i=0; i < 50; i++) { val = $('#styleMe').html(); } } RocknCoder.plugInFast = function() { var i, val, $styleMe = $('#styleMe'); for(i=0; i < 50; i++) { val = $styleMe.html(); } } Thursday, July 25, 13
  • 41. Use event.preventDefault • If your code completely handles an event, you should be sure to event.preventDefault • This will stop unnecessary code from executing $('#usRank').on('click', function(evt){ evt.preventDefault(); showChart('US Rank', filterUSRank); }); Thursday, July 25, 13
  • 42. Summary • JavaScript is the most important language of web development • But it is a quirky language • Use these tips to speed up your code • And make your JavaScript code groovier Thursday, July 25, 13