SlideShare a Scribd company logo
10 Groovy Little
JavaScript Tips
So Cal Code Camp, 7 March 2015
Troy Miles
Troy Miles
Over 35 years of programming experience
Blog: http://therockncoder.blogspot.com/
Twitter: @therockncoder
Email: rockncoder@gmail.com
GitHub: https://github.com/Rockncoder
Slides: https://slideshare.net/rockncoder
The Browser Wars
Languages
ActionScript
Java
JavaScript
JScript
VBScript
Our Goal
To provide you with some simple to follow, easy to
remember tips, which can improve your JavaScript.
The Tips
Code
Conditionals
Conversions
jQuery
Code
Tip #1
Use protection
Use Protection
The Browser is a very dirty environment
Protect your code by wrapping it in a function
/* using protection */
(function (doc, win) {
“use strict”;
/* put all of your precious code here to keep it safe */
/* extra bonus, parameters passed in become local, minor performance boost */
}(document, window));
Tip #2
debugger is your friend
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)});
});
});
}
});
Conditional
Tip #3
Always Use ===
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 !=, use !== instead
Tip #4
Learn to love falsey
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
Falsey
Type Results
Null FALSE
Undefined FALSE
Number if 0 or NaN, FALSE
String if length = 0, FALSE
Object TRUE
Conversions
JavaScript’s Conversion
Shortcuts
Default Value
To Binary
To Number
To String
Tip #5
Getting default value
Getting 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);
Tip #6
Convert to boolean
Convert to boolean
Double exclamation (!!) converts a value to its boolean
representation (true/false)
/* convert to boolean */
var toBinary = !!null;
console.log(toBinary);
Tip #7
Convert string to number
Convert string to number
The plus sign (+) before a numeric string converts it to
a numeric value
/* convert to number */
var toNumber = +"42";
console.log(toNumber);
Tip #8
Convert value to string
Convert value to string
Add an empty string (“”) to a value converts it to a
string
var toString = 42 + "";
console.log(toString);
jQuery
Tip #9
jQuery isn’t always the answer
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()
Tip #10
Cache selectors
Cache selectors
jQuery Selectors are method calls, not operators
The method calls interrogate the DOM
Method calls are slow
Interrogating the DOM is VERY slow
Caching selectors can dramatically improve the speed
of your code
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();
}
}
Bonus tip #1
Return false from handled events
Return false from handled
events
If your code completely handles an event, you should
be sure to return false
It will call event.preventDefault()
And call event.stopPropagation()
This will stop unnecessary code from executing
Bonus tip #2
Use && for null checking
Use && for null checking
/*
&& demo
*/
function someReallyCoolMethod() {
var val = ptr && ptr.prop;
}
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

More Related Content

What's hot

vb script
vb scriptvb script
vb script
Anand Dhana
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
Manoj kumar
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
DHTMLExtreme
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
DivyaKS12
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
Edorian
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
Saai Vignesh P
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
Vishal Mittal
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
nanjil1984
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]srikanthbkm
 
Javascript
JavascriptJavascript
Javascript
Nagarajan
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Bhanuka Uyanage
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
Andrea Paciolla
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
SHC
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
Folio3 Software
 
Java scriptforjavadev part1
Java scriptforjavadev part1Java scriptforjavadev part1
Java scriptforjavadev part1
Makarand Bhatambarekar
 
Java script
Java scriptJava script
Java script
Jay Patel
 
Javascript 01 (js)
Javascript 01 (js)Javascript 01 (js)
Javascript 01 (js)
AbhishekMondal42
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptzachwise
 
Java script
Java scriptJava script
Java script
Sadeek Mohammed
 

What's hot (20)

vb script
vb scriptvb script
vb script
 
PHP Introduction and Training Material
PHP Introduction and Training MaterialPHP Introduction and Training Material
PHP Introduction and Training Material
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Clean Code: Stop wasting my time
Clean Code: Stop wasting my timeClean Code: Stop wasting my time
Clean Code: Stop wasting my time
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Java scriptforjavadev part1
Java scriptforjavadev part1Java scriptforjavadev part1
Java scriptforjavadev part1
 
Java script
Java scriptJava script
Java script
 
Javascript 01 (js)
Javascript 01 (js)Javascript 01 (js)
Javascript 01 (js)
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script
Java scriptJava script
Java script
 

Viewers also liked

Discover Android Wear
Discover Android WearDiscover Android Wear
Discover Android Wear
Troy Miles
 
Debugging and Tuning Mobile Web Sites with Modern Web Browsers
Debugging and Tuning Mobile Web Sites with Modern Web BrowsersDebugging and Tuning Mobile Web Sites with Modern Web Browsers
Debugging and Tuning Mobile Web Sites with Modern Web Browsers
Troy Miles
 
Enterprise javascriptsession1
Enterprise javascriptsession1Enterprise javascriptsession1
Enterprise javascriptsession1Troy Miles
 
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim RemaniFinding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
JAXLondon2014
 
An Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows AzureAn Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows Azure
Troy Miles
 
AngularJS on Mobile with the Ionic Framework
AngularJS on Mobile with the Ionic FrameworkAngularJS on Mobile with the Ionic Framework
AngularJS on Mobile with the Ionic FrameworkTroy Miles
 
MongoDB Workshop
MongoDB WorkshopMongoDB Workshop
MongoDB Workshop
eagerdeveloper
 
Chrome Dev Tools
Chrome Dev ToolsChrome Dev Tools
Chrome Dev Tools
Troy Miles
 
Quick & Dirty Mobile Web with jQuery Mobile
Quick & Dirty Mobile Web with jQuery MobileQuick & Dirty Mobile Web with jQuery Mobile
Quick & Dirty Mobile Web with jQuery Mobile
Troy Miles
 

Viewers also liked (9)

Discover Android Wear
Discover Android WearDiscover Android Wear
Discover Android Wear
 
Debugging and Tuning Mobile Web Sites with Modern Web Browsers
Debugging and Tuning Mobile Web Sites with Modern Web BrowsersDebugging and Tuning Mobile Web Sites with Modern Web Browsers
Debugging and Tuning Mobile Web Sites with Modern Web Browsers
 
Enterprise javascriptsession1
Enterprise javascriptsession1Enterprise javascriptsession1
Enterprise javascriptsession1
 
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim RemaniFinding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
Finding your Way in the Midst of the NoSQL Haze - Abdelmonaim Remani
 
An Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows AzureAn Introduction to Node.js Development with Windows Azure
An Introduction to Node.js Development with Windows Azure
 
AngularJS on Mobile with the Ionic Framework
AngularJS on Mobile with the Ionic FrameworkAngularJS on Mobile with the Ionic Framework
AngularJS on Mobile with the Ionic Framework
 
MongoDB Workshop
MongoDB WorkshopMongoDB Workshop
MongoDB Workshop
 
Chrome Dev Tools
Chrome Dev ToolsChrome Dev Tools
Chrome Dev Tools
 
Quick & Dirty Mobile Web with jQuery Mobile
Quick & Dirty Mobile Web with jQuery MobileQuick & Dirty Mobile Web with jQuery Mobile
Quick & Dirty Mobile Web with jQuery Mobile
 

Similar to 10 Groovy Little JavaScript Tips

Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
Sultan Khan
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
Bob Paulin
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
Artificial Intelligence Institute at UofSC
 
JavaScript Basics with baby steps
JavaScript Basics with baby stepsJavaScript Basics with baby steps
JavaScript Basics with baby steps
Muhammad khurram khan
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
First class Variables in Pharo
First class Variables in PharoFirst class Variables in Pharo
First class Variables in Pharo
ESUG
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
Marcus Denker
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
Ortus Solutions, Corp
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
13 javascript techniques to improve your code
13 javascript techniques to improve your code13 javascript techniques to improve your code
13 javascript techniques to improve your code
Surendra kumar
 
JS class slides (2016)
JS class slides (2016)JS class slides (2016)
JS class slides (2016)
Yves-Emmanuel Jutard
 
JS Class 2016
JS Class 2016JS Class 2016
JS Class 2016
Yves-Emmanuel Jutard
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
Mike Subelsky
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
JohnLagman3
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Ten Groovy Little JavaScript Tips
Ten Groovy Little JavaScript TipsTen Groovy Little JavaScript Tips
Ten Groovy Little JavaScript Tips
Troy Miles
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
Mikel Torres Ugarte
 

Similar to 10 Groovy Little JavaScript Tips (20)

Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Code Quality Practice and Tools
Code Quality Practice and ToolsCode Quality Practice and Tools
Code Quality Practice and Tools
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
 
JavaScript Basics with baby steps
JavaScript Basics with baby stepsJavaScript Basics with baby steps
JavaScript Basics with baby steps
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
First class Variables in Pharo
First class Variables in PharoFirst class Variables in Pharo
First class Variables in Pharo
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
13 javascript techniques to improve your code
13 javascript techniques to improve your code13 javascript techniques to improve your code
13 javascript techniques to improve your code
 
JS class slides (2016)
JS class slides (2016)JS class slides (2016)
JS class slides (2016)
 
JS Class 2016
JS Class 2016JS Class 2016
JS Class 2016
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Ten Groovy Little JavaScript Tips
Ten Groovy Little JavaScript TipsTen Groovy Little JavaScript Tips
Ten Groovy Little JavaScript Tips
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 

More from Troy Miles

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

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 

Recently uploaded (20)

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 

10 Groovy Little JavaScript Tips

  • 1. 10 Groovy Little JavaScript Tips So Cal Code Camp, 7 March 2015 Troy Miles
  • 2. Troy Miles Over 35 years of programming experience Blog: http://therockncoder.blogspot.com/ Twitter: @therockncoder Email: rockncoder@gmail.com GitHub: https://github.com/Rockncoder Slides: https://slideshare.net/rockncoder
  • 4. Our Goal To provide you with some simple to follow, easy to remember tips, which can improve your JavaScript.
  • 8. Use Protection The Browser is a very dirty environment Protect your code by wrapping it in a function /* using protection */ (function (doc, win) { “use strict”; /* put all of your precious code here to keep it safe */ /* extra bonus, parameters passed in become local, minor performance boost */ }(document, window));
  • 9. Tip #2 debugger is your friend
  • 10. 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)}); }); }); } });
  • 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 !=, use !== instead
  • 14. Tip #4 Learn to love falsey
  • 15. 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
  • 16. Falsey Type Results Null FALSE Undefined FALSE Number if 0 or NaN, FALSE String if length = 0, FALSE Object TRUE
  • 20. Getting 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);
  • 21. Tip #6 Convert to boolean
  • 22. Convert to boolean Double exclamation (!!) converts a value to its boolean representation (true/false) /* convert to boolean */ var toBinary = !!null; console.log(toBinary);
  • 24. Convert string to number The plus sign (+) before a numeric string converts it to a numeric value /* convert to number */ var toNumber = +"42"; console.log(toNumber);
  • 25. Tip #8 Convert value to string
  • 26. Convert value to string Add an empty string (“”) to a value converts it to a string var toString = 42 + ""; console.log(toString);
  • 28. Tip #9 jQuery isn’t always the answer
  • 29.
  • 30. 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()
  • 32. Cache selectors jQuery Selectors are method calls, not operators The method calls interrogate the DOM Method calls are slow Interrogating the DOM is VERY slow Caching selectors can dramatically improve the speed of your code
  • 33. 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(); } }
  • 34. Bonus tip #1 Return false from handled events
  • 35. Return false from handled events If your code completely handles an event, you should be sure to return false It will call event.preventDefault() And call event.stopPropagation() This will stop unnecessary code from executing
  • 36. Bonus tip #2 Use && for null checking
  • 37. Use && for null checking /* && demo */ function someReallyCoolMethod() { var val = ptr && ptr.prop; }
  • 38. 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