Variables in JavaScript

A variable is a named container that can hold a single value. The value can be changed at any time.

Declaration

In order to use a variable in our JavaScript code, we must first declare it. Use the var keyword to declare a variable, followed by some whitespace, and then the variable name (x), finishing off with the end-of-statement symbol (;):

var x;

Test the Declaration

If we were to Run the above code as it is, it will finish and provide no feedback. So we will add a simple line of test code, using the JavaScript console.log() function:

var x;
console.log("x = " + x);

The above code adds the following text to the Console:

"x = undefined"

The initial value for the variable x was never specified, so it has no value (undefined in JavaScript). It is common to both declare and initialize a variable at the same time.

Initialized Declaration

In order to declare and initialize a variable, start with the var keyword, add whitespace, add the variable name (x), add the assignment operator (=), followed by the initial value of the variable (0), and finishing off with the end-of-statement symbol (;):

var x=0;

Test the Initialized Declaration

var x=0;
console.log("x = " + x);

The above code adds the following text to the Console:

"x = 0"

Link to sandbox code:
https://jsfiddle.net/clean_blue_dot/pyjx96bz/7/

Leave a Reply