JavaScript

JavaScript if/else Statements

I am still learning JavaScript. Last month I received a Grow with Google Challenge Scholarship. The course starts with the basics and HTML and CSS then ends with JavaScript. There is a ton of support from other students on the course Slack group and forum.

I started the JavaScript lessons last week. I am working on JavaScript conditionals. Conditionals regulate the way JavaScript performs.

One type of conditional is the if statement. The statement runs if the condition in parenthesis is true.

if (/* this expression is true */) {
// run this code
} else {
// run this code instead
}

You can do more with the if statement when adding an else statement. Else allows another block of code to run when the if conditional does not happen.

An else if statement adds yet another conditional with its own block of code.

 

var musicians = 5;
if (musicians <= 0) {
console.log(“not a group”);
} else if (musicians === 1) {
console.log(“solo”);
} else if (musicians === 2) {
console.log(“duet”);
} else if (musicians === 3) {
console.log(“trio”);
} else if (musicians === 4) {
console.log(“quartet”);
} else if (musicians > 4) {
console.log(“this is a large group”);
}

var room = “ballroom”;
var suspect = “Mr. Parkes”;

var weapon = “”;
var solved = false;

if (room === “ballroom”) {
weapon = “poison”;
suspect === “Mr. Kalehoff”;
solved = true;
} else if (room === “dining room”) {
weapon = “knife”;
suspect === “Mr. Parkes”;
solved = true;
} else if (room === “gallery”) {
weapon = “trophy”;
suspect === “Ms. Van Cleve”;
solved = true;
} else {
(room === “billiards room”);
weapon = “pool stick”;
suspect === “Mrs. Sparr”;
solved = true;
}

if (solved) {
console.log(suspect + ” did it in the ” + room + ” with the ” + weapon + “!”);
}

Leave a Reply