ten groovy little javascript tips
DESCRIPTION
JavaScript, like it or not, has become the most important language on the web. Nearly every developer who builds Internet apps has to use it. But JavaScript can be tough to write and even tougher to read. So here are ten tips to help you get groovy with JavaScript.TRANSCRIPT
Ten Groovy Little JavaScript TipsSo 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 [email protected]
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 Rate This Talkhttp://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 #1Use 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 #2debugger 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 #3Always 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 #4Learn 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
• Default Value
• To Binary
• To Number
• To String
Thursday, July 25, 13
Tip #5Getting 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 #6Convert 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 #7Convert 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 #8Convert 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 #9jQuery 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 #10Cache 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 is VERY 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 #1Use
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 Rate This Talkhttp://spkr8.com/t/22971
Thursday, July 25, 13