var
or alert
).firstName
, you will get an error if you try to call firstname
.//"Declaring" a variable with the keyword, 'var'...
var xyz;
//Assigning a value to a variable when we declare it...
var xyz = "Hello world!";
//We could name our variable 'xyz', but we should give it a name that describes the value that it is storing...
var userGreeting = "Hello world!";
//We retrieve a value from storage by calling the variable name (the label on the box)...
alert( userGreeting );
JavaScript treats different types of data in different ways. The main JavaScript data types are: String, Number, Boolean, Null, and Undefined. There are others, but these are the main ones.
true
or false
– not the word "true" or "false". Think: "on" or "off".null
(lowercase) is nothing. Not 0 (the number zero) or “” (an empty string), it is nothing.//"Declaring" a variable with a String value...
var myJob = "Web Developer";
var yearsExperience = 12; //Number data type - no quotes.
var salesTax = 0.13; //Number data type includes decimals.
var loggedIn = false; //Boolean. Only other possible value is true.
var customerObject = null; //Null data type.
var userInput; //Undefined data type. We have created a box with a label but its contents are undefined.
var myTotal = 12 + 8; //myTotal is 20
var newDebt = 400 - 150; //newDebt is 250
var totalBill = subTotal * salesTax; //Using variables. This is the power of variables!!
//Adding (concatenating) strings of text...
var myMessage = "Hello" + "world!";//This gives Helloworld with no space.
var userName = "Sam";
var userGreeting = "Hello" + " " + userName;//This adds a variable to static text. Note the empty space that solves the problem of the previous example.
//We have to be careful when concatenating strings with numbers because JavaScript will convert the Number into a String character.
var x = 8 + 8; //x is 16
var y = 8 + "8"; //y is 88. Specifically, the character eight beside the character 8, not the number 88.