Functions in JavaScript

Important points to note about functions are given below
  • There are mainly 2 types of functions - named and anonymous
  • Function can return a value
  • Primitive types of parameters are passed to function by value
  • Reference type of Parameters are passed to function by reference
  • We can also set the default parameter to function
  • ... notation can be used to mark the variable length parameter

Function definition Examples

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

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

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

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

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

Complex problems, Simple Solutions