SlideShare una empresa de Scribd logo
1 de 43
Descargar para leer sin conexión
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

Más contenido relacionado

Similar 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
 

Similar 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
 

Más 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
 

Más 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

Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Último (20)

Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

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