DEV Community

Abinaya V
Abinaya V

Posted on

“Function in JavaScript and its types”

function

In JavaScript, a function is a block of code designed to perform a specific task. It runs only when it is called (invoked).
Think of a function as a reusable piece of code—you write it once and use it many times.

Basic Syntax

function functionName() {
// code to execute
}
Example
function greet() {
console.log("Hello!");
}

greet();

Function with Parameters

You can pass values (called parameters) into a function:
function greet(name) {
console.log("Hello " + name);
}

greet("abi");

output:
Hello abi

Function with Return Value

function add(a, b) {
return a + b;
}

let result = add(3, 5);

output:
8

Types of Functions in JavaScript

Function Declaration(version 1)

 function add (no1,no2){
    return no+1no+2;
 }
Enter fullscreen mode Exit fullscreen mode

Function Expression(version 2)

 const add =function(no+no2){
    return no1+no2;
Enter fullscreen mode Exit fullscreen mode

}

Arrow Function(version 3)

 function greeting(name){
Enter fullscreen mode Exit fullscreen mode

return"good moring"+name;
}
short version for arrowtype

program 1 for use one argument

const greeting =name=>"good morning"+name;
console.log (greeting("abi"));

program 2 for use two argument

const add=(no1,no2)=>no1+no2
console.log(add(5,10);

Program for More than one line code

const add(no1,no2)=>{
let result=no1,no2;
return result;
}

Top comments (0)