Functions in JavaScript

Important points to note about functions are given below

  1. There are mainly 2 types of functions - named and anonymous
  2. Function can return a value
  3. Primitive types of parameters are passed to function by value
  4. Reference type of Parameters are passed to function by reference
  5. We can also set the default parameter to function
  6. ... notation can be used to mark the variable length parameter

Function definition Examples

//standard functions
function calculate(){
console.log("calculate something")
}
calculate();

//Assigning function to variable.
let f1 = function calculate(){
    console.log("calculate something")
}
f1();

//Anonymous function
let p = function(){
    console.log("do stuff in anonymous function")
}
p();

//fat arrow syntax
p = () => {console.log("fat arrow syntax")}
p()

Function Parameters Examples

Below examples show how to pass the parameters to JavaScript functions. We have also demonstrated how to set default parameter and variable number of parameters.

//Passing param
function add(a,b){
    return a + b;
}
let result = add(2,3)
console.log(result) // output - 5

//Default param
function addDefault(a,b=2){
    return a + b;
}
result = addDefault(4)
console.log("Default param addition - > " + result) // output - 6

//Variable number of params
function addVariableParams(...a){
    let result = 0;
    for(let i=0;i<a.length;i++){
        result += a[i];
    }
    return result;
}
result = addVariableParams(4,5,7,5)
console.log("Variable param addition -  " + result) // output - 21
Youtube | Facebook | Twitter | Website Home | Online Grocery Shopping Brisbane