Passing Parameter in Function

In JavaScript, you can pass parameters to functions, allowing you to provide data or values that the function can use during its execution. Parameters are specified in the function declaration or definition, and they act as placeholders for the values that will be passed when the function is called.

The syntax of function is:

// Function is called, the return value will end up in x
data_type variable = myFunction(parameter);
function func-name(parameter) {
    // Function returns the product of a and b
    return operation;
}

Here's an explanation of how to pass parameters to functions in JavaScript:

Function Declaration

Function declarations define the structure of the function, including its name and parameters. Parameters are enclosed in parentheses following the function name.

Example:

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

In this example, the greet function is declared with a name parameter. This parameter represents the value that will be passed to the function when it is called.

Function Call

When calling a function, you provide the actual values, called arguments, for the parameters declared in the function definition. Arguments are enclosed in parentheses following the function name.

Example :

greet('John');

In this example, the greet function is called with the argument 'John'. The argument 'John' is passed to the name parameter in the function declaration.

Multiple Parameters

Functions in JavaScript can accept multiple parameters by separating them with commas in the function declaration. When calling the function, you provide corresponding values for each parameter in the same order.

Example:

function sum(a, b) {
    console.log(a + b);
}
sum(5, 3);

In this example, the sum function is defined with two parameters, a and b. When the function is called with arguments 5 and 3, the values are assigned to a and b respectively, and their sum is printed to the console.

Conclusion

Passing parameters to functions in JavaScript allows you to provide input or data to the function's logic, making the function more versatile and reusable. You can pass different values to the same function, enabling it to perform different actions based on the provided arguments.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs