What is JavaScript?

If you are taking this course, you know that JavaScript is a popular client-side programming language. Client-side programs run on your computer's web browser. So, where can you see JavasScript on the web? When you visit a website and submit a form, that's JavaScript. The language is easy to use and learn. This article introduces several features of the language and some of the things you can do with it. 

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:

const para = document.querySelector('p');
para.addEventListener('click', updateName);
function updateName() {
 let name = prompt('Enter a new name');
 para.textContent = 'Player 1: ' + name;
}

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph 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 paragraph 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  -  TypeError: para is undefined. This means that the para object does not exist 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.