JavaScript is a great language for anyone just starting to code for a variety of reasons. It's lightweight, runs fast and most importantly you don't need any fancy software to run it. You can download any text editor, I recommend Sublime because it offers many features that you can find useful once you learn a tiny bit of JavaScript, and you can run it on pretty much any browser right now. And it's not just great for learning to code, but it's also quickly becoming a language that needs to be taken seriously as more applications move to the web.
So here's a quick beginners guide that will run through the most important aspects of JavaScript. From creating a function, with a few variables to making a request to a web service to fetch some data to display. I'll be using a simple deck of cards program that I wrote on a previous blog post as an example because the best to way to learn is by doing. So feel free to copy the code into your text editor, hit save, and fire up Chrome to see what develops.
Variable Declarations
You can think of variables as containers for data. That data includes strings, numbers, decimal numbers, lists of data and more complex types which I'll cover down below. Variable declaration in JavaScript is as follows:
var deck = new Array();
var suits = ["spades", "diamonds", "clubs", "hearts"];
var values = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
Variables follow the following format:
type identifier;
type identifier = "some value";
type identifier = new className;
In this case our variables are of type 'var', the identifier is the name given after 'var', like deck, suits, and values. And each variable is set to equal something. In the case of deck, it is set to be of the Array type. 'suits' and 'values' are both also set to be Arrays although implicitly, and this is because it is set to equal values that are in the array format.
Arrays
Arrays are pretty important in most programming languages and I've declared 3 above in my deck example. The first array, 'deck', is currently empty. Initializing as new Array(), just creates the array in memory, but it is empty at this point. We have to push items onto it and they will be added to that list in that order, which is important. Both methods of Array declaration are valid. That is:
var deck = new Array();
var suits = ["spades", "diamonds", "clubs", "hearts"];
The only difference here is that the second array comes equipped with data after we declare it. But we could also continue to add items to it if we wished. In order to add items to these variables, you can use the 'push' method that are specific to variables that are of type Array.
var array = new Array();
array.push(1);
array.push(2);
In order to retrieve values back from Arrays, you will need the values ordinal position in the Array, that is where it is located sequentially starting at 0.
var value1 = array[0];
var value2 = array[1];
These calls for example would set the value1 and value2 variables equal to '1' and '2' respectively.
Functions
Functions are blocks of code that you can call from various locations. The syntax for them is pretty simple for the most part.
function functionName(parameter1, parameter2)
{
var variable1;
return variable1;
}
The word function, followed by a name of your choosing and an optional list of parameters that can be passed to this function. Inside the function you can pretty much call any JS code that you wish. You can declare variables, which will be only visible inside of your function, and you access variables that are not declared inside of functions, or global variables.
Here's a quick function that generates a set of 52 card combinations, based on the suit and value items in the array above.
function getDeck()
{
var deck = new Array(); // this array is local to this function only
for(var i = 0; i < suits.length; i++)
{
for(var x = 0; x < values.length; x++)
{
var card = {Value: values[x], Suit: suits[i]};
deck.push(card); // adding the card variable to the array
}
}
// returns the 52 length array of card objects
return deck;
}
This function takes 0 parameters and it returns a new Array of card objects. If you notice the card declaration, variables can also contain more complex type. The card variable above is comprised of 2 different values, one for the suit of the card and one for the value. There are also 2 for loops implemented, which I'll talk about below.
Loops
Loops allow you to repeat a block of code a number of times. For example, if you had a list of numbers and you wanted to add a 2 to each one, you would use a loop to run through all of the elements appending a 2 along the way. To continue with the deck example, here is a function that will shuffle the deck in a random order.
function shuffle()
{
// for 1000 turns
// switch the values of two random cards
for (var i = 0; i < 1000; i++)
{
var location1 = Math.floor((Math.random() * deck.length));
var location2 = Math.floor((Math.random() * deck.length));
var tmp = deck[location1];
deck[location1] = deck[location2];
deck[location2] = tmp;
}
}
This is just one type of loop. There are also while loops and do while loops. But for the sake of the example, I'll be using the for loop. Let's break it down a little bit. For loops are comprised of 3 elements.
var i = 0;
for ( i = 0; i < 1000; i++)
We have the keyword for with 3 specific items inside of it.
- this is the initial value of our loop.
- this is a condition that our tracing variable must meet.
- this is the operation that will be performed on our tracing variable after each iteration
If This Then That
Because sometimes yes and sometimes, not so much. Conditional statements will validate a value that will return either a true or a false response and will execute the code accordingly based on those values. And again, the syntax is pretty simple:
if (condition that evaluates to true or false)
{
// run block of code
}
else
{
// run this block of code
}
Unfortunately, I didn't use any in my deck example.
Events
Without events, we can't really make use of JavaScript. Something has to trigger the JS code. Whether it be a mouse click, or a entering text into a text field, these events can then call JavaScript. The JavaScript specification has a fair number of events, and I'm not going to be covering all of them here as there are much better sources out there for that, but here's a list of some of the most common ones:
- onchange - An HTML element has been changed
- onclick - An HTML element has been clicked
- onmouseover - User moves mouse over an element
- onmouseout - User moves mouse away from an element
For our current deck example, I'll have a button that shuffles the deck whenever it is clicked, so we'll use the onclick event on an input element.
<input type="button" value="Shuffle" onclick="shuffle()" />
So this will call the shuffle method that I declared above whenever it is clicked.
DOM Manipulation
Perhaps JavaScripts most important feature is its ability to manipulate DOM elements in a variety of ways. The final function for the deck example is the one that will draw the cards onto the screen and on your browser. I'll create a new function, and call it renderDeck. It will take no parameters and will return no values.
function renderDeck()
{
for(var i = 0; i < deck.length; i++)
{
var card = document.createElement("div");
var value = document.createElement("div");
var suit = document.createElement("div");
card.className = "card";
value.className = "value";
suit.className = "suit " + deck[i].Suit;
value.innerHTML = deck[i].Value;
card.appendChild(value);
card.appendChild(suit);
document.getElementById("deck").appendChild(card);
}
}
In the end I want to draw out the cards onto the screen. So for that I can use the JavaScript functions to create DOM elements onto the document.
var card = document.createElement("div");
This variable for example will create a div and assign it to the card variable. It won't add it to the page just yet however. At this point we can set almost anything in this div. It's styling, its content and even attach events to it. For this example, I'll just be setting the class to that of the proper suit.
Where To Place It
JavaScript scripts can go in a variety of places on your website.
Externally: You can create external files for JavaScript code. These files will contain the .js extension.
In the <head>: Another popular place to place JavaScript is in the head section of your webpage. There are a few reasons for this, such as page speed. If you have a miniscule amount of JavaScript, then it doesn't make too much sense to
Inside the <body>: You can place JavaScript scripts directly on your body, preferably at the very bottom so it doesn't interfere with any HTML elements loading.
There's Plenty More, But For Now...
So this is for the most part what you will be using JavaScript for. This is about 80% of JavaScript I would say. The other 20% is more specialized and complex code that will focus on DOM manipulation and timing events. But if you know these basic concepts then you are good to go to start coding some basic applications.
View full source
<html>
<head>
<style>
.card
{
border: solid 1px #aaa;
border-radius: 9px;
width: 95px;
height: 150px;
float:left;
background-color: white;
padding: 3px 3px 3px 3px;
}
.card .value{
font-size:15pt;
font-family: sans-serif;
}
.card .suit
{
background-image: url('suits.png');
height: 100px;
width: 90px;
}
.card .diamonds
{
background-position-y: 100px;
}
.card .hearts
{
background-position-x: 90px;
}
.card .clubs
{
background-position-x:90px;
background-position-y:100px;
}
</style>
<script type="text/javascript">
var cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["diamonds", "hearts", "spades", "clubs"];
var deck = new Array();
function getDeck()
{
var deck = new Array();
for(var i = 0; i < suits.length; i++)
{
for(var x = 0; x < cards.length; x++)
{
var card = {Value: cards[x], Suit: suits[i]};
deck.push(card);
}
}
return deck;
}
function deal()
{
// remove top card from deck
var card = deck[deck.length-1];
deck.splice(deck.length-1, 1);
return card;
}
function shuffle()
{
// for 1000 turns
// switch the values of two random cards
for (var i = 0; i < 1000; i++)
{
var location1 = Math.floor((Math.random() * deck.length));
var location2 = Math.floor((Math.random() * deck.length));
var tmp = deck[location1];
deck[location1] = deck[location2];
deck[location2] = tmp;
}
}
function renderDeck()
{
for(var i = 0; i < deck.length; i++)
{
var card = document.createElement("div");
var value = document.createElement("div");
var suit = document.createElement("div");
card.className = "card";
value.className = "value";
suit.className = "suit " + deck[i].Suit;
value.innerHTML = deck[i].Value;
card.appendChild(value);
card.appendChild(suit);
document.getElementById("deck").appendChild(card);
}
}
function load()
{
deck = getDeck();
shuffle();
renderDeck();
}
window.onload = load;
</script>
</head>
<body>
<h1>A Deck of Cards</h1>
<div id="deck"></div>
</body>
</html>