How To

JavaScript Programming for Absolute Beginners

31 Aug , 2016  

Ok, are you ready to start programming in JavaScript?

That’s what we’re going to do today.

JavaScript, as I’m sure you’re aware, is one of the most-used programming languages today.

And it’s still growing in popularity!

Every day there are new JavaScript frameworks and libraries being released.

So there’s never been a better time to start learning.

Because everyone has to start somewhere, we’ll keep things simple. We’ll practice some basic programming concepts using JavasScript, and learn how JavaScript, HTML and your browser all work together.

Let’s get started!

The absolute beginners guide to JavaScript

 

Goals

Here’s what you’re going to learn today:

  • How we can use HTML to trigger some JavaScript
  • How to write JavaScript inside an HTML web page
  • How to define a simple JavaScript function
  • To use JavaScript to make changes to a web page
  • How to use abstraction
  • How to use and define variables

Phew! That’s plenty!

How to use this article

This article builds on previous articles on this site. If you’re not at least a little familiar with HTML and Computational Thinking, I suggest you catch up with the following articles:

Remember UrkelBot from the Computational Thinking article?

Computational thinking with UrkelBotWe put him in a kitchen to make a cup of tea.

In the kitchen, he didn’t really know how to use a kettle or turn on a tap.

Now you’ve swapped places with UrkelBot.

If you haven’t programmed before, then JavaScript is going to feel like that kitchen did to our robot.

You’re going to be presented with tools that don’t at first make any sense. Don’t worry!

The goal today isn’t to understand everything about JavaScript. The goal here is to practice some fundamental programming ideas, and see JavaScript working in a browser.

You’ll learn some introductory JavaScript syntax, which you can build on for future learning.

So go through the article one section at a time.

Each section has a core learning goal (that I’ll spell out at the beginning) that I hope the section will convey successfully. Anything else presented along the way is a bonus, but not vital for today’s article.

Key Takeaways:

  • This article assumes a very basic understanding of HTML and programming concepts
  • The primary goal is to practice some fundamental programming concepts in JavaScript
  • The secondary goal is getting a little familiarity with JavaScript syntax.

Click here for your free HTML, CSS and JavaScript E-book

How programming languages work

Learning goal: Gain a high-level understanding of how a program is turned into something a computer understands and acts upon.

As I’ve mentioned in other articles, programming is often called ‘coding’, because we as programmers encode our instructions in a format that can be understood by a computer.

Of course we can’t say Computer! Count all the records in the invoice file! But we might say something[i] like:

for each invoice record
   add one to the count

That’s the first step in encoding our instruction for a computer.

Lucky for us, the rest is taken care of by other computer programs, but it goes something like this:

Compiling source code for computer

In that image, you can see that our source file (where we type our programming code), is encoded into a series of formats that are increasingly more computer friendly.

Finally, it reaches a stage where it’s in a format that corresponds to the instructions used internally by a computer.

The computer’s then free to orchestrate activity amongst its parts to carry out the instructions that were in your source file.

There’s a couple things to note here:

  • Once upon a long time ago, people programmed computers using that lowest level of programming code (yes 1s and 0s).
  • The different levels of code can be viewed as levels of abstraction.
    • The highest level is the one we deal with when we type code into a source file.
    • These abstractions save us time and effort by avoiding complex detail.

Key Takeaways

  • Our programming code must be turned into ‘machine’ code before a computer can use it.
  • We have programs called interpreters, compilers and linkers to turn our code into something a computer can use
  • The programming code we use today is an abstraction that hides complex detail. This saves us time, effort and reduces the opportunity to make mistakes.

How JavaScript works in your browser

Learning goal: Gain a high-level understanding of the differences between running JavaScript and other code.

So we’ve seen how programming code is turned into something a computer understands, and then how that code is used by a computer.

JavaScript is a little different, because it uses a browser to execute all its instructions. Actually, the browser has a JavaScript Engine which is part of the browser.

 

JavaScript compiled in browser

The JavaScript Engine compiles the JavaScript and executes it, which in turn controls the browser.

Key Takeaways

  • JavaScript is compiled like other programming languages
  • The difference is that the resulting machine code is executed within the browser.

How JavaScript, HTML and the browser work together

Learning goal: Understand how JavaScript can affect HTML, and how that affects the browser.

Now that we’ve seen how JavaScript code is executed in a browser, let’s take a closer look at how that works in our HTML.

As we’ve seen in other articles, an HTML page is structured like this:
HTML page structure

We can use <script>  tags to add code to the HTML. We normally put <script>  tags in the <head>  section of a page, but more often these days we put it at the very end of the page.

This is to stop very large pieces of JavaScript making a page load slowly.

For simplicity, we’ll put our code at the top of the page, since it’s going to be small anyway.

Our page is going to look kind of like this:

HTML page structure with script tags

But how does the JavaScript do anything? It’s just sitting there in the page, right?

Well, there are lots of ways of running JavaScript in a page, but the most common, and what we’ll be focusing on today, is events.

Every time you do something on a web page like click a button, or type in a text box, you trigger an event.

When an event occurs, it’s packed up in a parcel of information:

  • What the event was (a click? A keypress?)
  • Information about the event (what was clicked? What key was pressed?)

The browser uses this information to react to the user’s actions.

Did the user click a submit button? The browser had better check what the form the button belongs to, and submit the form.

Did the user type in an input? The browser had better update the input to show what the user typed.

The great thing is, we can catch these events in our HTML, and then pass them to our JavaScript.

So imagine we have a <button> element that’s not part of a form. We can tell the browser that we want to know when our <button>  is clicked like this:

<button onclick=”our-javascript-goes-here”>

So now when our <button>  is clicked the browser executes whatever our-javascript-goes-here may be.

And the beautiful thing is that our JavaScript can then go and change what the user sees on the page, creating a cycle of interaction.

Key Takeaways

  • JavaScript can appear in HTML pages between <script>  tags
  • We can execute JavaScript by linking it to events.
  • Events can be triggered by a user doing something in the browser.
  • JavaScript can update the browser display, so the user knows their action had an effect!

Let’s try some JavaScript in a sample page

Learning goal: Execute JavaScript for the first time; learn the syntax for calling a JavaScript function.

Ok! It’s time to try some JavaScript! We’ll start super-simple and work our way up to something more interesting.

To begin with, open up a text editor, and enter and save the following (js-intro.html):

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Introduction</title>
</head>
<body>
  <h1>HTML, meet JavaScript</h1>
  <button onclick="alert('Why, hello there.')">Say Hi</button>
</body>
</html>

Open it in your browser, and you should see something like:

JavaScript and HTML example

And if you click the button:

JavaScript and HTML example

So let’s take a look at what’s going on here:

<button onclick="alert('Why, hello there.')">Say Hi</button>

There’s a couple new things here.

One is the <button>  tag. This is very similar to <input type=”submit”> . The main difference is that it has a closing </button> tag, which means we can stuff other HTML inside it.

The most interesting part is this:

onclick="alert('Why, hello there.')"

There’s a few things to notice here:

  • The HTML attribute onclick (it’s not JavaScript!) is used to say we want to execute some code when our button is clicked.
  • All events in HTML are specified in the form onevent. E.g. onchange, onkeypress, and so on.
  • As usual with a tag attribute value, we’ve enclosed it in double-quotes (“):”alert(‘Why, hello there.’)”
  • The actual JavaScript is this:

alert(‘Why, hello there.’)

  • Notice that we’re using a string here – ‘Why, hello there.’ – which we’ve enclosed in single quotes (‘). We have to use single quotes here because the whole thing’s wrapped in double-quotes (“).
  • The browser isn’t smart enough to understand that: “alert(“Why, hello there.”)” isn’t three separate things:
    • alert(
    • Why, hello there.
    • )
  • When we say string in programming, we mean a piece of text, usually enclosed in quotes. For example: “A”, “this is a string”, ‘this is also a string’.

Let’s take a closer look at our JavaScript code:

alert('Why, hello there.')

Remember when I said you’d be like UrkelBot navigating an unfamiliar kitchen? Well this is your first mystery appliance. Every kitchen has them, right? A cupboard full of appliances that on first glance don’t really make sense?

Mystery Appliance

JavaScript has built-in tools (like alert) that we can use. They’re unfamiliar at first, but you’ll get to be more familiar with them as you use them.

So alert is a JavaScript function. A function is a series of commands bundled up together with a name on them.

As we discovered, alert creates a little window on our screen with text in it. When we give a function a value to use like that, that value is called a parameter. Functions are executed (or called) like this:

functionName(parameter)

If a function had two parameters, we’d call it like this (note the comma between parameters):

functionName(parameter1, parameter2)

And if it had no parameters:

functionName()

In JavaScript, a function always has brackets “(” and “)” at the end, even if it has no parameters.

So looking at our JavaScript example then:

alert('Why, hello there.')

We can say we’re calling the function alert with the parameter ‘Why, hello there.’

These rules for writing JavaScript (and other languages) are called syntax.

A programming language syntax simplifies natural language commands (“Please open a small window and display ‘Why, hello there.’ in it.”) so that computers can understand them.

Let’s try another example:

Try changing the parameter in our alert function to ‘This is my first JavaScript programming exercise.’

Key Takeaways

  • We can attach JavaScript to events in HTML
  • We do this using onevent We used onclick in our example.
  • JavaScript has functions
  • Functions are commands grouped together with a name.
  • We can pass one or more values to a function. These values are called parameters.
  • Functions are always used with “(” and “)” at the end of the function name.
  • Parameters are always separated by a comma (,).

Time to roll your own JavaScript

Learning goal: Define your own JavaScript function; execute it with an HTML event.

So now we’ve used JavaScript’s alert function, let’s try making our own. Update your example HTML file so that it looks like this:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Introduction</title>

  <script type="text/javascript">

    function showAlert(alertMsg){
      alert(alertMsg);
    }

  </script>
</head>
<body>
  <h1>HTML, meet JavaScript</h1>
  <button onclick="showAlert('Why, hello there.')">Say Hi</button>
</body>
</html>

Note – we’ve added some <script>  tags, a function definition inside them, and we’ve updated our <button>’s  ‘onclick’ attribute.

If you reload that file in your browser, you should get exactly the same behaviour! Never mind – we’re covering some important concepts here and we’ll start expanding our JavaScript capabilities soon 🙂

Let’s take a look at our changes.

First, we have our <script>  tag:

<script type="text/javascript">

You can see we’re using a type attribute with a value of “text/javascript”. As always, we need to spell out to the browser exactly what we’re up to!

Even though the browser will guess that our code is JavaScript, we should always tell it explicitly because it’s possible to use languages other than JavaScript in <script> tags.

Next:

function showAlert(alertMsg){
  alert(alertMsg);
}

What’s happening here? We’ve made our own function!

In the last section I said that a function is some commands grouped together with a name.

In this case there’s only one command, JavaScript’s alert function, which we saw in the previous section.

And to make our function and give it a name, we have this:

function showAlert ( alertMsg )

We use the word function to tell JavaScript we’re making a new function. Then we give it a name. For names like this it’s best to stick to normal alphabetic letters (A-Z, a-z). Also, we can’t use spaces or hyphens (-) in function names either.

Notice that the function name is in the form verbNoun, where show is the verb, and Alert is the noun. This helps us know what a function does. It shows an alert.

We could call the function xyz(abc) and it would work exactly the same – but we wouldn’t know what it does!

Anyway, you’ll notice that the showAlert has (alertMsg) on the end of it.

In the last section we saw a parameter being passed to alert like this:

alert('Why, hello there.')

‘Why, hello there.’ is the parameter. So we give a function a parameter. But how does it receive it?

It receives it with a named parameter. The actual definition of the alert function starts like this:

function alert(message)

So ‘Why, hello there.’ goes in, and it comes out as message. In this case, message is like a container for ‘Why, hello there.’

For our new function showAlert we’ve given it a container for messages called alertMsg.

There are two more important things to cover with our new function. Let’s look at the function again:

function showAlert(alertMsg){
  alert(alertMsg);
}

The first of these is that alert(alertMsg) has a semi-colon (;) on the end of it. Semi-colons at the end of a line in a JavaScript function are optional, but I believe it’s best to use them.

The second, is that there are curly braces “{” and “}” around the body of the function. This is how a function’s commands are grouped together.

Finally, let’s see how we use our new function:

<button onclick="showAlert('Why, hello there.')">

As you can see we’ve just exchanged alert for our own showAlert. Because we package ‘Why, hello there.’ up in a parameter called alertMsg, we’re free to pass it along to the call to alert in our own function.

What we’ve just covered here is the syntax for declaring a function. We could define any function in the same way:

function nameOfFunction(parameter1, parameter2,...){
    command1;
    command2;
    etc
}

Key Takeaways

  • We can make our own JavaScript commands, called functions.
  • Functions can have parameters, which are containers for the values we give functions.
  • A function doesn’t have to have parameters!
  • We can call our functions the same way we call JavaScript commands like alert.
  • You can name a function however you want, but descriptive names are best.
  • Parameters should also have descriptive names.
  • Descriptive names help us as programmers remember what our code does (it’s surprisingly easy to forget!)

Click here for your free HTML, CSS and JavaScript E-book

Use JavaScript to write a message on our page

Learning goal: Learn how to declare a variable; see how we get data from an HTML page; see how we write data to an HTML page.

In the previous section we replaced JavaScript’s alert function with one of our own.

But I’m sure you’ve noticed that most websites don’t communicate with you by opening little windows with messages in them!

It’s much better to change the actual web page. And that’s what we’ll do now:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Introduction</title>
  <script type="text/javascript">

    function updateMessage(){
      var msg;
      msg = document.getElementById('msgInput').value;
      document.getElementById('message').innerHTML = msg;
    }

  </script>
</head>
<body>
  <h1>HTML, meet JavaScript</h1>
  
  <div>Get typing:</div>
  <input id="msgInput" type="text" onkeyup="updateMessage()">
  
  <h2 id="message"></h2>
</body>
</html>

There are some big changes here! Maybe make a new file (e.g. ‘js-intro-2.html’) and type the new code into it. Then open it in your browser. What do you think it will do? Try typing into the text input and see what happens!

HTML and JavaScript for beginners example

Now that you’ve done that, let’s look at our new code.

This time, we’ll start with the HTML:

<h1>HTML, meet JavaScript</h1>

<div>Get typing:</div>
<input id="msgInput" type="text" onkeyup="updateMessage()">

<h2 id="message"></h2>

So our <h1>  is the same.

Then we’ve got a <div>  with Get typing: in it. Nothing special there.

Next is a text input:

<input id="msgInput" type="text" onkeyup="updateMessage()">

Ok! Now we’ve got something new. Let’s check it out.

If you’ve read earlier articles here on HTML and Forms, you’ll already know about text inputs. You can see this one’s got an id of msgInput. You’ll see why that’s important soon.

The really interesting thing about this input is that it’s using a different event: onkeyup.

We’ve assigned updateMessage() to it. This means that when we type into that text input and our finger lifts off a key, updateMessage() will be executed.

Finally in the HTML we have:

<h2 id="message"></h2>

Hmmm. An empty <h2>  with an id set to message. You’ll see how we use this <h2>  and id value in a moment.

Time to check out our JavaScript:

  <script type="text/javascript">

    function updateMessage(){
      var msg;
      msg = document.getElementById('msgInput').value;
      document.getElementById('message').innerHTML = msg;
    }

  </script>

So the <script> tag is the same as before.

But we have a new function: updateMessage(). This is the function we assigned to that text input’s onkeyup event.

What’s it doing? You can see the curly-braces “{” and “}” grouping together three commands. And they’re pretty funky commands.

At a high level:

  • The first command makes a container (variable) called msg.
  • The next command gets whatever is in our text input and stores it in msg.
  • The last command puts the contents of msg inside our <h2> tags.

Let’s take a closer look. Here’s the first line:

var msg;

This creates a variable valled msg. var is short for variable.

What’s a variable?

Like the parameter I described earlier, a variable is a container we can temporarily store something in, like a number (1, 2, 50.23 etc), or a string (“A”, ‘B’, “Here’s lookin’ at you, kid.”).

When we put a value into a variable like that, we can pass the variable around and re-use it over and over. That way you only have to type “Here’s lookin’ at you, kid” once. Thank goodness for that.

Once again I’ve ended the variable declaration with a semicolon (;).

So now we have a container called msg. What’s next?

msg = document.getElementById('msgInput').value;

Whenever you see something = somethingElse, it means that something is some kind of variable, and we’re putting the value of somethingElse into it.

The somethingElse could be a literal value, like a number or string, or it could be another variable.

Hey, let’s try that right now! Change your updateMessage() function to read as follows:

function updateMessage(){
  var msg;
  msg = "Here's lookin' at you, kid.";
  document.getElementById('message').innerHTML = msg;
}

Reload it in your browser, and try typing in that input field again. You should see something like:

Beginners JavaScript example

So we’re assigning a value to our variable msg.

It’s not a requirement for our purposes today to understand more than that.

The rest of this section deals with the nitty-gritty of how we refer to elements (HTML tags displayed in a browser) in JavaScript. We refer to them in this way so we can get data from them, or put data in them.

So it’s entirely expected for the next part not to make sense – but only because it’s unfamiliar to you. It’s not complicated, just weird (for now!)

Anyway, let’s change the function back again:

function updateMessage(){
  var msg;
  msg = document.getElementById('msgInput').value;
  document.getElementById('message').innerHTML = msg;
}

What are we assigning to msg here?

msg = document.getElementById('msgInput').value;

You know how I said that variables are like containers we put values in?

Well those containers can hold more containers, and so on down. Just like the Russian dolls.

Here’s what each part of document.getElementById(‘msgInput’).value; means:

  • document: this is a reference to our HTML document js-intro-2.html. Yes! JavaScript lets us play directly with our HTML.
  • .getElementById: a function that belongs to document (containers can have functions in them too). The parameter we give it (msgInput) is the id of our HTML <input>  (check the HTML again to see for yourself).
  • So getElementById(‘msgInput’) is like a container for our HTML <input> .
  • .value: This is the text you typed into the <input> .
  • When we want to refer to a container inside another container, we put dots between their names:
    • outerContainer.innerContainer
    • Container isn’t the correct word, but it’s a good way to think about these things for now.

Phew. That’s the fundamental JavaScript machinery for getting an HTML element (tag) from a page in the browser and doing something with it.

Finally, the last line of the function:

document.getElementById('message').innerHTML = msg;

We already know that document.getElementById is a function that gives us a container for an HTML element.

This time we’re asking for an element with an id of ‘message’.

Quick! Check the HTML to see which tag that will be…

Ok, I hope you checked and saw that it’s the <h2> tag. This time though, we’re using assignment (=) to put a value into our element’s innerHTML. innerHTML is whatever is in between an element’s tags.

Remember when we assigned “Here’s lookin’ at you, kid.” to msg earlier, and then assigned msg to document.getElementById(‘message’).innerHTML = msg;

That was just like typing <h2 id=”message”> Here’s lookin’ at you, kid.</h2>  directly into our HTML file.

Only now, msg has been assigned the value of whatever is in our <input>  field.

Once we assign msg to the <h2> ‘s innerHTML, the <h2>  will contain whatever the <input>  tag contains.

Golly.

Key Takeaways:

  • Variables are like a temporary container for storing something
  • Variables let us pass values around with a label (like msg) without having to refer to the actual contents of the variable
  • Variables are declared like this: var variableName;
  • We can use getElementById(id) to get a reference to an HTML element
  • Remember an HTML element is a tag from an HTML file that’s been rendered – displayed – in a browser.
  • getElementById(id).value is what’s inside an <input> field. It’ll be nothing if id isn’t an <input> field.
  • getElementById(id).innerHTML = value put’s whatever is in value inside the HTML tags of id.

A simple abstraction with JavaScript

Learning goal: See how an abstraction can be used to hide complexity, and isolate costly changes

You know, I really don’t like document.getElementById(). It’s long, ugly-looking and I usually mis-type it.

So let’s replace it with something nicer in our code:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Introduction</title>

  <script type="text/javascript">

    function updateMessage(){
      var msg;
      msg = getInput();
      writeMessage(msg);
    }

    function getInput() {
      return document.getElementById('msgInput').value;
    }

    function writeMessage(theMessage){
      document.getElementById('message').innerHTML = theMessage;
    }
  </script>

</head>
<body>
  <h1>HTML, meet JavaScript</h1>
  <div>Get typing:</div>
  <input id="msgInput" onkeyup="updateMessage()">
  <h2 id="message"></h2>
</body>
</html>

This time only the JavaScript has changed. Update your file and reload it in your browser. Everything should work just like it did before.

Our JavaScript has two new functions, and the updateMessage function uses them:

    function updateMessage(){
      var msg;
      msg = getInput();
      writeMessage(msg);
    }

    function getInput() {
      return document.getElementById('msgInput').value;
    }

    function writeMessage(theMessage){
      document.getElementById('message').innerHTML = theMessage;
    }

So updateMessage looks a lot more straightforward now. It declares msg, assigns getInput() to it and then uses writeMessage(msg). That, I think, is more intuitive than our previous version of updateMessage().

In fact, we’ve introduced a very simple abstraction. Which is to say invent a name with meaning (getInput) to replace something that has no obvious meaning on its own (document.getElementById…).

Let’s look at these new functions:

    function getInput() {
      return document.getElementById('msgInput').value;
    }

This is the first time we’ve seen return in a function. We can explain the use of return as follows:

alert("Hello Dolly");

Is exactly the same as:

function sayHello(){
  return "Hello Dolly";
}

alert(sayHello())

It’s like saying that sayHello() is the same as “Hello Dolly”.

So in our updated code we’re saying that getInput() is the same as document.getElementById(‘msgInput’).value.

The next function:

    function writeMessage(theMessage){
      document.getElementById('message').innerHTML = theMessage;
    }

takes a parameter theMessage and assigns it to the innerHTML of our <h2>  tag, just like we did before.

There’s not much advantage of using functions like these if we’re only going to use them once.

But imagine if in our code we had to read from our <input>  and write to our <h2> over and over again.

By making functions with sensible names we make our code more readable and hide complexity, which makes it more understandable.

We also avoid typing long, complicated pieces of code over and over again. This reduces the opportunity for making mistakes.

Additionally, imagine if we did use these functions many, maybe hundreds of times. And then we had to change where we get the input value from. If we used document.getElementById(‘msgInput’).value everywhere in our code, we’d have to make hundreds of changes.

If we replaced document.getElementById(‘msgInput’).value with a function, then we only have to make the change in one place, inside the function. Our code can keep calling that function getInput(), and benefit from the change.

Key Takeaways:

  • We can replace complex code with well-named functions
  • This make our code more readable and understandable
  • It saves us from coding errors
  • It hides complexity
  • It can save us from extra work in the future
  • Assigning a meaningful name to a complex operation is an example of abstraction.

Enough already!

That’s a lot.

I mean an absolute ton.

And like I said before, don’t worry if you’re not feeling super-solid of some of the more technical parts of what we’ve covered today.

If you’d like to feel more comfortable with these concepts – try playing with the code: introduce new elements and new events. See what happens!

To recap, today we’ve covered:

  • How HTML and JavaScript work together with events.
  • How put JavaScript in an HTML web page
  • How to write simple JavaScript functions
  • How to use and define variables
  • To we can change a web page with JavaScript
  • How to use abstraction

I hope it’s been useful for you!

And stick around – I’ll be introducing more JavaScript syntax in later articles, including how to make decisions, and how to do loops.

Let me know in the comments if there’s anything that needs to be clarified, improved or just done better.


[i] This is often called pseudocode – a way of expressing programming ideas without being restricted to any one language

Click here for your free HTML, CSS and JavaScript E-book

By


Leave a Reply

Your email address will not be published. Required fields are marked *