JavaScript Functions
A function is a group of statements that perform specific tasks and can be kept and maintained separately from the main program. JavaScript functions provide a way to create reusable code packages which are more portable and easier to debug. Here are some advantages of using functions:
Functions reduce the repetition of code within a program. Functions make the code much easier to maintain. Functions make it easier to eliminate errors.
Defining and Calling a Function
The declaration of a function starts with the function keyword, followed by the name of the function you want to create, followed by parentheses i.e. (), and finally, place your function’s code between curly brackets {}. Here’s the basic syntax for declaring a function:
function functionName() { // Code to be executed
}
Adding Parameters to Functions
You can specify parameters when you define your function to accept input values at run time. The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.
Parameters are set on the first line of the function inside the set of parentheses, like this:
function functionName(parameter1, parameter2, parameter3) {
// Code to be executed
}
You can define as many parameters as you like. However, for each parameter, you specify, a corresponding argument needs to be passed to the function when it is called, otherwise, its value becomes undefined.
Returning Values from a Function
A function can return a value back to the script that called the function, as a result, using the return statement. The value may be of any type, including arrays and objects.
The return statement usually placed as the last line of the function before the closing curly bracket and ends with a semicolon.
A function can not return multiple values. However, you can obtain similar results by returning an array of values.
If you liked our content JavaScript Functions, then you will also likeĀ Loops in JavaScript
Leave a Reply