Skip to content

JavaScript function arguments | Example code

  • by

JavaScript Function arguments are nothing just real values passed to (and received by) the function. Function parameters are the names listed in the function definition.

function functionName(parameter1, parameter2, parameter3) {
  // code to be executed
}

Note: You can’t specify data types for parameters.

JavaScript function arguments

A simple example code finds the largest number.

<!DOCTYPE html>
<html>
<body>
  <script>

    function max( var1, var2, var3 ) {
      if( var1 > var2 ) {
        if( var1 > var3 ) {
          return var1;
        }
        else {
          return var3;
        }
      }
      else {
        if( var2 > var3 ) {
          return var2;
        }
        else {
          return var3;
        }
      }
    } 

    console.log("Largest Argument",max(2,6,3))
  </script>

</body>
</html> 

Output:

JavaScript function arguments

Default Parameters

The default parameters are used to initialize the named parameters with default values in case no value or undefined is passed. Where the missing values are set to undefined automatic.

<script>
    function myFunction(x, y = 2) {
      return x*y;
    }

    console.log(myFunction(2,))
</script>

Output: 2

Arguments Object

JavaScript functions have a built-in object called the arguments object. It contains an array of the arguments used when the function was called (invoked).

<script>
    x = findMax(1, 20, 5, 10, 30, 25);

    function findMax() {
      let max = -Infinity;
      for (let i = 0; i < arguments.length; i++) {
        if (arguments[i] > max) {
          max = arguments[i];
        }
      }
      return max;
    }

    console.log(x)
</script>

Output: 30

Note: The syntax function.arguments is deprecated. The recommended way to access the arguments object available within functions is to refer to the variable arguments.

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading