Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the above syntax to create a function in JavaScript. A function definition is sometimes also termed a function declaration or function statement. Below are the rules for creating a function in JavaScript:
- Every function should begin with the keyword function followed by,
- A user-defined function name that should be unique,
- A list of parameters enclosed within parentheses and separated by commas,
- A list of statements composing the body of the function enclosed within curly braces {}.
Example: This example shows a basic declaration of a function in javascript.
function calcAddition(number1, number2) {
return number1 + number2;
}
console.log(calcAddition(6,9));
Output
15
In the above example, we have created a function named calcAddition,
- This function accepts two numbers as parameters and returns the addition of these two numbers.
- Accessing the function with just the function name without () will return the function object instead of the function result.
There are three ways of writing a function in JavaScript:
Function Declaration: It declares a function with a function keyword. The function declaration must have a function name.
Syntax:
function w3wiki(paramA, paramB) {
// Set of statements
}
Functions in JavaScript
A JavaScript function is a block of code designed to perform a particular task. It encapsulates a set of instructions that can be reused throughout a program. Functions can take parameters, execute statements, and return values, enabling code organization, modularity, and reusability in JavaScript programming.
A JavaScript function is executed when “something” invokes it (calls it).
Example: A basic javascript function, here we create a function that divides the 1st element by the second element.
function myFunction(g1, g2) {
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);
Output
4
Output:
4
You must already have seen some commonly used functions in JavaScript like alert(), which is a built-in function in JavaScript. But JavaScript allows us to create user-defined functions also. We can create functions in JavaScript using the keyword `function`.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function, separated by the name of the function and parameters within parenthesis. The part of the function inside the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for assignments, or calculations.