DEV Community

Sajin Joe J
Sajin Joe J

Posted on

Function in javascript

In JavaScript, a function is a reusable block of code that performs a task. You define it once and can call it whenever you need it.

1. Basic function

function greet() {
  console.log("Hello!");
}

greet();
Enter fullscreen mode Exit fullscreen mode

Here, greet is the function name, and greet() calls the function.

2. Function with parameters
Parameters let you pass information into a function:

function greet(name) {
  console.log("Hello, " + name);
}

greet("John");
greet("Sara");
Enter fullscreen mode Exit fullscreen mode

Output :

Hello, John
Hello, Sara
Enter fullscreen mode Exit fullscreen mode

3. Returning a value
A function can calculate something and return the result:

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

let result = add(10, 20);

console.log(result); // 30
Enter fullscreen mode Exit fullscreen mode

a and b are parameters, while 10 and 20 are arguments.

4. Function expression
A function can also be stored in a variable:

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

console.log(add(5, 3)); // 8
Enter fullscreen mode Exit fullscreen mode

5. Arrow function
Modern JavaScript commonly uses arrow functions:

const add = (a, b) => {
  return a + b;
};
Enter fullscreen mode Exit fullscreen mode

For a simple return, you can shorten it:

const add = (a, b) => a + b;

console.log(add(5, 3)); // 8
Enter fullscreen mode Exit fullscreen mode

So the core idea is:

function functionName(parameters) {
  // code
  return result;
}

functionName(arguments);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)