Please Support - Ride for the child

I’ve been diving deep into JS recently and I’ve started looking at JS as a language and how my code can shorter and ultimately faster. Here are a few things I’ve learnt…

JS can be very loosely typed, in fact I was amazed to find you don’t need much structure at all when writing JS. However it goes without saying that shorthand JS isn’t always the best option, it’s important to find a balance between maintainability/readability/performance. Lets look at some examples.

No brackets

if(name) {
  alert(name);
 }
 else{
  alert(‘no name’);
}

// can be wrote like the following, no brackets are needed, but it makes it less readable so I wouldn’t use it too often
if(name) alert(name);
else alert(‘no name’);

Increment/decrement

numberCount + 1;
numberCount - 1;

// Can be swapped for 
numberCount++;
numberCount--;

Add/Subtract/Multiply/divide

numberDogs = numberDogs * 5;

// Can be swapped for
numberDogs *= 5;

// You can do the same with the other mathematical methods
numberDogs += 5;
numberDogs /= 5;

If statement (Ternary operator)

if(numberPints > maxNumberPints) {
goHome();
}
else {
another();
}

// Can be shortened
if(numberPints > maxNumberPints) ? goHome() : another();

// Alternately if it were returning true/false values you could do store it in a variable.
var haveAnother = (numberPints > maxNumberPints) ? true : false;

// Or even shorter
var haveAnother = numberPints > maxNumberPints;

Assignments

Checking if a variable has been set, if not then use another

var manyCats = function(catNum) {
var numberOfCats;
if (catNum) {
numberOfCats = catNum;
}
else {
numberOfCats = 100;
}
}

// Those if statements are not needed, you can just use the following
var numberOfCats = catNum || 100;

Assign the same value to two variables

var one = ‘something’;
var two = one;

var one = two = 'something';

//However the var two would be global unless previously defined so to keep scope you would do the following
var one,two;
one = two = 'something';

There are probably lots more examples and I will continue to add to the list. If you’ve any good examples then tweet me @webknit.