Functions
Functions
JavaScript Functions, just like in any other language, is a set of statements that are used to
perform a specific task, like adding two numbers, finding the square of a number, or any
user-defined task.
● For instance, suppose you want to add some numbers and display the results on a web
page. In that case, you can define the code for adding the numbers in a function and call
the function whenever needed.
● For repetitive tasks like displaying a message whenever a web page is loaded into the
browser, we can use functions.
1. Code reusability: We can call a function several times in a script to perform their tasks so
it saves coding.
2. Less coding: It makes our program compact. We don't need to write many lines of code
each time to perform a common task.
In JavaScript, function is defined by using the function keyword followed by the function
name and parentheses ( ), to hold params(inputs) if any. A function can have zero or more
parameters separated by commas.The function body is enclosed within curly braces just
after the function declaration
part(function name and params), and at the end of the function body, we can have
a return statement to return some output, if we want.
where, function_name represents the name of the function and parameter-1, ... ,
parameter-n represents list of parameters.
● Calling a User-defined Function:
After creating a function, we can call it anywhere in our script. The syntax for calling a
function is given below:
function_name(val-1, val-2, ..., val-n);
Here, list of parameters represents the values passed to the funtion during function call.
return value;
The return keyword returns the value to the calling statement.