DEV Community

Cover image for Function in JS
Vigneshwaran V
Vigneshwaran V

Posted on

Function in JS

What is function

A JavaScript function is a reusable block of code designed to perform a specific task. Instead of writing the same code multiple times, you wrap it inside a function and execute it whenever needed.

  • In JavaScript, functions are First-Class Objects, meaning they can be stored in variables, passed as arguments to other functions, and returned from other functions.

  • In JavaScript, a first-class object (or first-class citizen) means that a value can be treated like any other value in the language.

  • Because JavaScript treats functions just like other values such as numbers, strings, and objects.

Key Components of a Function

  • Definition: Creating the function using a specific syntax.

  • Parameters: Placeholder variables listed inside the parentheses () when defining the function.

  • Arguments: The actual values passed into the function when you run it.

  • Return Statement: An optional return keyword used to send a value back to where the function was called. It immediately stops function execution.

  • Invocation (Calling): Running the function by using its name followed by parentheses ().

Why Use Functions?

  • Code Reusability: Write your logic once and reuse it across your application.

  • Organization: Breaks down a complex program into smaller, manageable chunks.

  • Maintainability: If a task changes, you only need to update the code inside the function.

  • Scope Isolation: Variables defined inside a function are hidden from the outside world, preventing naming conflicts.

Example

function greet(name) {   // 'name' is a parameter
  console.log("Hello " + name);
}

greet("Alice");  // "Alice" is the argument
Enter fullscreen mode Exit fullscreen mode
  • Parameter: name (placeholder inside the function).

  • Argument: "Alice" (real value given at call time).

Default Parameters

  • Default parameters are used when no argument is provided during the function call.

  • If no value is passed, the function automatically uses the default value.

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

greet();           //Hello Guest
greet("Aman");    //Hello Aman
Enter fullscreen mode Exit fullscreen mode

Return Statement

  • The return statement is used to send a result back from a function.

  • When return executes, the function stops running at that point.

  • The returned value can be stored in a variable or used directly.

function add(a, b) {
  return a + b; // returns the sum
}

let result = add(5, 10);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Naming a function

In JavaScript, you can name a function using camelCase (most common convention).

Syntax

function functionName() {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Examples

function greetUser() {
    console.log("Hello User");
}

function calculateSum() {
    console.log(10 + 20);
}

function findLargestNumber() {
    console.log("Finding largest number");
}
Enter fullscreen mode Exit fullscreen mode

Naming rules

Can contain:

  • Letters (a-z, A-Z)

  • Numbers (0-9) (but not at the beginning)

  • _ (underscore)

  • $ (dollar sign)

function user1() {}
function _display() {}
function $calculate() {}
Enter fullscreen mode Exit fullscreen mode

Best Practices

Use names that describe what the function does:

function getUserData() {}
function calculateEMI() {}
function reverseNumber() {}
function checkLeapYear() {}
Enter fullscreen mode Exit fullscreen mode

Avoid unclear names:

function a() {}      // Bad
function xyz() {}    // Bad
Enter fullscreen mode Exit fullscreen mode
  • Function names should be meaningful, follow camelCase convention, start with a letter, _, or $, and clearly describe the purpose of the function.

Parameters

Parameters are variables listed in the function definition that receive values when the function is called.

function greet(name) {   // name is a parameter
    console.log("Hello " + name);
}

greet("Vicky");          // "Vicky" is an argument
Enter fullscreen mode Exit fullscreen mode
  • Parameter → Variable in the function definition.

  • Argument → Actual value passed to the function.

Types of Parameters

1. No Parameters

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

greet();
Enter fullscreen mode Exit fullscreen mode

2. Single Parameter

function square(num) {
    console.log(num * num);
}

square(5);
Enter fullscreen mode Exit fullscreen mode

3. Multiple Parameters

function add(a, b) {
    console.log(a + b);
}

add(10, 20);
Enter fullscreen mode Exit fullscreen mode

4. Default Parameters

  • If no argument is passed, the default value is used.
function greet(name = "Guest") {
    console.log("Hello " + name);
}

greet();         // Hello Guest
greet("Vicky");  // Hello Vicky
Enter fullscreen mode Exit fullscreen mode

5. Rest Parameters (...)

Used when you don't know how many arguments will be passed.

function sum(...numbers) {
    console.log(numbers);
}

sum(10, 20, 30, 40);
Enter fullscreen mode Exit fullscreen mode

Output:

[10, 20, 30, 40]
Enter fullscreen mode Exit fullscreen mode

Common Cases

Case 1: Correct Number of Arguments

function add(a, b) {
    console.log(a + b);
}

add(10, 20);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Case 2: Fewer Arguments than Parameters

function add(a, b) {
    console.log(a, b);
}

add(10);
Enter fullscreen mode Exit fullscreen mode

Output:

10 undefined
Enter fullscreen mode Exit fullscreen mode

Because b did not receive a value.

Case 3: More Arguments than Parameters

function add(a, b) {
    console.log(a, b);
}

add(10, 20, 30, 40);
Enter fullscreen mode Exit fullscreen mode

Output:

10 20
Enter fullscreen mode Exit fullscreen mode

Extra arguments are ignored (unless using rest parameters).

Case 4: Passing Different Data Types

function display(value) {
    console.log(value);
}

display(100);
display("Hello");
display(true);
Enter fullscreen mode Exit fullscreen mode

Parameter and Argument

function multiply(a, b) { // Parameters
    return a * b;
}

multiply(5, 4);           // Arguments
Enter fullscreen mode Exit fullscreen mode
  • Parameters are variables declared in a function definition that receive values (arguments) when the function is called. JavaScript supports normal parameters, multiple parameters, default parameters, and rest parameters.

Formal Arguments and Actual Arguments

function multiply(x, y) {   // Formal arguments
    return x * y;
}

multiply(5, 4);             // Actual arguments
Enter fullscreen mode Exit fullscreen mode
  • Formal arguments (parameters) are the variables declared in a function definition. Actual arguments are the real values passed to the function when it is called.

  • Parameters, also called formal arguments, are the variables declared in a function definition that receive values from the Actual arguments passed during a function call.

Return Statement in JavaScript

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

Syntax

function functionName() {
    return value;
}
Enter fullscreen mode Exit fullscreen mode

Uses of return

1. Return a Value

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

let result = add(10, 20);
console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

2. Store the Returned Value

function square(num) {
    return num * num;
}

let answer = square(5);
console.log(answer);
Enter fullscreen mode Exit fullscreen mode

Output:

25
Enter fullscreen mode Exit fullscreen mode

3. Use Returned Value in Another Expression

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

console.log(add(10, 20) * 2);
Enter fullscreen mode Exit fullscreen mode

Output:

60
Enter fullscreen mode Exit fullscreen mode

return Stops Function Execution

function test() {
    console.log("Start");
    return;
    console.log("End");
}

test();
Enter fullscreen mode Exit fullscreen mode

Output:

Start
Enter fullscreen mode Exit fullscreen mode

The code after return is never executed.

Multiple Returns with Conditions

function check(num) {
    if (num > 0) {
        return "Positive";
    }
    return "Negative or Zero";
}
Enter fullscreen mode Exit fullscreen mode

Only one return statement executes during a function call.

  • The return statement is used to exit a function and send a value back to the function caller. It can return any JavaScript data type such as Number, String, Boolean, Object, Array, Function, or undefined. The return statement also immediately stops further execution of the function.

Hoisting in Functions

Hoisting means JavaScript moves declarations to the top of their scope before executing the code.

1. Function Declaration → Hoisted

You can call the function before it is defined.

greet();

function greet() {
    console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Hello
Enter fullscreen mode Exit fullscreen mode

Why?
JavaScript internally treats it like:

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

greet();
Enter fullscreen mode Exit fullscreen mode

So function declarations are fully hoisted.

2. Function Expression with var → Partially Hoisted

greet();

var greet = function() {
    console.log("Hello");
};
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: greet is not a function
Enter fullscreen mode Exit fullscreen mode

Why?
Only the variable declaration is hoisted:

var greet; // hoisted

greet();   // undefined()

greet = function() {
    console.log("Hello");
};
Enter fullscreen mode Exit fullscreen mode

So greet exists, but it is undefined when called.

3. Function Expression with let → Not Usable Before Declaration

greet();

let greet = function() {
    console.log("Hello");
};
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError
Enter fullscreen mode Exit fullscreen mode

Because let is in the Temporal Dead Zone (TDZ) until its declaration is reached.

  • Function declarations are fully hoisted, so they can be called before their declaration. Function expressions and arrow functions are not fully hoisted; only variables declared with var are hoisted as undefined, while let and const remain in the Temporal Dead Zone until their declaration is reached.

References

https://www.programiz.com/javascript/function
https://www.geeksforgeeks.org/javascript/functions-in-javascript/

Top comments (0)