Skip to content

Instantly share code, notes, and snippets.

@themindfuldev
Last active December 19, 2015 10:59
Show Gist options
  • Save themindfuldev/5944520 to your computer and use it in GitHub Desktop.
Save themindfuldev/5944520 to your computer and use it in GitHub Desktop.
This gist just shows some good usage and bad usage examples about Hoisting concept in Javascript.
function stepSum() {
var total = 0;
for (var i = 0; i < arguments.length; i++) {
var parameter = arguments[i];
if (typeof(parameter) !== 'number') {
parameter = parseInt(parameter);
}
setTimeout(function() {
if (!isNaN(parameter)) {
total += parameter;
console.log(i + ") adding " + parameter +
", total is now " + total);
}
}, i*1000);
}
return "the stepSum has been triggered...";
}
stepSum(3, 2, 1);
function stepSum() {
var parameter, printStep,
total = 0,
i = 0;
// printStep function
printStep = function(parameter, step) {
step++;
setTimeout(function() {
if (!isNaN(parameter)) {
total += parameter;
console.log(step + ") adding " + parameter +
", total is now " + total);
}
}, step * 1000);
};
// Iterating
for (i = 0; i < arguments.length; i++) {
parameter = arguments[i];
if (typeof(parameter) !== 'number') {
parameter = parseInt(parameter);
}
printStep(parameter, i);
}
return "the stepSum has been triggered...";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment