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

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
 

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

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
 

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

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
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...DianaGray10
 
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
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
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
 
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 CVKhem
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
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
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
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...
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
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
 

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