eHow launches Android app: Get the best of eHow on the go.

How To

How to Declare a Variable in JavaScript

Contributor
By eHow Contributing Writer
(4 Ratings)

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.

Difficulty: Easy
Instructions

Things You'll Need:

  • JavaScript editor

    Declare a Variable in JavaScript

  1. Step 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. Step 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. Step 3

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

  4. Step 4

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

  5. Step 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.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

Demand Media
eHow_eHow Technology and Electronics