Lesson 3 of 199:49 video

JavaScript basics: variables, conditions, loops and functions

What a program is made of, how it remembers values, makes decisions and repeats itself, what a function is, and why putting a return value on the next line makes the function return undefined.

In this lesson

  1. 0:00 Intro
  2. 0:41 From values to programs
  3. 1:06 Statements
  4. 2:46 Variables
  5. 4:22 Names you didn't write
  6. 4:58 Decisions
  7. 5:51 Loops
  8. 7:01 Functions
  9. 9:10 Next time

Transcript

Intro

Here's a tiny JavaScript function, and it answers forty-two. Press Enter after the word return, so the forty-two moves to the next line, and now it answers undefined. Nothing else changed, and there's no error. How can one line break change what a program does? Today, we find out.

By the end of this video, you'll understand three things. One: what a program is made of. Two: how a program remembers values, makes decisions and repeats itself. Three: what a function is, and why that line break broke one.

From values to programs

Last time, we made values and used operators to turn them into new ones. That's the raw material. This time, we build something with it: a program. We'll look at the pieces JavaScript gives you for that, from variables that remember a value to decisions, loops and functions. By the end, you'll know how a program is put together, and the harder parts of the language will have something to stand on.

Statements

A program is made of statements, the way a recipe is made of steps. Each statement is one complete instruction, and when the program runs, JavaScript works down the list from top to bottom. Most statements start with a keyword that says what kind of instruction it is, and those keywords are the map of this episode. let declares a variable. if makes a decision. while repeats. function gives a piece of code a name. A statement can hold other statements too: the if here wraps another one inside its curly braces. And the smallest statement of all is a lone semicolon, which does nothing.

Inside a statement, the parts that work out to a value are called expressions. Last time, every line you saw on screen was one. Five is an expression. Five plus three is an expression, and so is ten greater than two, and the fork with the question mark. An expression never stands alone. It sits where a value is needed, inside a statement or inside a bigger expression.

Put a semicolon after an expression and it becomes a statement of its own. JavaScript works out the value and throws it away. So the number two followed by a semicolon is a complete program. A useless one, but a complete one. That semicolon is how JavaScript knows where one statement ends and the next begins. Leave it off, and JavaScript usually guesses for you, treating the end of the line as the end of the statement. The rule is called automatic semicolon insertion, and it has one famous trap, which we'll meet at the end. Until then, we'll write the semicolons.

Variables

A result only exists for the moment it's produced. Five plus three gives eight, and then the eight is gone. To use a value later, you keep it in a variable: a named place that holds one value. The keyword let makes one. let, the name seconds, one equals sign, then the value ten. From now on, the name seconds works out to ten wherever an expression needs a value. seconds minus one gives nine. But look at the box: it still holds ten. Using a variable doesn't change it.

To change what a variable holds, assign it a new value with that same equals sign. seconds equals seconds minus one. The right side is worked out first, which gives nine, and nine goes into the box, replacing the ten. One equals sign stores. Three in a row, from last time, compare. A variable doesn't need a value right away, either. Declare it and leave it empty, and it holds undefined, the value from last time for a blank nobody has filled in yet.

let is new, as JavaScript goes. The first versions of the language had one keyword for variables, var, and you'll still meet it in older code. The 2015 update we covered earlier in this series added let and const, to fix problems with var that we'll get to next time. For now, read var as the old way of writing let. const is the one that's different. It makes a constant, a variable that can't be assigned again. Try, and JavaScript stops with an error.

Names you didn't write

Your program doesn't start with an empty list of names. JavaScript defines some before your first line runs. Infinity and NaN from last time are two of them. Math holds the math tools, like Math dot round. And console is how your program talks to you: console dot log prints whatever you give it, and we'll use it for the rest of this episode. Where JavaScript runs adds more names. In a browser, document is the web page itself, and alert pops up a message. console dot log and alert are functions, and functions are where this episode ends.

Decisions

So far, every statement runs, in order, every time. An if statement changes that. It runs its block only when a condition is true. if, then the condition in parentheses, then the block in curly braces. seconds greater than zero is true while the countdown is running, so the block runs and prints the number. When seconds reaches zero, the condition is false, and JavaScript skips the whole block as if it weren't there.

Add else, and the skipped case gets its own block. Now it's a fork, like the ternary from last time: true takes the first road, false takes the second. The difference is what waits at the end of the roads. The ternary chooses between two values. if and else choose between two blocks of statements, and a block can hold as many statements as you need, including more decisions.

Loops

Printing the whole countdown by hand means writing the same two statements ten times. A loop writes them once and repeats them. while works like if, except that when the block finishes, JavaScript goes back and checks the condition again. seconds is ten, so print it and take one off. Nine, so again. The block keeps running until seconds reaches zero, the condition turns false, and the program carries on past the loop. If nothing in the block ever changes the condition, it never turns false, and the loop runs forever. In a browser, that's a frozen page.

Most loops have the same three parts: a starting value, a condition, and a step that moves towards the end. The for loop puts all three inside the parentheses, separated by semicolons, so the shape of the loop shows in one line. Start seconds at ten. Keep going while it's above zero. Take one off after each round. The block only has to hold what you actually want repeated, and both loops print the same countdown. Use for when you know how many rounds there are, and while when you don't.

Functions

Now the countdown works, and we want it again somewhere else in the program, maybe from a different number. Copying the loop around is how bugs spread. Instead, wrap it in a function: a block of statements with a name, that runs only when you ask. The keyword function, the name countdown, then parentheses, then the block. Inside the parentheses goes a parameter, from: a variable that gets its value each time the function is called. Nothing runs yet. Defining a function is writing the recipe down. To run it, call it: the name, then parentheses holding the value to use. countdown of ten counts from ten. countdown of three counts from three. The same code, twice, without writing it twice.

A function can also hand a value back, with the return statement: return, then an expression. The function stops there, and the call works out to that value. half of ten gives five. That makes a call an expression, so it can sit anywhere a value can, even inside another call. A function with no return still gives something back: undefined. And here's the trap from earlier. Write return, then put the value on the next line, and automatic semicolon insertion ends the statement right after return. The value is never reached, and the function returns undefined. Keep the value on the same line as return.

One last thing, and it's the reason functions matter so much in JavaScript. A function is a value, like a number or a string. Ask type of about countdown, and it says function. So a variable can hold one, and a function can be handed to another function as an argument. The formal phrase is that functions are first-class values. That's how a web page reacts to you: you hand the browser a function, and the browser calls it when the click happens. We'll build exactly that later in this series.

Next time

That's how a JavaScript program is built, in one line: statements run from top to bottom, variables remember, decisions and loops choose what runs and how often, and functions wrap it up to use again. Next time, we stay with functions and go deeper: a shorter way to write them, where their variables live and how a function can remember them, and what happens when a function takes another function, or calls itself.

Learn more