DEV Community

Hariharan S J
Hariharan S J

Posted on

Functions in JavaScript – Learn Once, Use Everywhere

1.Function Definition

A function is a set of instructions that performs a particular job when we call it.

(Or)

A function in JavaScript is a block of reusable code that is designed to perform a specific task. It runs only when it is called (invoked), and it helps to reduce code repetition, improve readability, and make programs easier to manage.

Example

function makeParotta() {
    console.log("Kothu Parotta is Ready");
}

makeParotta();  // calling the function
Enter fullscreen mode Exit fullscreen mode

2.Rules for Declaring a Function

  1. Starts with lower case

  2. No Space Allowed

  3. No Special Characters are allowed except Underscore(_) and Dollar($)

function myFunction() { }
function _test() { }
function $demo() { }
Enter fullscreen mode Exit fullscreen mode

JavaScript keywords cannot be used as function names

Reserved words like if, else, for, while, etc. cannot be used.

function if() { }   // ❌
function for() { }  // ❌
Enter fullscreen mode Exit fullscreen mode

Parameters in Function

Definition

Parameters are the variables listed in the function definition. They act as placeholders to receive values when the function is called.

function add(a, b) {   // a and b are parameters
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Here, a and b are parameters.

Arguments in Function

Definition

Arguments are the actual values passed to the function when calling it.

add(5, 3);   // 5 and 3 are arguments
Enter fullscreen mode Exit fullscreen mode

Here, 5 and 3 are arguments.

Simple One-Line Definition:

Parameter: Variable in function definition.

Argument: Value passed to the function.

Easy to Remember Trick:

P → Parameter → Placeholders
A → Argument → Actual values

Difference between Parameters and Arguments

Return Statement in a Function

A return statement gives the output of a function back to the caller.

(Or)

The return statement is used to send a value back from a function to the place where the function was called and stop the execution of the function.

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

let result = add(5, 3);
console.log(result);   // Output: 8
Enter fullscreen mode Exit fullscreen mode

Explanation

  • return a + b; → sends the value 8 back

  • result receives 8

Important Points

  1. A function can return only one value at a time.

  2. Any code after the return statement will not execute.

  3. If no return statement is used, the function returns undefined.

Top comments (0)