Introduction

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g. having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.Js which allow you to add more functionality to a website than simply downloading files (such as realtime collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

This means that in the browser, JavaScript can change the way the webpage (DOM) looks. And, likewise, Node.js JavaScript on the server can respond to custom requests from code written in the browser.

What You Should Already Know

This guide assumes you have the following basic background:

JavaScript and Java

JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.

In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.

JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.

Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.

In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.

Hello World!

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

(function(){ "use strict";
/* Start of your code */
function greetMe(yourName) {
alert('Hello ' + yourName);
} greetMe('World');
/* End of your code */
})();

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser! In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications. But, for the time being, remember to always include the (function(){"use strict"; before your code, and add })(); to the end of your code. You will learn what these mean, but for now they can be thought of as doing the following —

  1. Massively improve performance
  2. Prevent stupid semantics in JavaScript that trip up beginners
  3. Prevent code snippets executed in the console from interacting with one-another (e.g. having something created in one console execution being used for a different console execution).
Variables

A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. But one special thing about variables is that their contained values can change. Let's look at a simple example:

<button>Press me</button>
const button = document.querySelector('button');
button.onclick = function() {
let name = prompt('What is your name?');
alert('Hello ' + name + ', nice to see you!'); }



In this example pressing the button runs a couple of lines of code. The first line pops a box up on the screen that asks the reader to enter their name, and then stores the value in a variable. The second line displays a welcome message that includes their name, taken from the variable value.

To understand why this is so useful, let's think about how we'd write this example without using a variable. It would end up looking something like this:

let name = prompt('What is your name?');
if (name === 'Adam') {
alert('Hello Adam, nice to see you!');
} else if (name === 'Alan') {
alert('Hello Alan, nice to see you!');
} else if (name === 'Bella') {
alert('Hello Bella, nice to see you!');
} else if (name === 'Bianca') {
alert('Hello Bianca, nice to see you!');
} else if (name === 'Chris') {
alert('Hello Chris, nice to see you!');
}
// ... and so on ...

You may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for that name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices.

Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

Declaring Variables

To use a variable, you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword var or let followed by the name you want to call your variable:

let myName; let myAge;

Here we're creating two variables called myName and myAge. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.

Note: In JavaScript, all code instructions should end with a semi-colon (;) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

myName; myAge;

They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message — try typing in

scoobyDoo;

Note: Don't confuse a variable that exists but has no value defined with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it.

Variable Scope

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the global context (or the function if the following codes are part of the function), not the immediate if statement block.

if (true) { var x = 5; } console.log(x); // x is 5

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

if (true) { let y = 5; } console.log(y); // ReferenceError: y is not defined
Global Variables

Global variables are in fact properties of the global object. In web pages, the global object is window, so you can set and access global variables using the window.variable syntax.

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

Constants

You can create a read-only, named constant with the const keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign ($) and can contain alphabetic, numeric, or underscore characters.

const PI = 3.14;

A constant cannot change value through assignment or be re-declared while the script is running. It must be initialized to a value.

The scope rules for constants are the same as those for let block-scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

// THIS WILL CAUSE AN ERROR function f() {}; const f = 5; // THIS WILL CAUSE AN ERROR TOO function f() { const g = 5; var g; //statements }

However, the properties of objects assigned to constants are not protected, so the following statement is executed without problems.

const MY_OBJECT = {'key': 'value'}; MY_OBJECT.key = 'otherValue'; Also, the contents of an array are not protected, so the following statement is executed without problems. const MY_ARRAY = ['HTML','CSS']; MY_ARRAY.push('JAVASCRIPT'); console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT'];
Data Types

The latest ECMAScript standard defines eight data types:

Although these data types are relatively few, they enable you to perform useful functions with your applications. Objects and functions are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.

if ... else Statements

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. An if statement looks as follows:

if (condition) { statement_1; } else { statement_2; }

condition can be any expression that evaluates to true or false. See Boolean for an explanation of what evaluates to true and false. If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using else if to have multiple conditions tested in sequence, as follows:

if (condition_1) { statement_1; } else if (condition_2) { statement_2; } else if (condition_n) { statement_n; } else { statement_last; }

In the case of multiple conditions only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ ... }) . In general, it's good practice to always use block statements, especially when nesting if statements:

if (condition) { statement_1_runs_if_condition_is_true; statement_2_runs_if_condition_is_true; } else { statement_3_runs_if_condition_is_false; statement_4_runs_if_condition_is_false; }

It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:

if (x = y) { /* statements here */ }

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:

if ((x = y)) { /* statements here */ }
while Statements

A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:

while (condition) statement

If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.

The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops and control is passed to the statement following while.

To execute multiple statements, use a block statement ({ ... }) to group those statements.

Example: The following while loop iterates as long as n is less than three:

var n = 0; var x = 0; while (n < 3) { n++; x += n; }

With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Function Declarations

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

For example, the following code defines a simple function named square:

function square(number) { return number * number; }

The function square takes one argument, called number. The function consists of one statement that says to return the argument of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the function.

return number * number;

Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

Reference

All the documentation on this page is lovingly "borrowed" from MDN.