SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Ähnlich wie Ten Groovy Little JavaScript Tips

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 ... SpaceBen Scofield
 
Slides changes symfony23
Slides changes symfony23Slides changes symfony23
Slides changes symfony23Javier López
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScriptYnon Perek
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptxTamas Rev
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
 
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 AngularJSPablo Godel
 
jQuery Performance Tips and Tricks
jQuery Performance Tips and TricksjQuery Performance Tips and Tricks
jQuery Performance Tips and TricksValerii Iatsko
 
Teaching Programming Online
Teaching Programming OnlineTeaching Programming Online
Teaching Programming OnlinePamela Fox
 
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 AnglePablo Godel
 
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)Cyrille Le Clerc
 
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 2015CiaranMcNulty
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularErik Guzman
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
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 worldsIgnacio 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.comVeselin Nikolov
 

Ähnlich wie 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
 

Mehr von Troy Miles

Fast C++ Web Servers
Fast C++ Web ServersFast C++ Web Servers
Fast C++ Web ServersTroy Miles
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
 
AWS Lambda Function with Kotlin
AWS Lambda Function with KotlinAWS Lambda Function with Kotlin
AWS Lambda Function with KotlinTroy Miles
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN StackTroy Miles
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application TestingTroy Miles
 
What is Angular version 4?
What is Angular version 4?What is Angular version 4?
What is Angular version 4?Troy Miles
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
From MEAN to the MERN Stack
From MEAN to the MERN StackFrom MEAN to the MERN Stack
From MEAN to the MERN StackTroy Miles
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptTroy Miles
 
Functional Programming in Clojure
Functional Programming in ClojureFunctional Programming in Clojure
Functional Programming in ClojureTroy Miles
 
MEAN Stack Warm-up
MEAN Stack Warm-upMEAN Stack Warm-up
MEAN Stack Warm-upTroy Miles
 
The JavaScript You Wished You Knew
The JavaScript You Wished You KnewThe JavaScript You Wished You Knew
The JavaScript You Wished You KnewTroy Miles
 
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 1Troy Miles
 
Build a Game in 60 minutes
Build a Game in 60 minutesBuild a Game in 60 minutes
Build a Game in 60 minutesTroy Miles
 
Quick & Dirty & MEAN
Quick & Dirty & MEANQuick & Dirty & MEAN
Quick & Dirty & MEANTroy Miles
 
A Quick Intro to ReactiveX
A Quick Intro to ReactiveXA Quick Intro to ReactiveX
A Quick Intro to ReactiveXTroy Miles
 

Mehr von 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
 

Kürzlich hochgeladen

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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