JavaScript for Complete Beginners - Session 1 - Hello World

This is the basic JavaScript module. We will learn JavaScript in a top-down fashion.

When we say Top-Down, we mean that we will start with a goal.

Even if the goal is very far away, we will use it as a compassing for pointing to the truth north, so we can get there.

Our goal is to build an advanced calculator.

This calculator is advanced in the sense that not only can it handle more formulas than what a regular calculators could, it can also be used and embedded by anyone who wants to provide calculators on their site for some specific formulas. For example:

and any other sorts of "calculator" that you can think of, that you might want to create fairly quickly and easily to get it working on your website.

We might even be able to use it as a mini spreadsheet. Yeah think of a mini-spreadsheet, which might give us a good mental model of what we are trying to do.

Chances are - we will not finish building this calculator inside this module, but we can work toward it.

Prerequisites

For this course, we are assuming that you know the following:

Obviously, if you already know JavaScript, this module might be more of a refresher, though how to build up to an advanced calculator might still be of interest to you if you have never done it before.

How to Write Your First Program

Since the assumption is that we don't know anything at all, we have to start from the very basics. In programming, the easiest thing to do is usually try to print out something. We call this the "Hello world" program, meaning that it's a program that prints "Hello world", i.e. announcing itself to the world that it exists.

Okay so let's get started!

For most of other programming languages, you'll need to get a copy of the programming language tools (usually either a compiler or an intrepeter), but JavaScript is special, because it's available in every single modern browser. That's right, your browser is a full-fledge programming environment! JavaScript is probably the most accessible programming language in the world due to pretty much everyone has a web browser that they can get hold of.

It's obviously harder on mobile devices even though they also have a browser. Programming is much easier with keyboards as you'll be typing A LOT.

You can use any browser. As of 2017, I personally find Chrome's developer tool easiest to work with, so I'll be showing you in Chrome, but Firefox and Safari also work well (Edge is still a bit lacking). Things change fast in the web world though, so perhaps this will be updated in the future.

Open up the developer console (View > Developer > JavaScript console). You'll see something that looks like

Notice the flashing cursor - that's the prompt where you can type in code and have it evaluated as JavaScript. So let's type in something:

> 1 

(Don't type the >, which is the prompt. Just type what's after the prompt)

You should see the console prints something like the below back to you

< 1

Congratulations, you have just written your first JavaScript program!

Go ahead and type in another number. 2, 3, 50, 100. And you'll see them print back to you as well.

You might get adventurous and type in something like 1 + 2 * 3 (which should give you 7 as answer). You'll find that JavaScript behaves as you expected with basic mathematical formulas!

Don't try to go too fast though. People get lost in programming because they try to move too quickly without having solid foundations. So don't go crazy in trying to use it to type in whatever you want just yet.

Let's take things a bit slower.

What you are playing with is usually called a JavaScript console. It basically takes in what you typed in and tries to run it as JavaScript code.

In more "technical" terms, what you are seeing is something called a "REPL", which stands for the 4 steps that the program does:

  1. Read - reads what you have typed in. If you haven't typed in anything (and pressed ENTER), wait until you do.
  2. Eval - evaluates what was read and attempts to run it.
  3. Print - gets the result of the evaluation and "prints it out", i.e. displays on screen.
  4. Lloop - repeats from step 1 again.

REPL is very powerful, especially when comes to learning purposes, because it gives you immediate feedback. There are other languages with REPL as well, so it's not unique to JavaScript, and you'll find languages with REPL are usually easier to work with due to the short feedback cycle.

Okay, so let's get back to our learning here. You have discovered the power hidden inside your browser, and you have successfully typed in numbers and have them printed out. But now you remembered that we are trying to write a "hello world" program, but right now we aren't printing out hello world yet.

So go ahead and type the following into your console (again, remember not to type the prompt).

> "Hello world"

Voila - you now see "hello world" printed back at you! Mission accomplished!

Well - let's take it a bit further. Instead of the above, type:

> hello world

That's right - without the two double quotes, and let's see what happens.

Ah - your browser now gives you something like

x Uncaught SyntaxError: Unexpected Identifier

Congrats - this is your first error message (unless you have been running ahead and experiment, of course).

What happened here? Why did it work with quotes, but gives back this error message that you don't understand yet without quotes?

This is where we will talk a bit about the "syntax" of JavaScript. When you type in "hello world" (with the quotes), you are typing in something called a string, which is a data type that JavaScript understands, meaning that it knows its meaning and what it should do with them (in this case, give the **P**rint step what you have typed in).

When you type the above without the quotes, however, JavaScript reads what you have typed as two separate words, hello and world, and understand them as something called identifiers.

An identifier is like a street address. It's a piece of information that you can use to lookup the actual content. (think of it this way - your home address tells people how to get to your house).

In a REPL, if JavaScript (or any other programming language, really - these concepts are applicable to all programming languages) reads in an identifier, it'll try to evaluate the identifier by looking for what the identifier points to, and if it finds the info, it'll print out what it points to, otherwise it will throw an error saying the identifier is unknown.

But wait, we didn't get an unknown identifier error, we got an unexpected identifier error - are they the same thing?

Good catch, no they are not the same thing. Try to type the following into REPL again:

> hello

This time you should get something like

x Uncaught ReferenceError: hello is not defined

Okay - so it says hello is not defined, which is another way of saying "unknown identifier". But how did we get a different error earlier then?

The difference between what we typed in gives us the clue. Instead of typing in 1 identifier (which gives us the expected unknown identifier error), we typed in two identifiers consecutively separated by space.

JavaScript REPL tries to evaluate everything you typed in (before ENTER) as a single unit (i.e. the E step happens as a single step) no matter what you typed in, and it just turns out that having two consecutive identifiers like that is an invalid way of writing JavaScript. I.e. you cannot put two identifiers back to back in JavaScript without them either being related or separated somehow.

If we type in the following instead

> hello; world

Then we get back the same

x Uncaught ReferenceError: hello is not defined

The semicolon ; means "the parts prior to semicolon forms a unit of code and is unrelated the what's following", so even though the JavaScript console reads in both hello and world together as a unit, because of the semicolon, JavaScript treats it as two separate units, and when it tries to evaluate the first unit, we get back the unknown identifier error.

As you get deeper in programming, you'll encounter a lot of errors, because you'll be making a lot of mistakes, even as a seasoned developer. Don't get frustrated about errors - they are your friend, since they tell you what you need to fix with your program.

What should you take away from the above so far?

It means that you'll need to pay attention to what you type. Unlike English, grammars matters much more in programming languages (they need to be exact), otherwise you'll get a lot of errors.

Luckily that although programming languages are demanding grammar wise, they are a lot simpler when compared to English, so fear not - just understand their behaviors as given, so you can know what to expect and therefore overcome them.

Let's get back to our first programming lesson.

Although we have accomplished printing out "hello world" on the screen, since we did that inside the JavaScript console, technically we haven't really done it yet, since when it comes to web pages, only developers would work with JavaScript consoles. Most people would only read web pages.

So unless you want to build programs that no one sees, we still have quite a few steps to do - we need to print this in an HTML page!

All right - it's time to start writing some "real" JavaScript programs that can print to web pages.

Open up your favorite text editor. And let's just create a blank html page.

<html>
  <head>
  </head>
  <body>
  </body>
</html>

What we want to do is to write a small script that will print "hello world" into that page when you load the page into the browser.

Go ahead and save the html, call it something like helloworld.html. Find it on your hard drive (via your file browser), and then double click it to open it.

You should see a blank window open. Alright - we now know our blank html page works. Now add the following to the <head> element.

<script>
  document.write('hello world');
</script>

Save it and run again. Viola - you now see hello world shown in the web page! What just happened here?

First - the <script> tag is how you add "script" - a little snippet of code that'll be run when the page is loaded - into html. So when we add it in the page, we are telling the browser to run the code inside the tags.

Second, when inside a web page, there is an identifer called document, that points to, you guessed it, this web page. So in JavaScript, document basically gives you access to everything associated with the web page as long as you know what you are looking for, and you can then "program" the web page to your heart's content.

The document happens to have a method attached to it called write. When you run the method with a string, it will then "write" what you passed in to the document.

When it comes to programming web pages, working with document and everything else associated with it (together they are called DOM, which stands for Document Object Model), is inevitable. Programming DOM is how you add interactivity to web pages, so we'll keep coming back to DOM again and again.

If you don't understand this last part yet - no worries. We will go through them in much more details in the upcoming lessons.

For now - congratulations on your first real program! You now know how to print out "hello world", and we are one step closer toward our goal!