#Function in Javascrpit ##1.Defining a Function
var square = function(x) {
return x * x;
};
square(5);
##2. Scope
// // NESTED SCOPE
// var landscape = function(){
// var result = "";
// var flat = function(size){
// for (var count = 0; count < size; count++)
// result += "_";
// };
// var moutain = function(size){
// result += "/";
// for (var count = 0; count < size; count++)
// result += "'";
// result += "\\";
// };
// flat(3);
// moutain(4);
// }
##3. CALL STACK
// CALL STACK
function greet(who) {
console.log("Hello " + who);
ask("How are you?");
console.log("I'm fine");
};
function ask(question) {
console.log("well, " + question);
};
greet("Harry");
console.log("Bye");
the storage where computer stores context is called CALL STACK
Out of Call Stack
function chicken() {
return egg();
}
function egg() {
return chicken();
}
console.log(chicken() + " came first");
##4. Optional Argument
// alert("Halo", "wie geth gut?", "mir geth gut");
function power(base, exponent) {
if (exponent == undefined) {
exponent = 2;
}
var result = 1;
for (var count = 0; count < exponent; count++) {
result = result * base;
}
return result;
}
console.log(power(4)); //power auto sets second parameter to undefined
console.log(power(4,3));
// upside: flexible
// downside: hard to control the error
##Closure Look at this example:
function sayHello(name){
var text = 'Hello' + name;
var say = function(){
console.log(text);
}
return say;
}
var say2 = sayHello("ahaha");
say2();
if in C program, is say2() work? The answer is nope! Because in C program, when a function return, then the Stack-flame will be destroyed, and all the local variable such as text will undefinded. So, when say2() is called, there is no text anymore, and the error, will be shown!
But, in JavaScript, This code works!! Because, it provides for us an Object called Closure! Closure is borned when we define a function in another function, it keep all the live local variable. So, when say2() is called, the closure will give all the value of local variable outside it, and text will be identity.! What an geek!
##5. Recursion
// RECURSION
// A function can call itself, as long as it is not overflow
// call stack
// A function call itself and not overflow called Recursion
function power(base, exponent){
if (exponent == 0){
return 1;
}
else{
return base * power(base, exponent -1);
}
}
console.log(power(2,3));
function FindSolution(target){
function Find(start, history){
if (start == target){
return history;
}
else if (start > target){
return null;
}
else{
return Find(start + 5, "(" + history + " + 5 ") ||
Find(start * 3, "(" + history + " * 3)");
}
}
return Find(1, "1");
}
console.log(FindSolution(25));