----: Functions In JavaScript :----
Function Definition
Calling a function
Function Parameter
Function Arguments
Function Expression
Return Keyword
Anonymous Function
A javascript function is a block of code design to perform
a perticular task.
Function Defination :-
Before we use a function , we need to define it.
A function defination (also called a function declaration
, or function statement) , consists of the functions keyword , Followed By :
The name of the function
The list of parameter to the function, enclosed in parentheses and separated by commas.
The javascript statement that defiend the function,enclosed in curly barkets {...}
function sum (){
var a = 10;
var b = 20;
var total = a+b;
console.log(total);
}
Calling Functions :-
Defining a function does not execute it.
A javaScript function is executed when 'something' invokes it (calls it).
function sum (){
var a = 10;
var b = 20;
var total = a+b;
console.log(total);
}
sum();
Challenge Time :-
Q. What is difference between function parameter vs function Arguments.
Function parameters are the names listed in the function's defination.
Function arguments are the real values passed to the function.
function sum(a,b) { // (a,b) is parameters
var total = a+b;
console.log(total);
}
sum();
sum(8,9) // (8,9) is arguments
sum(4,8);
Interview Questions:-
Q. Why functions?
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.
OR
A function os a group of reusable code which can be called anywhere
in your program. This eliminates the need of writing the same code
again and again.
DRY => Do Not Repeat Yourself.
Function Expression :-
Function expression simply means
Create a function and put it into variables
function sum(a,b) {
var total = a+b;
console.log(total);
}
var funExp = sum(5,10);
Return Keyword :-
When JavaScript reaches a return statement,
the function will stop executing.
Function often compute a return value.
The return value is "returned" back to the "caller"
ex.
function sum(a,b) {
return total = a+b;
}
var funExp = sum(10,4);
console.log("The sum of 10 and 4 are " + funExp);
ex.
function sum (a,b){
return total = a+b;
}
var funExp = sum(2,2);
console.log("The sum of 2 and 2 are " + funExp);
Anonymous Function :-
A function expression is similar to and has the same syntax
as a function declaration one can defined "named"
function expression (where the name of the expression might
be used in the call stack for example )
or "anonymous" function expressions.
Function without name is called anonymous function.
var funExp = function(a,b){
return total = a+b;
}
var sum = funExp(15,15);
var sum1 = funExp(13,15);
console.log("The sum of two no. is" + sum);