First steps in programming: conditionals

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.


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

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
Announcing Intelligent Cache, our caching library

Our newest open source initiative, intelligent cache, is available for use

Read more
Guest Blog: The mythical 10x programmer by Antirez

In this post, Salvatore Sanfilippo puts together a list of qualities that I believe make the most difference in programmers’ productivity.

Read more
Team EMEA

Today I want to introduce our second engineering team: Team EMEA

Read more
Guest Blog: Technology and Storytelling by Orf Quarenghi

LEGO star-ships aren't made to collect dust on a shelf, but to explore strange new worlds

Read more

Gleanings

And the Most Realistic Developer in Fiction is...
Julia Silge • Mar 28, 2017

We can say that Mr. Robot is having a moment. The main character was one of the top choices and thus is perhaps the most/least realistic/annoying/inspiring portrayal of what it’s like to be a computer programmer today.

Read more…