Functions with parameters
A parameter is a special kind of variable, used in a function to refer to a piece of data provided as input to the function.
Let's see some examples of functions that have parameters:
String as input parameter
function sayHello(name) {
console.log("Hello! " + name);
}
// call the function with required input data
sayHello('Emily')
Run the function by calling it's name and providing necessary input values to it's parameters. In the above example, string value 'Emily'
is provided to parameter name
.
Run, console result:
Hello! Emily
Note that in the console.log
line, we input "Hello! " + name
, the plus + sign indicates that we are going to use name
as a string since only a string can be added to string "Hello! "
.
Number as input parameter
function addTwo(x) {
console.log(2 + x);
}
// call the function
addTwo(10) // console result: 12
addTwo(20) // console result: 22
Inside the function definition, console.log(2 + x)
requires that x
needs to be a number.