There are actually two literal forms of functions. The first is a function declaration, which begins with the function keyword and includes the name of the function immediately following it.
function add(num1, num2) {
return num1 + num2;
}
The second form is a function expression, which doesn’t require a name after function. These functions are considered anonymous because the function object itself has no name. Instead, function expressions are typically referenced via a variable or property, as in this expression:
var add = function(num1, num2) {
return num1 + num2;
};
Function hoisting
Function declarations are hoisted to the top of the context when the code is executed. That means you can actually define a function after it is used in code without generating an error.var result = add(5, 5);
function add(num1, num2) {
return num1 + num2;
}
Function hoisting happens only for function declarations because the function name is known ahead of time. Function expressions, on the other hand, cannot be hoisted because the functions can be referenced only through a variable. So this code causes an error:
// error!
var result = add(5, 5);
var add = function(num1, num2) {
return num1 + num2;
};
Functions as Values
function sayHi() {
console.log("Hi!");
}
sayHi(); // outputs "Hi!"
var sayHi2 = sayHi;
sayHi2(); // outputs "Hi!"
Parameters
You can pass any number of parameters to any function without causing an error. That’s because function parameters are actually stored as an array-like structure called arguments. The values are referenced via numeric indices, and there is a length property to determine how many values are present.function sum() {
var result = 0,
i = 0,
len = arguments.length;
while (i < len) {
result += arguments[i];
i++;
}
return result;
}
console.log(sum(1, 2)); // 3
console.log(sum(3, 4, 5, 6)); // 18
console.log(sum(50)); // 50
console.log(sum()); // 0
Overloading
The fact that functions don’t have signatures in JavaScript doesn’t mean you can’t mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do.function sayMessage(message) {
if (arguments.length === 0) {
message = "Default message";
}
console.log(message);
}
sayMessage("Hello!"); // outputs "Hello!"
0 comments:
Post a Comment