Ok.. let's get a bit more in-depth.
VARIABLES:
A variable is basically a data container whose contents can be changed as needed. If I create a variable called
whatever, like so:
...I can put lot of kinds of data into it by assigning it with the assignment operator, a single equals sign:
Code:
whatever = "Some data";
whatever = 1122363723;
whatever = 'c';
whatever = prompt("Are you stupid");
The first line above is assigning a
string to the variable. A
string is just a collection of alphanumeric characters in a certain order. This phrase is a string. When working with a string, the data needs to be enclosed in "quotation marks." This is probably the kind of variable you'll work with the most.
The second line assigns a number value to variable. Pretty straightforward.
The third assigns a character, which is just any single alphanumeric character. These need to be enclosed in single-quotes. In Javascript, a character is just like a string that is only one character long.
The fourth example above assigns the
return value of the function to the variable. That return value may be a string, number, whatever.
COMMENTS: I'll take a quick aside here and mention comments... on any given line of code, if you put two slashes (//), then everything after that point on that line will be ignored, so you can insert comments. I'll use these in the example below. You can also put comments inside of /* and */, and then the comment can span multiple lines.
Any time you use a variable name in your code, the value currently contained in the variable will be substituted. Example:
Code:
var myNumber = 0;
myNumber = 1 + 5; // Variable myNumber now equals 6
myNumber = myNumber + 10; // myNumber now equals 16
var newNumber = myNumber + myNumber; //newNumber = 32, myNumber still equals 16
A variable can be named whatever you want, as long as the first character of the name isn't a number, and there are no spaces in the name. Varaiable names are case-sensitive, so a variable called
TEST cannot be referenced as
Test or
test. The following are all valid and unique names:
Code:
var Test;
var test;
var TEST;
var _TEST_;
var Test2;
var testingIsAFunThingToDoInJavascript;
As written, these variables will all conain the special value
undefined, because I didnt set any value to them with the assignment operator, the equals sign.
As a general rule, try to use logical names for your variables, so you can remember what you're using them for. A variable called
it isn't nearly as descriptive as
bookTitle or
softwareVersion. The extra keystrokes are worth it.
You'll also notice that with multi-word variable names in my sample code, I don't capitalize the first letter of the first word, but I do the first letter of every subsequent word (see above). This is common practice in several programming languages, but is not required. Function names follow a similar practice, except that the first letter IS captialized.
Next up: Objects. Unless I think of something else I should mention first.