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 and know how to use variables

We ended the last instalment with a program that remembers the user's name and greets them.

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

You might have noticed that if we just press "OK" without a name, the program will output a blank line instead of the name. This is a usually not desirable, and we might want to make the computer react differently in that case. For example we can make it say "Hello stranger" if a name is not provided. We will use two new commands, if and else that tell the computer what to do in a specific case or otherwise. They are called conditionals.

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

Now, try this out and try both a real name and just clicking "OK". In the former case you will see the old behavior and in the latter, "Hello stranger" will be printed instead.

output 1

That's it! Now you know how to make your programs even smarter!

Let me leave you with an epic use of conditionals, can you imagine how this clip would work behind the scenes?

In the next instalment we will look at how to repeat execution with loops and make our Apollo 11 countdown program much shorter.


A software engineer & Stack Overflow alumnus in London. I write about software development, coding, architecture and team leadership. I also speak at conferences worldwide.

About me

Follow me on Twitter

Gleanings

hackurls - news for hackers and programmers
Claudio Santini • Mar 27, 2017

$ wget -O - hackurls.com/ascii | less

Read more…