For example (in JavaScript):
//Not that I would ever add a method to a base JavaScript prototype...
//(*wink nudge*)...
Array.prototype.lastIndex = function() {
return this.length - 1;
}
console.log(array[array.lastIndex()]);
vs
console.log(array[array.length - 1]);
Technically speaking, the latter method uses one less character, but also utilizes a magic number. Granted, the readability may not really be affected in this case, but magic numbers suck. Which is better practice to use?
I’m of the opinion that
1and0don’t really count as “magic numbers” in many cases. When you’re referring to the index of the last item (i.e.length - 1), that would definitely be one time where I would not consider1a magic number.