SlideShare a Scribd company logo
1 of 43
Download to read 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

More Related Content

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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 FresherRemote DBA Services
 
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?Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
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 WorkerThousandEyes
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 DiscoveryTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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 FMESafe Software
 
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
 

Recently uploaded (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

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