In this section we will start to look at JavaScript, the programming language of the Web. In this section, we will be using JSBin's JavaScript, Console and Output panes, so make sure those are open before we continue. Through this article you should try entering the code samples into the JavaScript pane unless otherwise noted.
What is JavaScript, really?
JavaScript is a complete programming language that can be applied to HTML and used to create dynamic interactivity on websites.
You can do pretty much anything with JavaScript, starting small with simple features such as adjusting layouts, making things happen when buttons are clicked, and image galleries — and moving up to bigger things like creating games, animated 2D and 3D graphics, full blown database-driven apps, and more.
JavaScript itself is fairly small, but it is very flexible, and developers have written a lot of tools that sit on top of the core JavaScript language to provide you with access to a huge amount of extra functionality with very little effort. These include:
- Application Programming Interfaces (APIs) built into web browsers that allow you to do anything from dynamically create HTML and set CSS styles, to grab and manipulate a video stream from the user's web cam, or generate 3D graphics and audio samples.
- 3rd party APIs to allow developers to incorporate functionality in their sites from other properties, such as Twitter or Facebook.
- 3rd party frameworks and libraries you can apply to your HTML to allow you to rapidly build up sites and applications.
A "hello world" example
The above section sounds really exciting, and so it should — JavaScript is one of the most exciting web technologies, and when you start to get good at it your websites will enter a new dimension of power and creativity.
HOWEVER, JavaScript is a bit more complex to get comfortable with than HTML and CSS, and you'll have to start small, and keep working at it in tiny regular steps. To start off with, we'll show you how to add some really basic JavaScript to your page, to create a "hello world!" example (the standard in basic programming examples.)
- First, open the JavaScript pane in JSBin.
- Add the following code into the pane:
var myHeading = document.querySelector('h1');
myHeading.innerHTML = 'Hello world!';
What happened?
So your heading text has been changed to "Hello world!" using JavaScript. We did this by first using a function called document.querySelector()
to grab a reference to our heading, and store it in a variable called myHeading
. This is very similar to what we did in CSS using selectors — we want to do something to an element, so we need to first select it.
After that, we set the value of the myHeading
variable's innerHTML
property (which represents the content of the heading) to "Hello world!". Again, we are working with properties — this is again similar to CSS.
This is the way that most JavaScript works — you have to manipulate a number of different objects, which represent different things inside the browser's runtime (the state of the web page after it has been rendered by the browser), to make cool things happen.
Language basics crash course
Let's explain just some of the basic features of the JavaScript language, to give you some more understanding of how it all works.
Note: Such features are common to all programming languages. If you can understand these fundamentals, you should be able to make a start in programming just about anything.
Variables
Variables are containers that you can store values in. You start by declaring a variable with the var
keyword, followed by any name you want to call it:
var myVariable;
Note: All lines in JS must end with a semi-colon, to indicate that this is where the line ends. If you don't include these, you can get unexpected results.
Note: You can call a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.)
Note: JavaScript is case sensitive — myVariable
is a different variable to myvariable
. If you are getting problems in your code, check the casing!
After declaring a variable, you can give it a value:
myVariable = 'Bob';
You can retrieve the value by just calling the variable by name (try typing this in the Console pane):
myVariable;
You can do both these operations on the same line if you wish:
var myVariable = 'Bob';
After giving a variable a value, you can later choose to change it:
var myVariable = 'Bob';
myVariable = 'Steve';
Note that variables have different data types:
So why do we need variables? Well, variables are needed to do anything interesting in programming. If values couldn't change, then you wouldn't be able to do anything dynamic, like personalize a greeting message to the user visiting your site, or change the image displayed in an image gallery, etc.
Operators
An operator is basically a mathematical symbol that can act on two values (or variables) and produce a result. In the below table you can see some of the most simple operators, along with some examples to try out in the browser console.
Operator | Explanation | Symbol(s) | Example |
---|---|---|---|
add/concatenation | Used to add two numbers together, or glue two strings together. | + |
|
subtract, multiple, divide | These do what you'd expect them to do in basic math. | - , * , / |
|
assignment operator | You've seen this already: it assigns a value to a variable. | = |
|
Identity operator | Does a test to see if two values are equal to one another, and returns a true /false (boolean) result. |
=== |
|
Negation, not equal | Often used alongside the Equality operator, the negation operator is the JS equivalent of a logical NOT — it turns a true into a false , etc. |
!== |
The basic expression is
Here we are testing "is
|
There are a lot more to explore, but this will do for now. See Expressions and operators for a complete list.
Conditionals
Conditionals are code structures that allow you to test whether an expression returns true or not, and then run different code depending on the result. The most common form of conditional is called if ... else
. So for example:
var iceCream = 'chocolate';
if (condition) {
code1
} else {
code2
}
This is a simple shell of an expression. condition should be replaced by a condition to test. code1 should be replaced by what happens if the condition is true; code2 should be replaced by what happens if the condition is false.
Replace condition with:
iceCream === 'chocolate'
Replace code1 with:
alert('Yay, I love chocolate ice cream!');
Replace code2 with:
alert('Awwww, but chocolate is my favorite...');
Now run the code using Run with JS. What happens?
The expression inside the if ( ... )
is the test — this uses the identity operator (as described above) to compare the variable iceCream
with the string chocolate
to see if the two are equal. Because this comparison returns true
, we run the first block of code, giving us the first alert.
Functions
Functions are a way of encapsulating functionality that you want to reuse, so you can call that function with a single function name, and not have to write the entire code out again and again each time you use it. The browser has many built in functions (contained in the core JavaScript language), for example:
var myVariable = document.querySelector('h1');
alert('hello!');
These functions are built into the browser for you to use whenever you like.
If you see something that looks like a variable name, but has brackets — ()
— after it, it is probably a function. Functions often take arguments — bits of data they need to do their job. These are put inside the brackets, and separated by commas if there is more than one. This is similar to HTML attributes.
For example, the alert()
function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell it what message it is supposed to write in the pop-up box.
The good news is that you can define your own functions — in this next example we write a simple function that takes two numbers as arguments and multiples them together:
function multiply(num1,num2) {
var result = num1 * num2;
return result;
};
Try putting the above function in the JavaScript pane, then try using your new function a few times, by running it in the Console pane e.g.:
multiply(4,7);
multiply(20,20);
multiply(0.5,3);
Note: The return
statement tells the browser to return the result
variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping.
Extra: Another function example
The above function is a bit pointless, because you can write out a multiplication pretty fast. But what about a personalised greeting?
function greeting(name) {
var myGreeting = 'Hello ' + name + ', nice to meet you!';
return myGreeting;
};
Events
To create real interactivity on a website, you have to use events — these are code structures that listen out for things happening to the browser, and then allow you to run code in response to those things happening. The most obvious example is the click
event, which is fired by the browser when the mouse clicks on something.
To demonstrate this, try entering the following into your JavaScript pane, then clicking on the Output pane:
document.querySelector('html').onclick = function() {
alert('Ouch! Stop poking me!');
};
There are many ways to attach an event to an element; here we are selecting the HTML element and making its onclick
handler property equal to an anonymous function (a function without a name) that contains the code we want to run when the click event occurs.