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

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

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…