February 23, 2017 by Marco Cecconi
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.
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 moreMarch 12, 2023 by Marco Cecconi
Stack Overflow could benefit from adopting a using conversational AI to provide specific answers
Read moreOctober 15, 2021 by Marco Cecconi
Multiple people with my name use my email address and I can read their email, chaos ensues!
Read moreSeptember 29, 2021 by Marco Cecconi
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 moreFebruary 03, 2021 by Marco Cecconi
A lesson in building communities by Stack Overflow's most prominent community manager emeritus, Shog9
Read moreDecember 02, 2020 by Marco Cecconi
Some lessons learned over the past 8 years of remote work in some of the best remote companies on the planet
Read more$ wget -O - hackurls.com/ascii | less
Read more…