How to Call a Function in JavaScript

Functions--named groups of statements that can be "called" or "invoked"--lie at the heart of JavaScript. Functions can be given special inputs, called "parameters" or "arguments", which control what they do. Once defined, a function can be called over and over again with different parameters. In JavaScript, functions are called by writing the name of the function followed by a pair of parentheses containing the parameters, if any.

Things You'll Need

  • JavaScript or text editor
Show More

Instructions

  1. Call a Function in JavaScript

    • 1

      Define the function to be called, using the following syntax. Or, identify an existing function that you want to call.
      function NAME (parameter 1, parameter 2, ...) { statement(s) }

    • 2

      Call the function by writing its name, a left parenthesis, parameters if any separated by commas, and a right parenthesis. For instance, to call the built-in alert function, simply code the following:
      alert("This is a call to the alert function.");

    • 3

      Call a function assigned to a variable by coding the variable's name, also followed by a parenthesized parameter list. Consider the following example:
      var back_or_forward = go_back ? history.back : history.forward;
      back_or_forward ();

    • 4

      Capture the return value from the function, if any, by placing the function call on the right side of an assignment statement, or anywhere else an expression is required. Examples:
      user_input = prompt("Your name");

Related Searches:

Comments

You May Also Like

Related Ads

Featured