Javascript Incrementing and Decrementing Primer Tutorial

Javascript Incrementing and Decrementing Primer Tutorial

Javascript Incrementing and Decrementing Primer Tutorial

Sometimes writing Javascript code we’ve let code like …


<script type='text/javascript'>
var counter=null;


function initializeCounter() {
counter=0;
}


function incrementCounter() {
if (counter == null) {
counter=0;
}
++counter;
}


if (eval(Math.floor(Math.random() * 1746765765) % 2) == 1) {
initializeCounter();
} else {
incrementCounter(); // if called first, is interesting
}
</script>

… go through to the keeper. There’s nothing intrinsically wrong with it. But the other day, thanks to Device Orientation ‘alpha’
Calibration … World-based calibration on iOS
, we learnt that the “if” bracketing above can be superfluous in the sense that that same code above could be written …


<script type='text/javascript'>
var counter=null;


function initializeCounter() {
counter=0;
}


function incrementCounter() {
++(+counter); // ... more succinctly
}


if (eval(Math.floor(Math.random() * 1746765765) % 2) == 1) {
initializeCounter();
} else {
incrementCounter(); // if called first, is interesting
}
</script>

And so, we thought we’d write today’s proof of concept plus_avoids_zero.html‘s live run link in order for a user to try out some “Prefix style” incrementing and decrementing of Javascript variables

If this was interesting you may be interested in this too.

This entry was posted in eLearning, Tutorials and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>