What went wrong? Troubleshooting JavaScript - Learn web development

What went wrong? Troubleshooting JavaScript
===========================================

* Previous
* Overview: First steps
* Next

When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some tips on how to find and fix errors in JavaScript programs.

|  |  |
| --- | --- |
| Prerequisites: |
 A basic understanding of HTML and CSS, an
 understanding of what JavaScript is.
  |
| Objective: |
 To gain the ability and confidence to start fixing problems in your own
 code.
  |

Types of error
--------------

Generally speaking, when you do something wrong in code, there are two main types of error that you'll come across:

* **Syntax errors**: These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean!
* **Logic errors**: These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn't an error message to direct you to the source of the error.

Okay, so it's not quite *that* simple — there are some other differentiators as you drill down deeper. But the above classifications will do at this early stage in your career. We'll look at both of these types going forward.

An erroneous example
--------------------

To get started, let's return to our number guessing game — except this time we'll be exploring a version that has some deliberate errors introduced. Go to GitHub and make yourself a local copy of number-game-errors.html (see it running live here).

1. To get started, open the local copy inside your favorite text editor, and your browser.
2. Try playing the game — you'll notice that when you press the "Submit guess" button, it doesn't work!

**Note:** You might well have your own version of the game example that doesn't work, which you might want to fix! We'd still like you to work through the article with our version, so that you can learn the techniques we are teaching here. Then you can go back and try to fix your example.

At this point, let's consult the developer console to see if it reports any syntax errors, then try to fix them. You'll learn how below.

Fixing syntax errors
--------------------

Earlier on in the course we got you to type some simple JavaScript commands into the developer tools JavaScript console (if you can't remember how to open this in your browser, follow the previous link to find out how). What's even more useful is that the console gives you error messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting.

1. Go to the tab that you've got `number-game-errors.html` open in, and open your JavaScript console. You should see an error message along the following lines:
 !["Number guessing game" demo page in Firefox. One error is visible in the JavaScript console: "X TypeError: guessSubmit.addeventListener is not a function [Learn More] (number-game-errors.html:86:3)".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/not-a-function.png)
2. The first line of the error message is:
```

Uncaught TypeError: guessSubmit.addeventListener is not a function
number-game-errors.html:86:15
```

    * The first part, `Uncaught TypeError: guessSubmit.addeventListener is not a function`, is telling us something about what went wrong.
    * The second part, `number-game-errors.html:86:15`, is telling us where in the code the error came from: line 86, character 15 of the file "number-game-errors.html".
3. If we look at line 86 in our code editor, we'll find this line:

**Warning:** Error message may not be on line 86.

If you are using any code editor with an extension that launches a live server on your local machine, this will cause extra code to be injected. Because of this, the developer tools will list the error as occurring on a line that is not 86.

```js
guessSubmit.addeventListener("click", checkGuess);
```

4. The error message says "guessSubmit.addeventListener is not a function", which means that the function we're calling is not recognized by the JavaScript interpreter. Often, this error message actually means that we've spelled something wrong. If you are not sure of the correct spelling of a piece of syntax, it is often good to look up the feature on MDN. The best way to do this currently is to search for "mdn *name-of-feature*" with your favorite search engine. Here's a shortcut to save you some time in this instance: `addEventListener()`.
5. So, looking at this page, the error appears to be that we've spelled the function name wrong! Remember that JavaScript is case-sensitive, so any slight difference in spelling or casing will cause an error. Changing `addeventListener` to `addEventListener` should fix this. Do this now.

**Note:** See our TypeError: "x" is not a function reference page for more details about this error.

### Syntax errors round two

1. Save your page and refresh, and you should see the error has gone.
2. Now if you try to enter a guess and press the Submit guess button, you'll see another error!
 ![Screenshot of the same "Number guessing game" demo. This time, a different error is visible in the console, reading "X TypeError: lowOrHi is null".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/variable-is-null.png)
3. This time the error being reported is:
```

Uncaught TypeError: can't access property "textContent", lowOrHi is null
```

Depending on the browser you are using, you might see a different message here. The message above is what Firefox will show you, but Chrome, for example, will show you this:
```

Uncaught TypeError: Cannot set properties of null (setting 'textContent')
```

It's the same error, but different browsers describe it in a different way.

**Note:** This error didn't come up as soon as the page was loaded because this error occurred inside a function (inside the `checkGuess() { }` block). As you'll learn in more detail in our later functions article, code inside functions runs in a separate scope than code outside functions. In this case, the code was not run and the error was not thrown until the `checkGuess()` function was run by line 86.
4. The line number given in the error is 80. Have a look at line 80, and you'll see the following code:

```js
lowOrHi.textContent = "Last guess was too high!";
```

5. This line is trying to set the `textContent` property of the `lowOrHi` variable to a text string, but it's not working because `lowOrHi` does not contain what it's supposed to. Let's see why this is — try searching for other instances of `lowOrHi` in the code. The earliest instance you'll find is on line 49:

```js
const lowOrHi = document.querySelector("lowOrHi");
```

6. At this point we are trying to make the variable contain a reference to an element in the document's HTML. Let's see what the variable contains after this line has been run. Add the following code on line 50:

```js
console.log(lowOrHi);
```

This code will print the value of `lowOrHi` to the console after we tried to set it in line 49. See `console.log()` for more information.
7. Save and refresh, and you should now see the `console.log()` result in your console.
 ![Screenshot of the same demo. One log statement is visible in the console, reading simply "null".](/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong/console-log-output.png) Sure enough, `lowOrHi`'s value is `null` at this point, and this matches up with the Firefox error message `lowOrHi is null`. So there is definitely a problem with line 49. The `null` value means "nothing", or "no value". So our code to set `lowOrHi` to an element is going wrong.
8. Let's think about what the problem could be. Line 49 is using a `document.querySelector()` method to get a reference to an element by selecting it with a CSS selector. Looking further up our file, we can find the paragraph in question:

```html
<p class="lowOrHi"></p>
```

9. So we need a class selector here, which begins with a dot (`.`), but the selector being passed into the `querySelector()` method in line 49 has no dot. This could be the problem! Try changing `lowOrHi` to `.lowOrHi` in line 49.
10. Try saving and refreshing again, and your `console.log()` statement should return the `<p>` element we want. Phew! Another error fixed! You can delete your `console.log()` line now, or keep it to reference later on — your choice.

**Note:** See our TypeError: "x" is (not) "y" reference page for more details about this error.

### Syntax errors round three

1. Now if you try playing the game through again, you should get more success — the game should play through absolutely fine, until you end the game, either by guessing the right number, or by running out of guesses.
2. At that point, the game fails again, and the same error is spat out that we got at the beginning — "TypeError: resetButton.addeventListener is not a function"! However, this time it's listed as coming from line 94.
3. Looking at line number 94, it is easy to see that we've made the same mistake here. We again just need to change `addeventListener` to `addEventListener`. Do this now.
A logic error
-------------

At this point, the game should play through fine, however after playing through a few times you'll undoubtedly notice that the game always chooses 1 as the "random" number you've got to guess. Definitely not quite how we want the game to play out!

There's definitely a problem in the game logic somewhere — the game is not returning an error; it just isn't playing right.

1. Search for the `randomNumber` variable, and the lines where the random number is first set. The instance that stores the random number that we want to guess at the start of the game should be around line number 45:

```js
let randomNumber = Math.floor(Math.random()) + 1;
```

2. And the one that generates the random number before each subsequent game is around line 113:

```js
randomNumber = Math.floor(Math.random()) + 1;
```

3. To check whether these lines are indeed the problem, let's turn to our friend `console.log()` again — insert the following line directly below each of the above two lines:

```js
console.log(randomNumber);
```

4. Save and refresh, then play a few games — you'll see that `randomNumber` is equal to 1 at each point where it is logged to the console.
### Working through the logic

To fix this, let's consider how this line is working. First, we invoke `Math.random()`, which generates a random decimal number between 0 and 1, e.g. 0.5675493843.

```js
Math.random();
```

Next, we pass the result of invoking `Math.random()` through `Math.floor()`, which rounds the number passed to it down to the nearest whole number. We then add 1 to that result:

```js
Math.floor(Math.random()) + 1;
```

Rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. We need to multiply the random number by 100 before we round it down. The following would give us a random number between 0 and 99:

```js
Math.floor(Math.random() \* 100);
```

Hence us wanting to add 1, to give us a random number between 1 and 100:

```js
Math.floor(Math.random() \* 100) + 1;
```

Try updating both lines like this, then save and refresh — the game should now play like we are intending it to!

Other common errors
-------------------

There are other common errors you'll come across in your code. This section highlights most of them.

### SyntaxError: missing ; before statement

This error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. For example, if we change this line inside the `checkGuess()` function:

```js
const userGuess = Number(guessField.value);
```

to

```js
const userGuess === Number(guessField.value);
```

It throws this error because it thinks you are trying to do something different. You should make sure that you don't mix up the assignment operator (`=`) — which sets a variable to be equal to a value — with the strict equality operator (`===`), which tests whether one value is equal to another, and returns a `true`/`false` result.

**Note:** See our SyntaxError: missing ; before statement reference page for more details about this error.

### The program always says you've won, regardless of the guess you enter

This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside `checkGuess()`:

```js
if (userGuess === randomNumber) {
```

to

```js
if (userGuess = randomNumber) {
```

the test would always return `true`, causing the program to report that the game has been won. Be careful!

### SyntaxError: missing ) after argument list

This one is pretty simple — it generally means that you've missed the closing parenthesis at the end of a function/method call.

**Note:** See our SyntaxError: missing ) after argument list reference page for more details about this error.

### SyntaxError: missing : after property id

This error usually relates to an incorrectly formed JavaScript object, but in this case we managed to get it by changing

```js
function checkGuess() {
```

to

```js
function checkGuess( {
```

This has caused the browser to think that we are trying to pass the contents of the function into the function as an argument. Be careful with those parentheses!

### SyntaxError: missing } after function body

This is easy — it generally means that you've missed one of your curly braces from a function or conditional structure. We got this error by deleting one of the closing curly braces near the bottom of the `checkGuess()` function.

### SyntaxError: expected expression, got '*string*' or SyntaxError: unterminated string literal

These errors generally mean that you've left off a string value's opening or closing quote mark. In the first error above, *string* would be replaced with the unexpected character(s) that the browser found instead of a quote mark at the start of a string. The second error means that the string has not been ended with a quote mark.

For all of these errors, think about how we tackled the examples we looked at in the walkthrough. When an error arises, look at the line number you are given, go to that line and see if you can spot what's wrong. Bear in mind that the error is not necessarily going to be on that line, and also that the error might not be caused by the exact same problem we cited above!

**Note:** See our SyntaxError: Unexpected token and SyntaxError: unterminated string literal reference pages for more details about these errors.

Summary
-------

So there we have it, the basics of figuring out errors in simple JavaScript programs. It won't always be that simple to work out what's wrong in your code, but at least this will save you a few hours of sleep and allow you to progress a bit faster when things don't turn out right, especially in the earlier stages of your learning journey.

See also
--------

* There are many other types of errors that aren't listed here; we are compiling a reference that explains what they mean in detail — see the JavaScript error reference.
* If you come across any errors in your code that you aren't sure how to fix after reading this article, you can get help! Ask for help on the communication channels. Tell us what your error is, and we'll try to help you. A listing of your code would be useful as well.
* Previous
* Overview: First steps
* Next


Test your skills: Strings - Learn web development

Test your skills: Strings
=========================

The aim of this skill test is to assess whether you've understood our Handling text — strings in JavaScript and Useful string methods articles.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

**Note:** In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version).

Strings 1
---------

In our first strings task, we start off small. You already have half of a famous quote inside a variable called `quoteStart`; we would like you to:

1. Look up the other half of the quote, and add it to the example inside a variable called `quoteEnd`.
2. Concatenate the two strings together to make a single string containing the complete quote. Save the result inside a variable called `finalQuote`.

You'll find that you get an error at this point. Can you fix the problem with `quoteStart`, so that the full quote displays correctly?

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Strings 2
---------

In this task you are provided with two variables, `quote` and `substring`, which contain two strings. We would like you to:

1. Retrieve the length of the quote, and store it in a variable called `quoteLength`.
2. Find the index position where `substring` appears in `quote`, and store that value in a variable called `index`.
3. Use a combination of the variables you have and available string properties/methods to trim down the original quote to "I do not like green eggs and ham.", and store it in a variable called `revisedQuote`.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Strings 3
---------

In the next string task, you are given the same quote that you ended up with in the previous task, but it is somewhat broken! We want you to fix and update it, like so:

1. Change the casing to correct sentence case (all lowercase, except for upper case first letter). Store the new quote in a variable called `fixedQuote`.
2. In `fixedQuote`, replace "green eggs and ham" with another food that you really don't like.
3. There is one more small fix to do — add a full stop onto the end of the quote, and save the final version in a variable called `finalQuote`.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Strings 4
---------

In the final string task, we have given you the name of a theorem, two numeric values, and an incomplete string (the bits that need adding are marked with asterisks (`*`)). We want you to change the value of the string as follows:

1. Change it from a regular string literal into a template literal.
2. Replace the four asterisks with four template literal placeholders. These should be:
    1. The name of the theorem.
    2. The two number values we have.
    3. The length of the hypotenuse of a right-angled triangle, given that the two other side lengths are the same as the two values we have. You'll need to look up how to calculate this from what you have. Do the calculation inside the placeholder.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.


Test your skills: variables - Learn web development

Test your skills: variables
===========================

The aim of this skill test is to assess whether you've understood our Storing the information you need — Variables article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.
 If there is an error in your code, it will be logged into the results panel on this page or in the JavaScript console.

If you get stuck, you can reach out to us in one of our communication channels.

Variables 1
-----------

In this task we want you to:

* Declare a variable called `myName`.
* Initialize `myName` with a suitable value, on a separate line (you can use your actual name, or something else).
* Declare a variable called `myAge` and initialize it with a value, on the same line.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Variables 2
-----------

In this task you need to add a new line to correct the value stored in the existing `myName` variable to your own name.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Variables 3
-----------

The final task for now — in this case you are provided with some existing code, which has two errors present in it. The results panel should be outputting the name `Chris`, and a statement about how old Chris will be in 20 years' time. How can you fix the problem and correct the output?

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.


Basic math in JavaScript — numbers and operators - Learn web development

Basic math in JavaScript — numbers and operators
================================================

* Previous
* Overview: First steps
* Next

At this point in the course, we discuss math in JavaScript — how we can use operators and other features to successfully manipulate numbers to do our bidding.

|  |  |
| --- | --- |
| Prerequisites: |
 A basic understanding of HTML and CSS, an
 understanding of what JavaScript is.
  |
| Objective: | To gain familiarity with the basics of math in JavaScript. |

Everybody loves math
--------------------

Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript (or any other language for that matter) — so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that JavaScript has a full-featured set of math functions available.

This article discusses only the basic parts that you need to know now.

### Types of numbers

In programming, even the humble decimal number system that we all know so well is more complicated than you might think. We use different terms to describe different types of decimal numbers, for example:

* **Integers** are floating-point numbers without a fraction. They can either be positive or negative, e.g. 10, 400, or -5.
* **Floating point numbers** (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
* **Doubles** are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).

We even have different types of number systems! Decimal is base 10 (meaning it uses 0–9 in each column), but we also have things like:

* **Binary** — The lowest level language of computers; 0s and 1s.
* **Octal** — Base 8, uses 0–7 in each column.
* **Hexadecimal** — Base 16, uses 0–9 and then a–f in each column. You may have encountered these numbers before when setting colors in CSS.

**Before you start to get worried about your brain melting, stop right there!** For a start, we are just going to stick to decimal numbers throughout this course; you'll rarely come across a need to start thinking about other types, if ever.

The second bit of good news is that unlike some other programming languages, JavaScript only has one data type for numbers, both integers and decimals — you guessed it, `Number`. This means that whatever type of numbers you are dealing with in JavaScript, you handle them in exactly the same way.

**Note:** Actually, JavaScript has a second number type, BigInt, used for very, very large integers. But for the purposes of this course, we'll just worry about `Number` values.

### It's all numbers to me

Let's quickly play with some numbers to reacquaint ourselves with the basic syntax we need. Enter the commands listed below into your developer tools JavaScript console.

1. First of all, let's declare a couple of variables and initialize them with an integer and a float, respectively, then type the variable names back in to check that everything is in order:

```js
const myInt = 5;
const myFloat = 6.667;
myInt;
myFloat;
```

2. Number values are typed in without quote marks — try declaring and initializing a couple more variables containing numbers before you move on.
3. Now let's check that both our original variables are of the same datatype. There is an operator called `typeof` in JavaScript that does this. Enter the below two lines as shown:

```js
typeof myInt;
typeof myFloat;
```

You should get `"number"` returned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in different ways. Phew!
### Useful Number methods

The `Number` object, an instance of which represents all standard numbers you'll use in your JavaScript, has a number of useful methods available on it for you to manipulate numbers. We don't cover these in detail in this article because we wanted to keep it as a simple introduction and only cover the real basic essentials for now; however, once you've read through this module a couple of times it is worth going to the object reference pages and learning more about what's available.

For example, to round your number to a fixed number of decimal places, use the `toFixed()` method. Type the following lines into your browser's console:

```js
const lotsOfDecimal = 1.766584958675746364;
lotsOfDecimal;
const twoDecimalPlaces = lotsOfDecimal.toFixed(2);
twoDecimalPlaces;
```

### Converting to number data types

Sometimes you might end up with a number that is stored as a string type, which makes it difficult to perform calculations with it. This most commonly happens when data is entered into a form input, and the input type is text. There is a way to solve this problem — passing the string value into the `Number()` constructor to return a number version of the same value.

For example, try typing these lines into your console:

```js
let myNumber = "74";
myNumber += 3;
```

You end up with the result 743, not 77, because `myNumber` is actually defined as a string. You can test this by typing in the following:

```js
typeof myNumber;
```

To fix the calculation, you can do this:

```js
let myNumber = "74";
myNumber = Number(myNumber) + 3;
```

The result is then 77, as initially expected.

Arithmetic operators
--------------------

Arithmetic operators are used for performing mathematical calculations in JavaScript:

| Operator | Name | Purpose | Example |
| --- | --- | --- | --- |
| `+` | Addition | Adds two numbers together. | `6 + 9` |
| `-` | Subtraction | Subtracts the right number from the left. | `20 - 15` |
| `*` | Multiplication | Multiplies two numbers together. | `3 * 7` |
| `/` | Division | Divides the left number by the right. | `10 / 5` |
| `%` | Remainder (sometimes called modulo) |
 Returns the remainder left over after you've divided the left number
 into a number of integer portions equal to the right number.
  |
`8 % 3` (returns 2, as three goes into 8 twice, leaving 2
 left over).
  |
| `**` | Exponent |
 Raises a `base` number to the `exponent` power,
 that is, the `base` number multiplied by itself,
 `exponent` times.
  | `5 ** 2` (returns `25`, which is the same as
 `5 * 5`).
  |

**Note:** You'll sometimes see numbers involved in arithmetic referred to as operands.

**Note:** You may sometimes see exponents expressed using the older `Math.pow()` method, which works in a very similar way. For example, in `Math.pow(7, 3)`, `7` is the base and `3` is the exponent, so the result of the expression is `343`. `Math.pow(7, 3)` is equivalent to `7**3`.

We probably don't need to teach you how to do basic math, but we would like to test your understanding of the syntax involved. Try entering the examples below into your developer tools JavaScript console to familiarize yourself with the syntax.

1. First try entering some simple examples of your own, such as

```js
10 + 7;
9 \* 8;
60 % 3;
```

2. You can also try declaring and initializing some numbers inside variables, and try using those in the sums — the variables will behave exactly like the values they hold for the purposes of the sum. For example:

```js
const num1 = 10;
const num2 = 50;
9 \* num1;
num1 \*\* 3;
num2 / num1;
```

3. Last for this section, try entering some more complex expressions, such as:

```js
5 + 10 \* 3;
(num2 % 9) \* num1;
num2 + num1 / 8 + 2;
```

Parts of this last set of calculations might not give you quite the result you were expecting; the section below might well give the answer as to why.

### Operator precedence

Let's look at the last example from above, assuming that `num2` holds the value 50 and `num1` holds the value 10 (as originally stated above):

```js
num2 + num1 / 8 + 2;
```

As a human being, you may read this as *"50 plus 10 equals 60"*, then *"8 plus 2 equals 10"*, and finally *"60 divided by 10 equals 6"*.

But the browser does *"10 divided by 8 equals 1.25"*, then *"50 plus 1.25 plus 2 equals 53.25"*.

This is because of **operator precedence** — some operators are applied before others when calculating the result of a calculation (referred to as an *expression*, in programming). Operator precedence in JavaScript is the same as is taught in math classes in school — multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right).

If you want to override operator precedence, you can put parentheses around the parts that you want to be explicitly dealt with first. So to get a result of 6, we could do this:

```js
(num2 + num1) / (8 + 2);
```

Try it and see.

**Note:** A full list of all JavaScript operators and their precedence can be found in Operator precedence.

Increment and decrement operators
---------------------------------

Sometimes you'll want to repeatedly add or subtract one to or from a numeric variable value. This can be conveniently done using the increment (`++`) and decrement (`--`) operators. We used `++` in our "Guess the number" game back in our first splash into JavaScript article, when we added 1 to our `guessCount` variable to keep track of how many guesses the user has left after each turn.

```js
guessCount++;
```

Let's try playing with these in your console. For a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself. The following will return an error:

```js
3++;
```

So, you can only increment an existing variable. Try this:

```js
let num1 = 4;
num1++;
```

Okay, strangeness number 2! When you do this, you'll see a value of 4 returned — this is because the browser returns the current value, *then* increments the variable. You can see that it's been incremented if you return the variable value again:

```js
num1;
```

The same is true of `--` : try the following

```js
let num2 = 6;
num2--;
num2;
```

**Note:** You can make the browser do it the other way round — increment/decrement the variable *then* return the value — by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use `++num1` and `--num2`.

Assignment operators
--------------------

Assignment operators are operators that assign a value to a variable. We have already used the most basic one, `=`, loads of times — it assigns the variable on the left the value stated on the right:

```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x = y; // x now contains the same value y contains, 4
```

But there are some more complex types, which provide useful shortcuts to keep your code neater and more efficient. The most common are listed below:

| Operator | Name | Purpose | Example | Shortcut for |
| --- | --- | --- | --- | --- |
| `+=` | Addition assignment |
 Adds the value on the right to the variable value on the left, then
 returns the new variable value
  | `x += 4;` | `x = x + 4;` |
| `-=` | Subtraction assignment |
 Subtracts the value on the right from the variable value on the left,
 and returns the new variable value
  | `x -= 3;` | `x = x - 3;` |
| `*=` | Multiplication assignment |
 Multiplies the variable value on the left by the value on the right, and
 returns the new variable value
  | `x *= 3;` | `x = x * 3;` |
| `/=` | Division assignment |
 Divides the variable value on the left by the value on the right, and
 returns the new variable value
  | `x /= 5;` | `x = x / 5;` |

Try typing some of the above examples into your console, to get an idea of how they work. In each case, see if you can guess what the value is before you type in the second line.

Note that you can quite happily use other variables on the right-hand side of each expression, for example:

```js
let x = 3; // x contains the value 3
let y = 4; // y contains the value 4
x \*= y; // x now contains the value 12
```

**Note:** There are lots of other assignment operators available, but these are the basic ones you should learn now.

Active learning: sizing a canvas box
------------------------------------

In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the Canvas API. There is no need to worry about how this works — just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables `x` and `y`, which are initially both given a value of 50.

**Open in new window**

In the editable code box above, there are two lines marked with a comment that we'd like you to update to make the box grow/shrink to certain sizes, using certain operators and/or values in each case. Let's try the following:

* Change the line that calculates x so the box is still 50px wide, but the 50 is calculated using the numbers 43 and 7 and an arithmetic operator.
* Change the line that calculates y so the box is 75px high, but the 75 is calculated using the numbers 25 and 3 and an arithmetic operator.
* Change the line that calculates x so the box is 250px wide, but the 250 is calculated using two numbers and the remainder (modulo) operator.
* Change the line that calculates y so the box is 150px high, but the 150 is calculated using three numbers and the subtraction and division operators.
* Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator.
* Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator.

Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges.

Comparison operators
--------------------

Sometimes we will want to run true/false tests, then act accordingly depending on the result of that test — to do this we use **comparison operators**.

| Operator | Name | Purpose | Example |
| --- | --- | --- | --- |
| `===` | Strict equality | Tests whether the left and right values are identical to one another | `5 === 2 + 4` |
| `!==` | Strict-non-equality | Tests whether the left and right values are **not** identical to one another | `5 !== 2 + 3` |
| `<` | Less than | Tests whether the left value is smaller than the right one. | `10 < 6` |
| `>` | Greater than | Tests whether the left value is greater than the right one. | `10 > 20` |
| `<=` | Less than or equal to | Tests whether the left value is smaller than or equal to the right one. | `3 <= 2` |
| `>=` | Greater than or equal to | Tests whether the left value is greater than or equal to the right one. | `5 >= 4` |

**Note:** You may see some people using `==` and `!=` in their tests for equality and non-equality. These are valid operators in JavaScript, but they differ from `===`/`!==`. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them.

If you try entering some of these values in a console, you'll see that they all return `true`/`false` values — those booleans we mentioned in the last article. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to:

* Display the correct text label on a button depending on whether a feature is turned on or off
* Display a game over message if a game is over or a victory message if the game has been won
* Display the correct seasonal greeting depending on what holiday season it is
* Zoom a map in or out depending on what zoom level is selected

We'll look at how to code such logic when we look at conditional statements in a future article. For now, let's look at a quick example:

```html
<button>Start machine</button>
<p>The machine is stopped.</p>
```

```js
const btn = document.querySelector("button");
const txt = document.querySelector("p");

btn.addEventListener("click", updateBtn);

function updateBtn() {
  if (btn.textContent === "Start machine") {
    btn.textContent = "Stop machine";
    txt.textContent = "The machine has started!";
  } else {
    btn.textContent = "Start machine";
    txt.textContent = "The machine is stopped.";
  }
}
```

**Open in new window**

You can see the equality operator being used just inside the `updateBtn()` function. In this case, we are not testing if two mathematical expressions have the same value — we are testing whether the text content of a button contains a certain string — but it is still the same principle at work. If the button is currently saying "Start machine" when it is pressed, we change its label to "Stop machine", and update the label as appropriate. If the button is currently saying "Stop machine" when it is pressed, we swap the display back again.

**Note:** Such a control that swaps between two states is generally referred to as a **toggle**. It toggles between one state and another — light on, light off, etc.

Test your skills!
-----------------

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Math.

Summary
-------

In this article, we have covered the fundamental information you need to know about numbers in JavaScript, for now. You'll see numbers used again and again, all the way through your JavaScript learning, so it's a good idea to get this out of the way now. If you are one of those people that doesn't enjoy math, you can take comfort in the fact that this chapter was pretty short.

In the next article, we'll explore text and how JavaScript allows us to manipulate it.

**Note:** If you do enjoy math and want to read more about how it is implemented in JavaScript, you can find a lot more detail in MDN's main JavaScript section. Great places to start are our Numbers and dates and Expressions and operators articles.

* Previous
* Overview: First steps
* Next


Handling text — strings in JavaScript - Learn web development

Handling text — strings in JavaScript
=====================================

* Previous
* Overview: First steps
* Next

Next, we'll turn our attention to strings — this is what pieces of text are called in programming. In this article, we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in strings, and joining strings together.

|  |  |
| --- | --- |
| Prerequisites: |
 A basic understanding of HTML and CSS, an
 understanding of what JavaScript is.
  |
| Objective: | To gain familiarity with the basics of strings in JavaScript. |

The power of words
------------------

Words are very important to humans — they are a large part of how we communicate. Since the Web is a largely text-based medium designed to allow humans to communicate and share information, it is useful for us to have control over the words that appear on it. HTML provides structure and meaning to our text, CSS allows us to precisely style it, and JavaScript contains a number of features for manipulating strings, creating custom welcome messages and prompts, showing the right text labels when needed, sorting terms into the desired order, and much more.

Pretty much all of the programs we've shown you so far in the course have involved some string manipulation.

Declaring strings
-----------------

Strings are dealt with similarly to numbers at first glance, but when you dig deeper you'll start to see some notable differences. Let's start by entering some basic lines into the browser developer console to familiarize ourselves.

To start with, enter the following lines:

```js
const string = "The revolution will not be televised.";
console.log(string);
```

Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.

If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines:

```js
const badString1 = This is a test;
const badString2 = 'This is a test;
const badString3 = This is a test';
```

These lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.

The following will work if you previously defined the variable `string` — try it now:

```js
const badString = string;
console.log(badString);
```

`badString` is now set to have the same value as `string`.

### Single quotes, double quotes, and backticks

In JavaScript, you can choose single quotes (`'`), double quotes (`"`), or backticks (```) to wrap your strings in. All of the following will work:

```js
const single = 'Single quotes';
const double = "Double quotes";
const backtick = `Backtick`;

console.log(single);
console.log(double);
console.log(backtick);
```

You must use the same character for the start and end of a string, or you will get an error:

```js
const badQuotes = 'This is not allowed!";
```

Strings declared using single quotes and strings declared using double quotes are the same, and which you use is down to personal preference — although it is good practice to choose one style and use it consistently in your code.

Strings declared using backticks are a special kind of string called a *template literal*. In most ways, template literals are like normal strings, but they have some special properties:

* you can embed JavaScript in them
* you can declare template literals over multiple lines
Embedding JavaScript
--------------------

Inside a template literal, you can wrap JavaScript variables or expressions inside `${ }`, and the result will be included in the string:

```js
const name = "Chris";
const greeting = `Hello, ${name}`;
console.log(greeting); // "Hello, Chris"
```

You can use the same technique to join together two variables:

```js
const one = "Hello, ";
const two = "how are you?";
const joined = `${one}${two}`;
console.log(joined); // "Hello, how are you?"
```

Joining strings together like this is called *concatenation*.

### Concatenation in context

Let's have a look at concatenation being used in action:

```html
<button>Press me</button>

```

```js
const button = document.querySelector("button");

function greet() {
  const name = prompt("What is your name?");
  const greeting = document.querySelector("#greeting");
  greeting.textContent = `Hello ${name}, nice to see you!`;
}

button.addEventListener("click", greet);
```

Here we're using the `window.prompt()` function, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case `name`. We then display a string which inserts the name into a generic greeting message.

### Concatenation using "+"

You can only use `${}` with template literals, not with normal strings. You can concatenate normal strings using the `+` operator:

```js
const greeting = "Hello";
const name = "Chris";
console.log(greeting + ", " + name); // "Hello, Chris"
```

However, template literals usually give you more readable code:

```js
const greeting = "Hello";
const name = "Chris";
console.log(`${greeting}, ${name}`); // "Hello, Chris"
```

### Including expressions in strings

You can include JavaScript expressions in template literals, as well as just variables, and the results will be included in the result:

```js
const song = "Fight the Youth";
const score = 9;
const highestScore = 10;
const output = `I like the song ${song}. I gave it a score of ${
 (score / highestScore) \* 100
}%.`;
console.log(output); // "I like the song Fight the Youth. I gave it a score of 90%."
```

Multiline strings
-----------------

Template literals respect the line breaks in the source code, so you can write strings that span multiple lines like this:

```js
const newline = `One day you finally knew
what you had to do, and began,`;
console.log(newline);

/\*
One day you finally knew
what you had to do, and began,
\*/
```

To have the equivalent output using a normal string you'd have to include line break characters (`\n`) in the string:

```js
const newline = "One day you finally knew\nwhat you had to do, and began,";
console.log(newline);

/\*
One day you finally knew
what you had to do, and began,
\*/
```

See our Template literals reference page for more examples and details of advanced features.

Including quotes in strings
---------------------------

Since we use quotes to indicate the start and end of strings, how can we include actual quotes in strings? We know that this won't work:

```js
const badQuotes = "She said "I think so!"";
```

One common option is to use one of the other characters to declare the string:

```js
const goodQuotes1 = 'She said "I think so!"';
const goodQuotes2 = `She said "I'm not going in there!"`;
```

Another option is to *escape* the problem quotation mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:

```js
const bigmouth = 'I\'ve got no right to take my place…';
console.log(bigmouth);
```

You can use the same technique to insert other special characters. See Escape sequences for more details.

Numbers vs. strings
-------------------

What happens when we try to concatenate a string and a number? Let's try it in our console:

```js
const name = "Front ";
const number = 242;
console.log(name + number); // "Front 242"
```

You might expect this to return an error, but it works just fine. How numbers should be displayed as strings is fairly well-defined, so the browser automatically converts the number to a string and concatenates the two strings.

If you have a numeric variable that you want to convert to a string, or a string variable that you want to convert to a number, you can use the following two constructs:

* The `Number()` function converts anything passed to it into a number, if it can. Try the following:

```js
const myString = "123";
const myNum = Number(myString);
console.log(typeof myNum);
// number
```

* Conversely, the `String()` function converts its argument to a string. Try this:

```js
const myNum2 = 123;
const myString2 = String(myNum2);
console.log(typeof myString2);
// string
```

These constructs can be really useful in some situations. For example, if a user enters a number into a form's text field, it's a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through `Number()` to handle this. We did exactly this in our Number Guessing Game, in line 59.

Conclusion
----------

So that's the very basics of strings covered in JavaScript. In the next article, we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.

* Previous
* Overview: First steps
* Next


What is JavaScript? - Learn web development

What is JavaScript?
===================

* Overview: First steps
* Next

 Welcome to the MDN beginner's JavaScript course!
 In this article we will look at JavaScript from a high level, answering questions such as "What is it?" and "What can you do with it?", and making sure you are comfortable with JavaScript's purpose.

|  |  |
| --- | --- |
| Prerequisites: | A basic understanding of HTML and CSS. |
| Objective: |
 To gain familiarity with what JavaScript is, what it can do, and how it
 fits into a website.
  |

A high-level definition
-----------------------

 JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved.
 It is the third layer of the layer cake of standard web technologies, two of which (HTML and CSS) we have covered in much more detail in other parts of the Learning Area.

![The three layers of standard web technologies; HTML, CSS and JavaScript](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/cake.png)

* HTML is the markup language that we use to structure and give meaning to our web content, for example defining paragraphs, headings, and data tables, or embedding images and videos in the page.
* CSS is a language of style rules that we use to apply styling to our HTML content, for example setting background colors and fonts, and laying out our content in multiple columns.
* JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)

The three layers build on top of one another nicely. Let's take a button as an example. We can mark it up using HTML to give it structure and purpose:

```html
<button type="button">Player 1: Chris</button>
```

![Button showing Player 1: Chris with no styling](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/just-html.png)

Then we can add some CSS into the mix to get it looking nice:

```css
button {
  font-family: "helvetica neue", helvetica, sans-serif;
  letter-spacing: 1px;
  text-transform: uppercase;
  border: 2px solid rgb(200 200 0 / 60%);
  background-color: rgb(0 217 217 / 60%);
  color: rgb(100 0 0 / 100%);
  box-shadow: 1px 1px 2px rgb(0 0 200 / 40%);
  border-radius: 10px;
  padding: 3px 10px;
  cursor: pointer;
}
```

![Button showing Player 1: Chris with styling](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/html-and-css.png)

And finally, we can add some JavaScript to implement dynamic behavior:

```js
const button = document.querySelector("button");

button.addEventListener("click", updateName);

function updateName() {
  const name = prompt("Enter a new name");
  button.textContent = `Player 1: ${name}`;
}
```

Try clicking on this last version of the text label to see what happens (note also that you can find this demo on GitHub — see the source code, or run it live)!

JavaScript can do a lot more than that — let's explore what in more detail.

So what can it really do?
-------------------------

The core client-side JavaScript language consists of some common programming features that allow you to do things like:

* Store useful values inside variables. In the above example for instance, we ask for a new name to be entered then store that name in a variable called `name`.
* Operations on pieces of text (known as "strings" in programming). In the above example we take the string "Player 1: " and join it to the `name` variable to create the complete text label, e.g. "Player 1: Chris".
* Running code in response to certain events occurring on a web page. We used a `click` event in our example above to detect when the label is clicked and then run the code that updates the text label.
* And much more!

What is even more exciting however is the functionality built on top of the client-side JavaScript language. So-called **Application Programming Interfaces** (**APIs**) provide you with extra superpowers to use in your JavaScript code.

 APIs are ready-made sets of code building blocks that allow a developer to implement programs that would otherwise be hard or impossible to implement.
 They do the same thing for programming that ready-made furniture kits do for home building — it is much easier to take ready-cut panels and screw them together to make a bookshelf than it is to work out the design yourself, go and find the correct wood, cut all the panels to the right size and shape, find the correct-sized screws, and *then* put them together to make a bookshelf.

They generally fall into two categories.

![Two categories of API; 3rd party APIs are shown to the side of the browser and browser APIs are in the browser](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/browser.png)

**Browser APIs** are built into your web browser, and are able to expose data from the surrounding computer environment, or do useful complex things. For example:

* The `DOM (Document Object Model) API` allows you to manipulate HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc.
 Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action.
* The `Geolocation API` retrieves geographical information.
 This is how Google Maps is able to find your location and plot it on a map.
* The `Canvas` and `WebGL` APIs allow you to create animated 2D and 3D graphics.
 People are doing some amazing things using these web technologies — see Chrome Experiments and webglsamples.
* Audio and Video APIs like `HTMLMediaElement` and `WebRTC` allow you to do really interesting things with multimedia, such as play audio and video right in a web page, or grab video from your web camera and display it on someone else's computer (try our simple Snapshot demo to get the idea).

**Note:** Many of the above demos won't work in an older browser — when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in.
 You will need to consider cross browser testing in more detail when you get closer to delivering production code (i.e. real code that real customers will use).

**Third party APIs** are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:

* The Twitter API allows you to do things like displaying your latest tweets on your website.
* The Google Maps API and OpenStreetMap API allows you to embed custom maps into your website, and other such functionality.

**Note:** These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our Client-side web APIs module.

There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps, or Instagram after studying JavaScript for 24 hours — there are a lot of basics to cover first. And that's why you're here — let's move on!

What is JavaScript doing on your page?
--------------------------------------

Here we'll actually start looking at some code, and while doing so, explore what actually happens when you run some JavaScript in your page.

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

![HTML, CSS and JavaScript code come together to create the content in the browser tab when the page is loaded](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/execution.png)

 A very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above).
 Note that the code in your web documents is generally loaded and executed in the order it appears on the page.
 Errors may occur if JavaScript is loaded and run before the HTML and CSS that it is intended to modify.
 You will learn ways around this later in the article, in the Script loading strategies section.

### Browser security

 Each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website.
 This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

**Note:** There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

### JavaScript running order

 When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom.
 This means that you need to be careful what order you put things in.
 For example, let's return to the block of JavaScript we saw in our first example:

```js
const button = document.querySelector("button");

button.addEventListener("click", updateName);

function updateName() {
  const name = prompt("Enter a new name");
  button.textContent = `Player 1: ${name}`;
}
```

Here we are selecting a button (line 1), then attaching an event listener to it (line 3) so that when the button is clicked, the `updateName()` code block (lines 5–8) is run. The `updateName()` code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the button text to update the display.

 If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — `Uncaught ReferenceError: Cannot access 'button' before initialization`.
 This means that the `button` object has not been initialized yet, so we can't add an event listener to it.

**Note:** This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

### Interpreted versus compiled code

 You might hear the terms **interpreted** and **compiled** in the context of programming.
 In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned.
 You don't have to transform the code into a different form before the browser runs it.
 The code is received in its programmer-friendly text form and processed directly from that.

 Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer.
 For example, C/C++ are compiled into machine code that is then run by the computer.
 The program is executed from a binary format, which was generated from the original program source code.

 JavaScript is a lightweight interpreted programming language.
 The web browser receives the JavaScript code in its original text form and runs the script from that.
 From a technical standpoint, most modern JavaScript interpreters actually use a technique called **just-in-time compiling** to improve performance; the JavaScript source code gets compiled into a faster, binary format while the script is being used, so that it can be run as quickly as possible.
 However, JavaScript is still considered an interpreted language, since the compilation is handled at run time, rather than ahead of time.

There are advantages to both types of language, but we won't discuss them right now.

### Server-side versus client-side code

 You might also hear the terms **server-side** and **client-side** code, especially in the context of web development.
 Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser.
 In this module we are explicitly talking about **client-side JavaScript**.

 Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser.
 Examples of popular server-side web languages include PHP, Python, Ruby, ASP.NET, and even JavaScript!
 JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find out more about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

### Dynamic versus static code

 The word **dynamic** is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required.
 Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user.
 The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

A web page with no dynamically updating content is referred to as **static** — it just shows the same content all the time.

How do you add JavaScript to your page?
---------------------------------------

 JavaScript is applied to your HTML page in a similar manner to CSS.
 Whereas CSS uses `<link>` elements to apply external stylesheets and `<style>` elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the `<script>` element. Let's learn how this works.

### Internal JavaScript

1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
2. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
3. Next, go to your text editor and add the following in your head — just before your closing `</head>` tag:

```html
<script>
 // JavaScript goes here
</script>
```

4. Now we'll add some JavaScript inside our `<script>` element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line:

```js
document.addEventListener("DOMContentLoaded", () => {
  function createParagraph() {
    const para = document.createElement("p");
    para.textContent = "You clicked the button!";
    document.body.appendChild(para);
  }

  const buttons = document.querySelectorAll("button");

  for (const button of buttons) {
    button.addEventListener("click", createParagraph);
  }
});
```

5. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.

**Note:** If your example doesn't seem to work, go through the steps again and check that you did everything right.
 Did you save your local copy of the starting code as a `.html` file?
 Did you add your `<script>` element just before the `</head>` tag?
 Did you enter the JavaScript exactly as shown? **JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.**

**Note:** You can see this version on GitHub as apply-javascript-internal.html (see it live too).

### External JavaScript

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

1. First, create a new file in the same directory as your sample HTML file. Call it `script.js` — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
2. Replace your current `<script>` element with the following:

```html
<script src="script.js" defer></script>
```

3. Inside `script.js`, add the following script:

```js
function createParagraph() {
  const para = document.createElement("p");
  para.textContent = "You clicked the button!";
  document.body.appendChild(para);
}

const buttons = document.querySelectorAll("button");

for (const button of buttons) {
  button.addEventListener("click", createParagraph);
}
```

4. Save and refresh your browser, and you should see the same thing!
 It works just the same, but now we've got our JavaScript in an external file.
 This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files.
 Plus, the HTML is easier to read without huge chunks of script dumped in it.

**Note:** You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

### Inline JavaScript handlers

 Note that sometimes you'll come across bits of actual JavaScript code living inside HTML.
 It might look something like this:

```js
function createParagraph() {
  const para = document.createElement("p");
  para.textContent = "You clicked the button!";
  document.body.appendChild(para);
}
```

```html
<button onclick="createParagraph()">Click me!</button>
```

You can try this version of our demo below.

This demo has exactly the same functionality as in the previous two sections, except that the `<button>` element includes an inline `onclick` handler to make the function run when the button is pressed.

**Please don't do this, however.** It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the `onclick="createParagraph()"` attribute on every button you want the JavaScript to apply to.

### Using addEventListener instead

 Instead of including JavaScript in your HTML, use a pure JavaScript construct.
 The `querySelectorAll()` function allows you to select all the buttons on a page.
 You can then loop through the buttons, assigning a handler for each using `addEventListener()`.
 The code for this is shown below:

```js
const buttons = document.querySelectorAll("button");

for (const button of buttons) {
  button.addEventListener("click", createParagraph);
}
```

 This might be a bit longer than the `onclick` attribute, but it will work for all buttons — no matter how many are on the page, nor how many are added or removed.
 The JavaScript does not need to be changed.

**Note:** Try editing your version of `apply-javascript.html` and add a few more buttons into the file.
 When you reload, you should find that all of the buttons when clicked will create a paragraph.
 Neat, huh?

### Script loading strategies

 There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems!
 A common problem is that all the HTML on a page is loaded in the order in which it appears.
 If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.

 In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed.
 This could cause an error, so we've used some constructs to get around it.

In the internal example, you can see this structure around the code:

```js
document.addEventListener("DOMContentLoaded", () => {
  // …
});
```

 This is an event listener, which listens for the browser's `DOMContentLoaded` event, which signifies that the HTML body is completely loaded and parsed.
 The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course).

In the external example, we use a more modern JavaScript feature to solve the problem, the `defer` attribute, which tells the browser to continue downloading the HTML content once the `<script>` tag element has been reached.

```html
<script src="script.js" defer></script>
```

In this case both the script and the HTML will load simultaneously and the code will work.

**Note:** In the external case, we did not need to use the `DOMContentLoaded` event because the `defer` attribute solved the problem for us.
 We didn't use the `defer` solution for the internal JavaScript example because `defer` only works for external scripts.

 An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the `</body>` tag), so that it would load after all the HTML has been parsed.
 The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded.
 On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.

#### async and defer

 There are actually two modern features we can use to bypass the problem of the blocking script — `async` and `defer` (which we saw above).
 Let's look at the difference between these two.

 Scripts loaded using the `async` attribute will download the script without blocking the page while the script is being fetched.
 However, once the download is complete, the script will execute, which blocks the page from rendering. This means that the rest of the content on the web page is prevented from being processed and displayed to the user until the script finishes executing.
 You get no guarantee that scripts will run in any specific order.
 It is best to use `async` when the scripts in the page run independently from each other and depend on no other script on the page.

 Scripts loaded with the `defer` attribute will load in the order they appear on the page.
 They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).

Here is a visual representation of the different script loading methods and what that means for your page:

![How the three script loading method work: default has parsing blocked while JavaScript is fetched and executed. With async, the parsing pauses for execution only. With defer, parsing isn't paused, but execution on happens after everything is else is parsed.](/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript/async-defer.jpg)

*This image is from the HTML spec, copied and cropped to a reduced version, under CC BY 4.0 license terms.*

For example, if you have the following script elements:

```html
<script async src="js/vendor/jquery.js"></script>

<script async src="js/script2.js"></script>

<script async src="js/script3.js"></script>
```

 You can't rely on the order the scripts will load in.
 `jquery.js` may load before or after `script2.js` and `script3.js` and if this is the case, any functions in those scripts depending on `jquery` will produce an error because `jquery` will not be defined at the time the script runs.

`async` should be used when you have a bunch of background scripts to load in, and you just want to get them in place as soon as possible.
 For example, maybe you have some game data files to load, which will be needed when the game actually begins, but for now you just want to get on with showing the game intro, titles, and lobby, without them being blocked by script loading.

Scripts loaded using the `defer` attribute (see below) will run in the order they appear in the page and execute them as soon as the script and content are downloaded:

```html
<script defer src="js/vendor/jquery.js"></script>

<script defer src="js/script2.js"></script>

<script defer src="js/script3.js"></script>
```

 In the second example, we can be sure that `jquery.js` will load before `script2.js` and `script3.js` and that `script2.js` will load before `script3.js`.
 They won't run until the page content has all loaded, which is useful if your scripts depend on the DOM being in place (e.g. they modify one or more elements on the page).

To summarize:

* `async` and `defer` both instruct the browser to download the script(s) in a separate thread, while the rest of the page (the DOM, etc.) is downloading, so the page loading is not blocked during the fetch process.
* scripts with an `async` attribute will execute as soon as the download is complete.
 This blocks the page and does not guarantee any specific execution order.
* scripts with a `defer` attribute will load in the order they are in and will only execute once everything has finished loading.
* If your scripts should be run immediately and they don't have any dependencies, then use `async`.
* If your scripts need to wait for parsing and depend on other scripts and/or the DOM being in place, load them using `defer` and put their corresponding `<script>` elements in the order you want the browser to execute them.
Comments
--------

 As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did).
 Comments are very useful, and you should use them often, particularly for larger applications.
 There are two types:

* A single line comment is written after a double forward slash (//), e.g.

```js
// I am a comment
```

* A multi-line comment is written between the strings /\* and \*/, e.g.

```js
/\*
 I am also
 a comment
\*/
```

So for example, we could annotate our last demo's JavaScript with comments like so:

```js
// Function: creates a new paragraph and appends it to the bottom of the HTML body.

function createParagraph() {
  const para = document.createElement("p");
  para.textContent = "You clicked the button!";
  document.body.appendChild(para);
}

/\*
 1. Get references to all the buttons on the page in an array format.
 2. Loop through all the buttons and add a click event listener to each one.

 When any button is pressed, the createParagraph() function will be run.
\*/

const buttons = document.querySelectorAll("button");

for (const button of buttons) {
  button.addEventListener("click", createParagraph);
}
```

**Note:** In general more comments are usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).

Summary
-------

 So there you go, your first step into the world of JavaScript.
 We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it.
 Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

 JavaScript may seem a bit daunting right now, but don't worry — in this course, we will take you through it in simple steps that will make sense going forward.
 In the next article, we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

* Overview: First steps
* Next