JavaScript Variables:
You do not have to "declare" a variable name before using it but you should!
A variable declared inside a function is a "local variable". A variable declared
outside of a function is a "global variable". In JavaScript there is only ONE type
of variable. It is a "var". But JavaScript does understand VALUE types.
|
STRING: a sequence of characters (text)
|
var strMyText = "I put this in quotation marks." |
|
INTEGER: a number without a decimal |
var intNumber = 59 |
|
DECIMAL: a number with a decimal |
var decMyDecimal = 7.83 |
Variables as Integers:
Add two numbers by declaring a variable for each integer. Next, create an alert
with a function to add the two numbers together.
var intNum1 = 2;
var intNum2 = 5;
alert (intNum1 + intNum2); will give me 7
Variables as Strings:
Combine two strings together (concatenate)by giving each string a variable name and then create an alert
function that joins the two strings into one.
var intNum1 = "2";
var intNum2 = "5";
alert(intNum1 + intNum2);
Converting Variable Types
Convert Number to String might give you unexpected results. The code below will return 25 because of the "" in the middle JavaScript will convert the Integers
to Strings.
alert(intNum1 + " " + intNum2);
Convert String to Number:
You can convert a string into a number if you need to add it or use it to count. The "parseInt" is a JavaScript built in function that converts a String to an Integer!
(returns an Integer from a String).
alert(parseInt(intNum1) +parseInt( intNum2) )
"Not A Number"
There may be times you need to check and see if your variable is not a number. JavaScript provides
a method for that using the NaN keyword. NaN is returned if it's "not a number".
parseInt("abc") NaN
parseInt("12abc") - returns 12
(the numeric value only!!)