Javascript shorthand for cleaner code
A 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.
Some links for light reading (26/05/10) | Max Design
26 May 2010 (11:43) #
[...] Javascript shorthand for cleaner code [...]
Charl van Niekerk » Blog: JavaScript Shorthands
26 May 2010 (13:09) #
[...] response to Javascript shorthand for cleaner code, there are ways you can make your code even more [...]
mrlagmer
26 May 2010 (22:41) #
Thanks. I always had trouble understanding the Ternary operator this makes more sense now.
Thanks.
Dylan
27 May 2010 (0:11) #
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.
Dennis
27 May 2010 (4:09) #
These also work in PHP, in fact I use
$var=isset($_POST['var'])?$_POST['var']:$_GET['var'];
Friday Focus 05/27/10: In Your Face Illustrations | Devlounge
28 May 2010 (16:20) #
[...] – Javascript shorthand for cleaner code “A few ways to save on some bytes in your Javascript code, as well as making it more readable [...]
Craig
29 May 2010 (4:32) #
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
Emma
29 May 2010 (10:42) #
@Craig – thanks for pointing that out, I’ve updated the example.
Tapani Jalonen
29 May 2010 (12:01) #
Default assignments was new. Thanks for pointing that out.
Paul Datta
29 May 2010 (12:24) #
This information might be redundant for some people but I am happy its here as a lot of us could use it. Neat.
eL Abee
29 May 2010 (12:38) #
I am new to Javascript, this shorthand very usefull! thanks
Sam Dalton
29 May 2010 (12:55) #
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.
William
29 May 2010 (13:14) #
Such a great tip… I have never used default assignment short code before… Nice and simple explanation. Thx for sharing again
Alex
29 May 2010 (13:21) #
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.
Alex
29 May 2010 (13:23) #
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.
Atika
29 May 2010 (13:41) #
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.
Punkchip | Javascript shorthand for cleaner code : Popular Links : eConsultant
29 May 2010 (14:25) #
[...] from: Punkchip | Javascript shorthand for cleaner code 25 May 2010 | Uncategorized | Trackback | del.icio.us | Stumble it! | View Count : 0 Next Post [...]
m3talsmith
29 May 2010 (15:41) #
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.
Krzysztkof Kotlarski
29 May 2010 (17:22) #
@Craig: You can use it like this
var navigation = $(‘.main-nav’).length ? $(‘.main-nav’) : $(‘.secondary-nav’);
Punkchip | Javascript shorthand for cleaner code « Resource Weblog
30 May 2010 (7:45) #
[...] Punkchip | Javascript shorthand for cleaner code By ivenme Check this out: Punkchip | Javascript shorthand for cleaner code [...]
Roman
30 May 2010 (13:30) #
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
Emma
02 June 2010 (10:36) #
@Roman – thanks my bad with the example, I’ve updated the text.
Joep
27 June 2010 (21:42) #
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();