html / xhtml, css, php, mysql, javascript, asp, seo, web management, semantics, accessibility and more.
Part 2 of Beginner JavaScript. This tutorial shows you how to use the basics of JS. Using functions, variables and arrays.
In category javascript.
Posted by Gunny on 05.03.06.
What are strings? You've used them before, and you will continue using them through your whole JS career.
What are they? Typically, they are used after functions (such as alert) to list what appears in the function.
But constantly typing out strings can get annoying. If you chose to start coding in PBJS, you'll use the document.getElementsByTagName('td') function. Now, in even in the simplest codes, you'll need to put this in at least five times. It gets annoying I guarantee.
So you use a variable.
Variables are used to store data in JS, and typically take the place of strings.
The var part tells JS that this is a Global Variable, which means that it can be applied to any script below the variable declaration.
admin is the name of this variable. Variable names can only include letters, numbers and underscorces. They must start with a lowercase letter.
Some examples of good and bad variable names are below;
Okay, so how do we use variables?
Notice I didn't put admin in ' ' whereas I would have if it was a string. If I had put admin in ' ', the alert box would have come up with 'admin', thinking it was a string.
Note that variable names are case-sensitive, so JS reads helloworld and helloWorld as different variables.
Arrays are specialist types of variables, used for storing data in JS. Just like variables! But better.
See? They're like variables but instead you just storing one variable, they store as many as you want. Nice! How do we output them in a function though?
Notice something new? I've used + to combine the array data with a string. You can do this with variables and Prompts too.
But what if I only want to return one of the above entries in the string? I would like to point out now that JS counts from zero, so you first value is 0, the second one is 1 etc etc.
You do this by adding a number after array name, surrounded by [ ]. So;
This will write "My Fav TV show is South Park"