JavaScript Function Parameters

Back to JS page

Table of Contents

Parameters (Function Input)

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Parameters</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Parameters (Function Input)</h4>
<p id="demo"></p>

<script>
function myFunction(firstName, lastName) {
  return "Hello " + firstName + " " + lastName;
}
document.getElementById("demo").innerHTML = myFunction("John", "Doe");
</script>

</body>
</html>

Example 1

Result View Example

Functions with One Parameter

A function can have a single parameter:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Parameters</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Functions with One Parameter</h4>
<p id="demo"></p>

<script>
function square(x) {
  return x * x;
}
document.getElementById("demo").innerHTML = "Square of 5: " + square(5);
</script>

</body>
</html>

Example 2

Result View Example

Functions with Multiple Parameters

A function can have multiple parameters separated by commas:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Parameters</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Functions with Multiple Parameters</h4>
<p id="demo"></p>

<script>
function sum(a, b, c) {
  return a + b + c;
}
document.getElementById("demo").innerHTML = "Sum of 5, 10, 15 = " + sum(5, 10, 15);
</script>

</body>
</html>

Example 3

Result View Example

Incorrect Parameters

If a function is called with missing arguments (fewer than declared), the missing values are set to undefined:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Parameters</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Incorrect Parameters</h4>
<p id="demo"></p>

<script>
function multiply(a, b) {
  return a * b;
}
// Only one argument passed, b will be undefined
document.getElementById("demo").innerHTML = "multiply(5) = " + multiply(5) + " (NaN because b is undefined)";
</script>

</body>
</html>

Example 4

Result View Example

Default Parameter Values

ES6 allows function parameters to have default values:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function Parameters</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Default Parameter Values</h4>
<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction(x, y = 10) {
  return x + y;
}
document.getElementById("demo1").innerHTML = "myFunction(5) = " + myFunction(5);
document.getElementById("demo2").innerHTML = "myFunction(5, 3) = " + myFunction(5, 3);
</script>

</body>
</html>

Example 5

Result View Example

Document

Document in project

You can Download PDF file.

Reference