Variables

Like other programming languages, JavaScript works with variables, which are basically named pieces of memory used to store data. Variables help you manipulate and change the data in your code.

It is important to remember that JavaScript is case-sensitive, so myVar is different from myvar.

When it comes to declaring a variable, JavaScript is a rather forgiving language. You can declare a variable, like this:

var aVariable;

or, you can declare and assign a value at the same time.

var aVariable = someValue

Bear in mind that JavaScript doesn’t care about the type of data stored in a variable. You can put into the same variable a string, an integer, a floating point number, or even an object. For example, consider the code in Listing B.2.

Listing B.2. Using variables
var myVar = 100;
document.write("myVar is an integer: " + myVar);
myVar = myVar + 23;
document.write("<br/>Now its value is: " + myVar);
myVar = "one hundred";
document.write("<br/>And now it is a string: " + myVar);
myVar = myVar + 23;
document.write("<br/>Finally, the string is modified: " + myVar);

The output of this script is this:

myVar is an integer: 100
Now its value is: 123
And now it is a string: one hundred
Finally, the string is modified: one hundred23

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset