Function Definition
A Function Definition or function statement starts with the function keyword and continues with the following.
- Function’s name.
- A list of function arguments contained in parenthesis and separated by commas.
- Statements are enclosed in curly brackets.
Syntax:
function name(arguments)
{
javascript statements
}
Function Calling:
Function Calling at a later point in the script, simply type the function’s name. By default, all JavaScript functions can utilize argument objects. Each parameter’s value is stored in an argument object. The argument object is similar to an array. Its values may be accessed using an index, much like an array. It does not, however, provide array methods.
function welcome() {
console.log("welcome to GfG");
}
// Function calling
welcome();
Output
welcome to GfG
Function Arguments:
A function can contain one or more arguments that are sent by the calling code and can be utilized within the function. Because JavaScript is a dynamically typed programming language, a Function Arguments can have any data type as a value.
function welcome(name) {
console.log("Hey " + "" + name + " " + "welcome to GfG");
}
// Passing arguments
welcome("Rohan");
Output
Hey Rohan welcome to GfG
Return Value:
A return statement is an optional part of a JavaScript function. If you wish to return a value from a function, you must do this. Return Value should be the final statement of a function.
function welcome() {
// Return statement
return "Welcome to GfG";
}
console.log(welcome());
Output
Welcome to GfG
Function Expression:
We may assign a function to a variable and then utilize that variable as a function in JavaScript. Function Expression is known as a function expression.
let welcome = function () {
return "Welcome to GfG";
}
let gfg = welcome();
console.log(gfg);
Output
Welcome to GfG
How to write a function in JavaScript ?
JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance code organization and maintainability.
Functions are one of JavaScript’s core building elements. In JavaScript, a function is comparable to a procedure—a series of words that performs a task or calculates a value—but for a process to qualify as a function, it must accept some input and produce an output with a clear link between the input and the result. To utilize a function, it must be defined in some place within the scope from which it will be called.