10 Groovy Little JavaScript Tips

38
10 Groovy Little JavaScript Tips So Cal Code Camp, 7 March 2015 Troy Miles

Transcript of 10 Groovy Little JavaScript Tips

Page 1: 10 Groovy Little JavaScript Tips

10 Groovy Little JavaScript TipsSo Cal Code Camp, 7 March 2015 Troy Miles

Page 2: 10 Groovy Little JavaScript Tips

Troy MilesOver 35 years of programming experience

Blog: http://therockncoder.blogspot.com/

Twitter: @therockncoder

Email: [email protected]

GitHub: https://github.com/Rockncoder

Slides: https://slideshare.net/rockncoder

Page 3: 10 Groovy Little JavaScript Tips

The Browser Wars Languages

ActionScript

Java

JavaScript

JScript

VBScript

Page 4: 10 Groovy Little JavaScript Tips

Our Goal

To provide you with some simple to follow, easy to remember tips, which can improve your JavaScript.

Page 5: 10 Groovy Little JavaScript Tips

The Tips

Code

Conditionals

Conversions

jQuery

Page 6: 10 Groovy Little JavaScript Tips

Code

Page 7: 10 Groovy Little JavaScript Tips

Tip #1 Use protection

Page 8: 10 Groovy Little JavaScript Tips

Use ProtectionThe 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));

Page 9: 10 Groovy Little JavaScript Tips

Tip #2 debugger is your friend

Page 10: 10 Groovy Little JavaScript Tips

debugger is your friendAt 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)}); }); }); } });

Page 11: 10 Groovy Little JavaScript Tips

Conditional

Page 12: 10 Groovy Little JavaScript Tips

Tip #3 Always Use ===

Page 13: 10 Groovy Little JavaScript Tips

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

Page 14: 10 Groovy Little JavaScript Tips

Tip #4 Learn to love falsey

Page 15: 10 Groovy Little JavaScript Tips

Learn to love falseyWhen 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

Page 16: 10 Groovy Little JavaScript Tips

Falsey

Type Results

Null FALSE

Undefined FALSE

Number if 0 or NaN, FALSE

String if length = 0, FALSE

Object TRUE

Page 17: 10 Groovy Little JavaScript Tips

Conversions

Page 18: 10 Groovy Little JavaScript Tips

JavaScript’s Conversion Shortcuts

Default Value

To Binary

To Number

To String

Page 19: 10 Groovy Little JavaScript Tips

Tip #5 Getting default value

Page 20: 10 Groovy Little JavaScript Tips

Getting default valueAt 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);

Page 21: 10 Groovy Little JavaScript Tips

Tip #6 Convert to boolean

Page 22: 10 Groovy Little JavaScript Tips

Convert to booleanDouble exclamation (!!) converts a value to its boolean representation (true/false)

/* convert to boolean */ var toBinary = !!null; console.log(toBinary);

Page 23: 10 Groovy Little JavaScript Tips

Tip #7 Convert string to number

Page 24: 10 Groovy Little JavaScript Tips

Convert string to numberThe plus sign (+) before a numeric string converts it to a numeric value

/* convert to number */ var toNumber = +"42"; console.log(toNumber);

Page 25: 10 Groovy Little JavaScript Tips

Tip #8 Convert value to string

Page 26: 10 Groovy Little JavaScript Tips

Convert value to stringAdd an empty string (“”) to a value converts it to a string

var toString = 42 + ""; console.log(toString);

Page 27: 10 Groovy Little JavaScript Tips

jQuery

Page 28: 10 Groovy Little JavaScript Tips

Tip #9 jQuery isn’t always the answer

Page 29: 10 Groovy Little JavaScript Tips
Page 30: 10 Groovy Little JavaScript Tips

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()

Page 31: 10 Groovy Little JavaScript Tips

Tip #10 Cache selectors

Page 32: 10 Groovy Little JavaScript Tips

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

Page 33: 10 Groovy Little JavaScript Tips

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(); } }

Page 34: 10 Groovy Little JavaScript Tips

Bonus tip #1 Return false from handled events

Page 35: 10 Groovy Little JavaScript Tips

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

Page 36: 10 Groovy Little JavaScript Tips

Bonus tip #2 Use && for null checking

Page 37: 10 Groovy Little JavaScript Tips

Use && for null checking

/* && demo */ function someReallyCoolMethod() { var val = ptr && ptr.prop; }

Page 38: 10 Groovy Little JavaScript Tips

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