Function:
The javascript function is a block of code designed to perform a particular task.
Syntax of function:
function functionName(parameter1, parameter2, parameter3) {
code to be executed/run
}
What are the parameters and arguments?
A parameter is an undefined variable in a function definition through which a function can accept data from an argument. A parameter is declared inside the parentheses of a function.
An argument is the value of a parameter where an argument is passed through the parameter.
To declare an argument, write a function name, give parenthesis, and write arguments inside the parentheses. These codes will be written outside of the function.
Arguments can be passed to the function as values or variables.
How does the function parameter work?
Information is received or passed through function parameters. It will be clear with the following example →
function cars(x){ document.write(x + " is a good car"); } cars("Ford");
Here,
Ford is information, and x (inside of parenthesis) is a parameter, and the information (Ford) is passed through parameter x, and information is received by x(inside the function body)
N.B→ information will send/received with a function name. For example- in the above example cars is a function.
Multiple parameters:
function cars(x1, x2, x3){
document.write(x1+"<br/>" + x2+"<br/>" + x3);
}
cars(" Ford", "Lamborghini", " Honda");
function cars(x){ document.write(x + " is a good car"); } cars("Ford");
The information Ford(an argument) is passed through an x1 parameter and received by x1 of a body of a function,
Lamborghini(an argument) is passed through an x2 parameter, received by x2 of the body of a function,
Honda(an argument) is passed through an x3 parameter, received by x3 of the body of a function.
Multiple arguments and multiple parameters must be separated by commas.
We can call a function for as much time as we want. For example…
function cars(x1, x2, x3){ document.write(x1+"<br/>" + x2+"<br/>" + x3); } cars(" Ford", "Lamborghini", " Honda"); cars (“Hero”, “Walton”, “Fujitsu”); cars (“Yamaha”, “Toyota”, “Ferrari”);
N.B→ we can use the same function name more than once e.g; cars function can be used multiple times to send information.
What function do we use?
Define the code once, and use it many times. We can use the same code many times with different arguments, to produce a different result.
function toCelsius(f) { return (5/9) * (f-32); } document.getElementById("demo").innerHTML = toCelsius(77);
The result is 25.
Post a Comment