Functions
- A JavaSciprt function is a block of code designed to perform a particular task.
Function definition
- Before we a function, we need to define it.
- A function definition (also called a function declarartion, or function statement) consists of the function keyword, followed by :
- The name of the function.
- A list of parameters to the function, enclosed in parenthesis and separated by commas.
- The JavaSciprt statements that define the function, enclcosed in curly brackets, {....}.
// normally
var a = 10;
var b = 20;
var sum = a + b;
console.log(sum);
// using function
function sum(){
var a = 10, b = 40;
var total = a + b;
console.log(total);
}
Calling a function
- Defining a function does not execute it.
- A JavaSciprt function is executed when "something" invokes it (calls it).
function sum(){
var a = 10, b = 40;
var total = a + b;
console.log(total);
}
sum(); // function call
Function Parameter vs Function Arguments
- Function parameters are the names listed in the function's definition.
- Function arguments are the real values passed to the function.
function sum(a, b){
var total = a + b;
console.log(total);
}
sum(40, 60);
sum(20, 30);
Interview Question
- Why function?
- You can reuse code: Define the code once, and use it many times.
- You can use the same code many times with different arguments, to produce different results.
- A function is a group of reusable code which can be called anywhiere in your program. This eliminates the need of writing the same code again and again.
- DRY → Do not repeat yourself.
Function expressions
- "Function expressions simply means create a function and put it into the variable."
function sum(a, b){
var total = a + b;
console.log(total);
}
var funExp = sum(5, 15);
Return Keyword
- When JavaSciprt reaches a return statement, the function will stop executing.
- Function often compute a return value.
- The return value is "returned" vack to the "caller".
function sum(a, b){
return a + b;
}
var funExp = sum(5, 25);
Anonymous Function
- A function expression is similear to and has the same syntax as a function declaration, one can define "named" function expressions (where the name of the expression might be used in that stack) or "anonymous" function expressions.
var funExp = function(a, b){
return a + b;
}
var sum = funExp(15, 15);
var sum1 = funExp(20, 15);
console.log(sum > sum1);