Notice the semi-colon (;) at the end of the line to indicate the end of the statement. The above declares a variable but doesn’t place any value in it. You can think of it as just an empty box waiting for content. We can put a value in the box (assign a value) using equals (=) as follows:
var firstName = "Martin";
Notice that the value “Martin” appears in quotes. This is to indicate that the value is text – or to use the more techie term – what we call a ‘string’. Note that when you assign a string/text value you can use double quotes, as above, or single quotes just as long as they pair up.
If you were wanting to place a numeric value in a variable there is no need for the quotes.
var age= 21;
Warning: Beware if you did use quotes in the above example it would be treated as string and not a number.
You probably want to see something happen in the web browser now so take a look at this page.
Alerts and Console
In the example linked to above the value of a variable is sent to the alert() method. Methods in a programming language represent doing words / verbs – and are things that you can do – sometimes requiring a value, sometimes that value taking the shape of a variable.
var surname = "Cooper"; alert(surname);
If you want to try this yourself create a simple HTML page and add the following before the closing body tag – that is the </body>.
There is a simple example here for you to use.
You can also make use of jsfiddle to play with code. Here is the simple
alert() example from above:
As well as
console(). Modern browsers like Chrome, Safari, IE9 and Firefox tend to have a ‘console’ often found as part of an Inspector. This is a pane that appears at the bottom of the browser window. For example, in Google Chrome if you right-click anywhere in the page you will be offered a menu with ‘Inspect Element’ as an option. When you select this you will see the Inspector appear at the bottom of the browser window. The Console tab is on the right.
Try changing the code in the simple example to the following:
var surname = "Cooper"; console.info(surname);
This time you will see the value of
surname placed in the console window. This is a neater way of seeing what is going on in your code rather than to continually have to click on alert boxes.
The <script> Tag