KEMBAR78
10 Groovy Little JavaScript Tips | PDF
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

10 Groovy Little JavaScript Tips

  • 1.
    10 Groovy Little JavaScriptTips So Cal Code Camp, 7 March 2015 Troy Miles
  • 2.
    Troy Miles Over 35years of programming experience Blog: http://therockncoder.blogspot.com/ Twitter: @therockncoder Email: rockncoder@gmail.com GitHub: https://github.com/Rockncoder Slides: https://slideshare.net/rockncoder
  • 3.
  • 4.
    Our Goal To provideyou with some simple to follow, easy to remember tips, which can improve your JavaScript.
  • 5.
  • 6.
  • 7.
  • 8.
    Use Protection The Browseris 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 isyour friend
  • 10.
    debugger is yourfriend 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)}); }); }); } });
  • 11.
  • 12.
  • 13.
    Always Use === Doubleequals (==) 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 tolove falsey
  • 15.
    Learn to lovefalsey 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 UndefinedFALSE Number if 0 or NaN, FALSE String if length = 0, FALSE Object TRUE
  • 17.
  • 18.
  • 19.
  • 20.
    Getting default value Attimes 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.
  • 22.
    Convert to boolean Doubleexclamation (!!) converts a value to its boolean representation (true/false) /* convert to boolean */ var toBinary = !!null; console.log(toBinary);
  • 23.
  • 24.
    Convert string tonumber The plus sign (+) before a numeric string converts it to a numeric value /* convert to number */ var toNumber = +"42"; console.log(toNumber);
  • 25.
  • 26.
    Convert value tostring Add an empty string (“”) to a value converts it to a string var toString = 42 + ""; console.log(toString);
  • 27.
  • 28.
    Tip #9 jQuery isn’talways the answer
  • 30.
    jQuery isn’t alwaysthe answer For many tasks plain JavaScript is better than jQuery For example, finding an element by its id, jQuery calls document.getElementById()
  • 31.
  • 32.
    Cache selectors jQuery Selectorsare 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 Returnfalse from handled events
  • 35.
    Return false fromhandled 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 && fornull checking /* && demo */ function someReallyCoolMethod() { var val = ptr && ptr.prop; }
  • 38.
    Summary JavaScript is themost 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