DEV Community

Madhavan G
Madhavan G

Posted on

Function in JavaScript.

What is Functions in JavaScript?

•Functions are reusable code blocks designed for particular tasks,You define it once, and then you can "call"(run) it whenever needed and it can be called multiple times as user want it.

•Functions are executed when they are called.

•Functions are fundamental in all programming languages.

Function Parameters:
•Parameters allow you to send values to a function.

•Parameters are listed in parentheses() in the function definition.

What Does a Function Look Like?

•A function can be created with the function keyword, a name, and parentheses.

•The code to run is written inside curly brackets.

Example:

function addNumbers(a, b)
{
let sum = a + b;
return sum;
}
•The function above does not do anything.
•It has to be called first.

let result = addNumbers(5, 3);
console.log(result);

•Now the above code will run.

What’s happening in this Code:

1. Function Declaration:

⇒function addNumbers(a, b)
•You define a function named addNumbers.
•It takes two parameters: a and b.
•Think of parameters as placeholders or container for values.

2. Function Body Executes When Called:
⇒let sum = a + b;
•Inside the function, a variable sum is created.
•It adds the values of a and b.

3. Returning a Value:
⇒return sum;
•The function sends the result back to wherever it was called.
•Without return, the function would give undefined.

4.Calling the Function:
⇒let result = addNumbers(5, 3);
•The function is called (invoked) with values 5 and 3.
•These values replace a and b:
⇒a = 5
⇒b = 3

5.Execution Inside the Function:
⇒sum = 5 + 3
•sum = 8
•return 8

6.Storing the Result:
⇒let result = 8;
•The returned value (8) is stored in result.

7.Output to Console:
⇒console.log(result);
•Prints: 8

Reference:https://www.w3schools.com/js/js_functions.asp

Top comments (0)