How JavaScript variables work

You create a variable by declaring it. After you declare the variable you have to assign a value to it using JavaScript assignment operator.

To declare a variable you use the var keyword which tells the browser that the text to follow is the name of a new variable. A semicolon must end the statement!

You can assign a value to your variable when you declare it or later in the script. To assign a value to your variable you use the JavaScript assignment operator equal to (=).

var motorbikeprice = 3420;

The statement begins with the var keyword (which tells the browser that what follows is the name of the variable), followed by the name of the variable, the assignment operator (=) (which tells the browser to assign the value from the right of the operator to the variable from the left of the operator), and the value of the variable. The statement ends with a semicolon.

The JavaScript assignment operator (=) does not mean is equal to. The operator is equal to is two equal signs ==.

When naming your variables you need to consider four things:

  • Case sensitivity – motorbikeprice, MotorbikePrice, MOTORBIKEPRICE, and MoToRbIkEpRiCe are four different variables.
  • Invalid characters – Name of a variable must begin with a letter or an underscore. Empty spaces are not allowed in variable names.
  • Names reserved by JavaScript – There are words reserved by JavaScript and they can not be used as names of variables (See below the JavaScript reserved words).
  • Meaningful and easy to remember names.

JavaScript reserved words are:
abstract, as boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extend, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int,interface, is, long, namespace, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, use, var, void, volatile, while, with.

Leave a Reply