What is JavaScript, really?
JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation.
JavaScript itself is fairly compact but very flexible, and developers have written a lot of tools on top of the core JavaScript language, to unlock a huge amount of extra functionality with very little effort. These include:
Application Programming Interfaces (APIs) built into web browsers, providing various functionality like dynamically creating HTML and setting CSS styles, grabbing and manipulating a video stream from the user's webcam, or generating 3D graphics and audio samples.
Third-party APIs to allow developers to incorporate functionality in their sites from other properties, such as Twitter or Facebook.
Third-party frameworks and libraries you can apply to your HTML to allow you to rapidly build up sites and applications.
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).
Variables
Variables are containers that you can store values in. You start by declaring a variable with thevar keyword, followed by any name you want to call it:
var myVariable;
Note: All statements in JavaScript must end with a semi-colon, to indicate that this is where the statement ends. If you don't include these, you can get unexpected results.
Note: You can name a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.) If you are unsure, you can check your variable name to see if it is valid.
Note: JavaScript is case sensitive —
myVariableis a different variable tomyvariable. If you are getting problems in your code, check the casing!
After declaring a variable, you can give it a value:
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:
| VariableExplanationExample | | |
| --- | --- | --- |
| String | A string of text. To signify that the variable is a string, you should enclose it in quote marks. | var myVariable = 'Bob'; |
| Number | A number. Numbers don't have quotes around them. | var myVariable = 10; |
| Boolean | A True\/False value. The words true andfalse are special keywords in JS, and don't need quotes. | var myVariable = true; |
| Array | A structure that allows you to store multiple values in one single reference. | var myVariable = [1,'Bob','Steve',10]; |
| Object | Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. | var myVariable = document.querySelector('h1');
All of the above examples too. |
| --- | --- | --- |
So why do we need variables? Well, variables are needed to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change the image displayed in an image gallery.
Comments
You can put comments into JavaScript code, just like you can in CSS:
/*
Everything in between is a comment.
*/
If your comment contains no line breaks, it's often easier to put it behind two slashes like this:
// This is a comment
Operators
An operator is a mathematical symbol that produces a result based on two values (or variables). In the following table you can see some of the simplest operators, along with some examples to try out in the JavaScript console.
| OperatorExplanationSymbol(s)Example | | | |
| --- | --- | --- | --- |
| add\/concatenation | Used to add two numbers together, or glue two strings together. | + | 6 + 9; |
"Hello " + "world!"; |
| subtract, multiply, divide | These do what you'd expect them to do in basic math. | -, *, / | 9 - 3;
8 * 2; // multiply in JS is an asterisk
9 / 3; |
| assignment operator | You've seen this already: it assigns a value to a variable. | = | var myVariable = 'Bob'; |
| Identity operator | Does a test to see if two values are equal to one another, and returns atrue\/false (Boolean) result. | === | var myVariable = 3;
myVariable === 4; |
| Negation, not equal | Returns the logically opposite value of what it preceeds; it turns a true into afalse, etc. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal. | !, !== | The basic expression istrue, but the comparison returnsfalsebecause we've negated it:var myVariable = 3;
!(myVariable === 3);Here we are testing "ismyVariableNOT equal to 3". This returnsfalsebecausemyVariableIS equal to 3.var myVariable = 3;
myVariable !== 3; |
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 (iceCream === 'chocolate') {
alert('Yay, I love chocolate ice cream!');
} else {
alert('Awwww, but chocolate is my favorite...');
}
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. If this comparison returns true, run the first block of code. If not, skip that code and run the second block of code after the else statement.
Functions
Functions are a way of packaging functionality that you want to reuse, so that whenever you want the functionality you can call the function with the function name rather than constantly rewriting the entire code. You have already seen some uses of functions above, for example:
var myVariable = document.querySelector('h1');
alert('hello!');
These functions, document.querySelector and alert, 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 go inside the brackets, separated by commas if there is more than one item.
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 the function what to write in the pop-up box.
You can define your own functions — in this next example we write a simple function that takes two numbers as arguments and multiplies them:
function multiply(num1,num2) {
var result = num1 * num2;
return result;
}
multiply(20,20);
Events
To create real interactivity on a website, you need 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. 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 console, then clicking on the current webpage:
There are many ways to attach an event to an element. Here we are selecting the HTML element and setting its onclick handler property equal to an anonymous (i.e. nameless) function that contains the code we want to run when the click event occurs.
document.querySelector('html').onclick = function() {};