Introduction to functions in JavaScript
Function for adding two numbes and returning the result
function add(x,y)
{
return x+y;
}
let result = add(3,2)
console.log(result);
Output
5
Handling Missing Parameters from within a function
function add(x,y)
{
if(y==undefined)
{
y=5;
}
return x+y;
}
let result = add(3)
console.log(result);
Output
8
Function with default parameters
function add(x,y=10)
{
return x+y;
}
let result = add(3,5)
console.log(result);
Output
8
Function with REST parameters
function add(...sat)
{
let sum=0
for(let x of sat)
{
sum+=x;
}
return sum;
}
let result = add(1,1,1,1,1,1)
console.log(result);
Output
6
Passing an Array to a function
function add(iarr)
{
let sum=0
for(var x of iarr)
{
sum+=x;
}
return sum;
}
const arr = [1,2,3,4,5,6]
let result = add(arr)
console.log(result)
Output
21