Functions in javaScript.

Functions in javaScript.

What is function ?

A function is a block of code in a programming language that performs a specific or predefined task whenever we call it in our program. We can also say a function is a reusable block of code that can be executed whenever needed.

Advantages of using Function :

  1. Code reusability.

  2. Perform repetitive tasks.

  3. Make your code more readable.

How to Declare a Function

In JavaScript, you can declare a function in a few different ways, but most commonly, you use the function keyword.

Here’s the basic syntax to declare a function:

function functionName() {
  // code to be executed
}
// Example 
function Greeting(){
 console.log("Hello Coders") 
}
Greeting() // Output :  Hello Coders

Function With Parameters: You can make function more useful by passing in parameter. Parameter is a like a placeholders which allows you to pass input to the function.

function Greeting(firstName, lastName) {
   console.log("Hello," + firstName + " " + lastName)
}
Greeting("Ankesh","Kumar")

Return Values from Functions

Functions can also return values. This means that after performing some operations, the function can give back a result that you can use in other parts of your code.

Here’s an example of a function that adds two numbers and returns the result:

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

let sum = add(5, 3);
console.log(sum);  // Output: 8

Now Let us See Types of Function In JavaScript :

Arrow Function :-

Here’s an example of an arrow function that multiplies two numbers:

const multiply = (a, b) => a * b;

let result = multiply(4, 2);
console.log(result);  // Output: 8

Function Expressions

In JavaScript, functions can also be assigned to variables. These are called function expressions.

Here’s an example:

const multiply = function(a, b) {
  return a * b;
};

let result = multiply(4, 2);
console.log(result);  // Output: 8

For More details click here :