Functions in Javascript
A JavaScript function is a block of code designed to perform a particular task.
// function definition
function sum(){
var a = 10, b = 40;
var total = a+b;
console.log(total);
}
sum(); // calling function
Output: 50
Function Parameter & Function Arguments:
// a and b is parameter
function sum(a,b){
var total = a+b;
console.log(total);
}
sum(20,30); // argument is 20 and 30
sum(50,50); // argument is 50 and 50
Output: 50
100
Why to use functions?
A function is a group of reusable code that can be called anywhere in your program. This eliminates the need to write the same code again and again.
Good coding practice follows DRY => Do not repeat yourself so we use functions.
Function expressions
Function expressions simply mean to 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);
Output: 20
return keyword
When JavaScript reaches a return statement, the function will stop executing. Functions often compute a return value. The return value is "returned" back to the "caller".
function sum(a,b){
return total = a+b;
}
var funExp = sum(5,25);
console.log('the sum of two no is ' + funExp );
output: the sum of two no is 30
Anonymous Function
A function expression is similar 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 the call stack for example) or "anonymous" function expressions.
var funExp = function(a,b){
return total = a+b;
}
var sum = funExp(15,15);
var sum1 = funExp(20,15);
console.log(sum > sum1 );
Output: false
By delving into the depths of functions in JavaScript, you've embraced the essence of what it means to be a curious and passionate learner. Your eagerness to expand your knowledge and understanding fuels our own enthusiasm for sharing insights and discoveries with you
Happy Testing ??