Javascript Basics

JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc. This article helps you get started with JavaScript and furthers your understanding of what is possible.

JavaScript ("JS" for short) is a full-fledged dynamic programming language that can add interactivity to a website. It was invented by Brendan Eich (co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation).

JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!

JavaScript itself is relatively compact, yet very flexible. Developers have written a variety of tools on top of the core JavaScript language, unlocking a vast amount of functionality with minimum effort. These include:

  • Browser Application Programming Interfaces (APIs) built into web browsers, providing functionality such as dynamically creating HTML and setting CSS styles; collecting and manipulating a video stream from a user's webcam, or generating 3D graphics and audio samples.

  • Third-party APIs that allow developers to incorporate functionality in sites from other content providers, such as Twitter or Facebook.

  • Third-party frameworks and libraries that you can apply to HTML to accelerate the work of building sites and applications.

It's outside the scope of this article—as a light introduction to JavaScript—to present the details of how the core JavaScript language is different from the tools listed above. You can learn more in MDN's JavaScript learning area, as well as in other parts of MDN.

Variables

Variables are containers that store values. You start by declaring a variable with the var (less recommended, dive deeper for the explanation) or the let keyword, followed by the name you give to the variable:

let myVariable;

Note: A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see Your Guide to Semicolons in JavaScript.

Note: You can name a variable nearly anything, but there are some restrictions. (See this section about naming rules.) If you are unsure, you can check your variable name to see if it's valid.

Note: JavaScript is case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case!

Note: For more details about the difference between var and let, see The difference between var and let.

After declaring a variable, you can give it a value:

myVariable = 'Bob';

Also, you can do both these operations on the same line:

let myVariable = 'Bob';

You retrieve the value by calling the variable name:

myVariable;

After assigning a value to a variable, you can change it later in the code:

let myVariable = 'Bob'; myVariable = 'Steve';

Note that variables may hold values that have different data types:

Variable Explanation Example
String

This is a sequence of text known as a string. To signify that the value is a string, enclose it in single quote marks.

let myVariable = 'Bob';
Number

This is a number. Numbers don't have quotes around them.

let myVariable = 10;
Boolean

This is a True/False value. The words true and false are special keywords that don't need quote marks.

let myVariable = true;
Array

This is a structure that allows you to store multiple values in a single reference.

let myVariable = [1,'Bob','Steve',10];

Refer to each member of the array like this:

myVariable[0], myVariable[1]

, etc.

Object

Object This can be anything. Everything in JavaScript is an object and can be stored in a variable. Keep this in mind as you learn.

let myVariable = document.querySelector('h1');

All of the above examples too.

So why do we need variables? Variables are necessary 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 an image displayed in an image gallery.

Comments

Comments are snippets of text that can be added along with code. The browser ignores text marked as comments. You can write comments in JavaScript just as you can in CSS:

/* Everything in between is a comment. */

If your comment contains no line breaks, it's an option 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 in the JavaScript console.

Operators Explanation Symbol(s) Example
Addition

Add two numbers together or combine two strings.

+

6 + 9; 'Hello ' + 'world!';
Substraction, Multiplication, Division

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

As you've seen already: this assigns a value to a variable.

=

let myVariable = 'Bob';
Equality

This performs a test to see if two values are equal. It returns a true/false (Boolean) result.

===

let myVariable = 3; myVariable === 4;
Not, Does-not-equal

This returns the logically opposite value of what it precedes. It turns a true into a false, etc.. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.

!, !==

"Does-not-equal" gives basically the same result with different syntax. Here we are testing "is myVariable NOT equal to 3". This returns false because myVariable IS equal to 3:

let myVariable = 3; myVariable !== 3;

There are a lot more operators to explore, but this is enough for now. See Expressions and operators for a complete list.

Note: Mixing data types can lead to some strange results when performing calculations. Be careful that you are referring to your variables correctly, and getting the results you expect. For example, enter '35' + '25' into your console. Why don't you get the result you expected? Because the quote marks turn the numbers into strings, so you've ended up concatenating strings rather than adding numbers. If you enter 35 + 25 you'll get the total of the two numbers.

Conditionals

Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if ... else statement. For example:

let 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, the first block of code runs. If the comparison is not true, the second block of code—after the else statement—runs instead.

Functions

Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions previously. For example:

  • let myVariable = document.querySelector('h1');
  • alert('hello!');

These functions, document.querySelector and alert, are built into the browser.

If you see something which looks like a variable name, but it's followed by parentheses— () —it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.

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 message to display.

You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:

function multiply(num1,num2) { let result = num1 * num2; return result; }

Try running this in the console; then test with several arguments. For example:

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. (Read more about variable scoping.)

Events

Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse. To demonstrate this, enter the following into your console, then click on the current webpage:

document.querySelector('html').onclick = function() { alert('Ouch! Stop poking me!'); }

There are many ways to attach an event handler to an element. Here we select the html element, setting its onclick handler property equal to an anonymous (i.e. nameless) function, which contains the code we want the click event to run.

Note that

document.querySelector('html').onclick = function() {};

is equivalent to

let myHTML = document.querySelector('html'); myHTML.onclick = function() {};

It's just shorter.

Reference