First steps in programming: loops

If you haven't read my other articles on getting started with coding you should do so before proceeding: I will assume that you can open a JavaScript console and run a basic program, know how to use variables and conditionals.

In the last post we learnt how to make the computer execute commands conditionally, printing a different message if our user entered a blank name, for example.

function Program() {
    var name = prompt("What is your name?")
    if (name == "") {
        console.log("Hello stranger")
    } else {
        console.log("Hello")
        console.log(name)
    }
}

This program says "Hello stranger" if no name is provided and moves on, but what if we really, really need the user to enter a name before proceeding? Is there a way of "sending" the user back to the prompt so they can repeat the input? This can we done with loops, and in particular with a statement called while.

function Program() {
    var name = "";
    input: while(1) {
        name = prompt("What is your name?")
        if (name != "") break input
    }
    console.log("Hello")
    console.log(name)
}

This works by creating a loop using while. This loop is called input. When the input is empty, we continue the loop. Otherwise we break the loop. The while is followed by a 1 to tell the computer to loop indefinitely, until we tell it to stop with break.

Since we rarely want loop to go on indefinitely, the 1 following the while can be substituted with a condition. This explains the name: while a condition holds, the loop will continue. We can take advantage of that and simplify the code.

function Program() {
    var name = ""
    while(name == "") {
        name = prompt("What is your name?")
    }
    console.log("Hello")
    console.log(name)
}

We can now apply this technique to the Apollo 11 program, changing this version

function Program() {
    console.log("ignition sequence start")
    var countdown = 6
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    countdown = countdown - 1
    console.log(countdown)
    console.log("All engines running")
}

into this, much shorter, one

function Program() {
    console.log("ignition sequence start")
    var countdown = 6
    while (countdown >= 0) {
        console.log(countdown)
        countdown = countdown - 1
    }
    console.log("All engines running")
}

Great!

output 1

This concludes this mini series on getting started in programming. Let's recap what we learnt:

  • programs are sequences of instructions or commands
  • variables are boxes that contain values so the computer can remember it
  • indirection allows us to refer to a variable instead of its value
  • conditionals are commands that allow the computer to chose different sequences of instructions based on a condition
  • loops are sequences of instructions which are repeated until a condition is met, or until we explicitly break out

These very few concepts are the basis of all programming. Once you master them you can literally write any program possible—it's mathematically proven!


Hi, I'm Marco Cecconi. I am the founder of Intelligent Hack, developer, hacker, blogger, conference lecturer. Bio: ex Stack Overflow core team, ex Toptal EM.

Read more

Newest Posts

What can Stack Overflow learn from ChatGPT?

Stack Overflow could benefit from adopting a using conversational AI to provide specific answers

Read more
Fan mail

Multiple people with my name use my email address and I can read their email, chaos ensues!

Read more
Intelligent Trip

After years of building, our top-notch consultancy to help start-ups and scale-ups create great, scalable products, I think it is high time I added an update to how it is going and what's next for us.

Read more
Guest blog: Building, in partnership with communities by Shog9

A lesson in building communities by Stack Overflow's most prominent community manager emeritus, Shog9

Read more
Can you migrate a company from on-premise to remote-only?

Some lessons learned over the past 8 years of remote work in some of the best remote companies on the planet

Read more

Gleanings

How Aristotle Created the Computer
Chris Dixon • Mar 20, 2017

What began, in Boole’s words, with an investigation “concerning the nature and constitution of the human mind,” could result in the creation of new minds—artificial minds—that might someday match or even exceed our own.

Read more…