Javascript shorthand for cleaner code
TweetA few ways to save on some bytes in your Javascript code, as well as making it more readable and quicker to write:
Variable increment/decrement/multiply/divide
When you want to increase or decrease a number variable by one; instead of this:
growCount = growCount + 1;
shrinkCount = shrinkCount - 1;
You can simply do the following:
growCount ++;
shrinkCount --;
Or to add/subtract/multiply/divide a number to/from/by itself you can do:
growCout += 100;
shrinkCount -= 2;
moreSweets *= 5; // multiply moreSweets by 5
lessApple /= 2; // divide lessApple by 2
Ternary operator (conditional)
This is a great code saver for when you want to do something if the test is true, else do something else:
if(myAge > legalAge) {
canDrink = true;
}
else {
canDrink = false;
}
Instead, put the condition before the question mark then the if true statement and false statement after that separated by a colon:
var canDrink = (myAge > legalAge) ? true : false;
var canDrink = myAge > legalAge because it’s returning a boolean.Associative array notation
The old school way of setting up an array was to create a named array and then add each named element one by one:
var skillSet = new Array();
skillSet['Document language'] = 'HTML5';
skillSet['Styling language'] = 'CSS3';
skillSet['Javascript library'] = 'jQuery';
skillSet['Other'] = 'Usability and accessibility';
A quicker and more readable way is to add the elements at the same time using the object literal notation to become:
var skillSet = {
'Document language' : 'HTML5',
'Styling language' : 'CSS3',
'Javascript library' : 'jQuery',
'Other' : 'Usability and accessibility'
};
Don’t forget to omit the final comma otherwise certain browsers will complain.
Default assignments
The following is useful if you are testing if a variable has previously been set and if not to try something else:
function displayValues(limit) {
var length;
if(limit) {
length = limit;
} else {
length = 10;
}
for(var i = 0; i++; i < = length) {
...
}
A shorter way is to use the double pipe. If limit has not been passed to the function then length will be set to the default of 10:
function displayValues(limit) {
var length = limit || 10;
for(var i = 0; i < = length; i++) {
...
}
length will be set to the value of the left operand if it evaluates to true, therefore anything other than the following:
- false
- 0
- null
- undefined
- empty string
Otherwise it will be set to the value of the right operand. So this isn’t the right thing to use if you need to explicitly set the length to zero.
[...] Javascript shorthand for cleaner code [...]
[...] response to Javascript shorthand for cleaner code, there are ways you can make your code even more [...]
Thanks. I always had trouble understanding the Ternary operator this makes more sense now.
Thanks.
Nice tips Emma.
Seeing as you’re either going to get true or false with that ternary, you could simplify it further:
var canDrink = (myAge >= legalAge);
I don’t think the parentheses are required there, but it helps with readability a little bit imho.
These also work in PHP, in fact I use
$var=isset($_POST['var'])?$_POST['var']:$_GET['var'];
[...] – Javascript shorthand for cleaner code “A few ways to save on some bytes in your Javascript code, as well as making it more readable [...]
Cool article.
One quick thing. Your default assignments example won’t do as intended in jQuery because $() will always return a jQuery object even if ‘.main-nav’ isn’t found. That jQuery object will always evaluate to true.
var navigation = $(‘.main-nav’) || $(‘.secondary-nav’);
Craig
@Craig – thanks for pointing that out, I’ve updated the example.
Default assignments was new. Thanks for pointing that out.
This information might be redundant for some people but I am happy its here as a lot of us could use it. Neat.
I am new to Javascript, this shorthand very usefull! thanks
It might be good to explain that || is in fact the OR operator, and not a piece of syntax used solely for achieveing a default function parameter.
Other than that, some great tips for those new to programming.
Such a great tip… I have never used default assignment short code before… Nice and simple explanation. Thx for sharing again
It might also be worth pointing out how the “Default assignments” works.
It works just like `if (myVar == 1 || myVar == 2)` in that if the left hand equates to true, it skips the right hand because only one needs to be true for ‘or’ to be true. If it evaluates to false, then it will check the other side, and because of the way JavaScript returns expressions, it gives the right hand value.
Be warned though, if one or your arguments can be FALSE then it will always give the right hand side.
Oh, and here it is on JSbin if you want to see what I’m talking about.
http://jsbin.com/ahaya/edit
Sorry I didn’t say it before, but this is a good list of techniques, thanks for the article. I wish I had read them compiled like this when I started JavaScript programming.
Thanks, very useful technics. I do not yet know the «double pipe» technics. It’s true that sometimes I don’t think to use this programming technics to simplify my code.
[...] from: Punkchip | Javascript shorthand for cleaner code 25 May 2010 | Uncategorized | Trackback | del.icio.us | Stumble it! | View Count : 0 Next Post [...]
I use the ternary operator often. It’s one of the most useful shorthands available and it’s available in almost every language, so once you’ve learned the technique, you can use it almost anywhere.
@Craig: You can use it like this
var navigation = $(‘.main-nav’).length ? $(‘.main-nav’) : $(‘.secondary-nav’);
Just wanted to point out one pitfall with the default value:
if you want to be the limit explicitly 0 it doesn’t work as desired:
var limit = 0;
var length = limit || 10;
console.log(length); // displays 10 instead of 0
so you always have to be careful with this one.
greets
@Roman – thanks my bad with the example, I’ve updated the text.
Here’s a nice one; to check if an object is set to any truthy value (i.e. not nothing/null) present (useful for browser specific things as ActiveX): !!object
The first negation causes the value to become a boolean, the second inverts it.
Example;
//check if window has a method named DrawPie
if(!!window.DrawPie) window.DrawPie();
Nice little set of short hand for JS, just what I was looking for to optimise my code some more.
[...] Javascript Shorthand for Cleaner Code – Emma Sax [...]