Recursion - Generally, recursion can be up to 10 times slower than looping. However, recursion can be more elegant, as such, the programmer must determine whether efficiency or simplicity is more appropriate.
function power(base, exponent) {
if (exponent == undefined) {
exponent = 2;
}
var result = 1;
for (var count = 0; count < exponent; count++) {
result *= base;
}
return result;
}
function powerR(base, exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);
}
console.log("Recursive: ", powerR(2, 3));
console.log("Loop: ", power(2,3));
function multiplier(factor) {
return function(number) {
console.log("Factor: ", factor, " Number: ", number);
return number * factor;
};
}
var twice = multiplier(3);
console.log(twice(5));
* Lexical scope is the variable 'visibility' of variables within a program via combinations of scope. Essentially, local scopes have access to those scope around them. They do not have access to scopes inside of them.
* Function declarations can be placed anywhere within the program as they are effectively hoisted to the top of the scope when running.
foo('bar');
// function declaration
function foo(string) {
console.log('Foo', string);
}
Expression functions need to be declared before they are used.
// function definition
var foo = function(string) {
return 'Foo' + string;
}
console.log(foo('bar'));
'How difficult it is to find a good name for a function is a good indication of how clear a concept it is that you’re trying to wrap.' - Marijn Haverbeke