techStackGuru

JavaScript Functions


We frequently need to repeat a similar action throughout the script. The primary building blocks of the software are functions. They allow the code to be called several times without having to repeat it.


Advantages of function in the code

  • Less complex
  • It allow user to reuse the code
  • The usage of functions improves readability and understandability

A function is created with a function keyword

Syntax


function functionName(parameter1, parameter2, ... parameterN){  
    //code block  
}  

Lets take an example of function


function add() {
    console.log(2+3)
  }
  
 add();
Output

5

Function with parameters


function add(a,b) {
    console.log(a+b)
  }
  
 add(3,5);
Output

8

Function with return value


function add(a,b) {
    return a+b;
  }
  
const result = add(2,8);
  
console.log(result)
Output

10

previous-button
next-button