How to Declare a Variable in JavaScript

Variables in JavaScript, as in any programming language, hold the numbers, strings, and other values used by a program. They are declared using the var command.

Things You'll Need

  • JavaScript editor
Show More

Instructions

  1. Declare a Variable in JavaScript

    • 1

      Choose a variable name which meets JavaScript guidelines. Variables names can contain only numbers, letters, or underscores, and must start with a letter or underscore. The are case-sensitive: the variable ABC is distinct from abc.

    • 2

      Find the best place to declare your variable. Variables declared outside of a function are available to all commands throughout the entire script, and are called "global" while variables exclusive to a specific function are "local", declared inside the function.

    • 3

      Declare the variable using the var command, as follows:
      var my_variable;

    • 4

      Add additional variables to the declaration for compactness:
      var one_var, two_var;

    • 5

      Specify an initial value for the variable by following it with an equal sign and the value:
      var zero=0;

Tips & Warnings

  • Place global variables at the beginning of your scripts so that they're clearly defined and accessible to the commands that need them later on.

  • Although JavaScript does not require variables to be declared, it is always best to do so. Otherwise, you may end up inadvertently using the wrong value of a variable.

Related Searches:

Comments

You May Also Like

Related Ads

Featured