Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Add a Final Else Clause

Mathias Nicolajsen
Mathias Nicolajsen
3,042 Points

2 variables in a if or else

I don't know how I add 2 variables to the if or the else (or else if) Could anyone pls help me?

script.js
var isAdmin = false;
var isStudent = false;

if ( isAdmin ) {
    alert('Welcome administrator');
} else if (isStudent) {
    alert('Welcome student');
} else (isAdmin + isStudent = false) {
  alert("Who are you?");
}
index.html
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JavaScript Basics</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
Mathias Nicolajsen
Mathias Nicolajsen
3,042 Points

I want to point out that the normal javascript code was

var isAdmin = false; var isStudent = false;

if ( isAdmin ) { alert('Welcome administrator'); } else if (isStudent) { alert('Welcome student'); }

2 Answers

You don't have to add anything (i.e. any condition) to the else clause (in fact, you cannot) - reaching the else clause implicitly means in this case that isStudent and isAdmin are both false, since you've already checked them in the if and else if branches above. An else clause is the very last (optional) element in a conditional structure, and simply means what should the program do if every other branch were evaluated to false.

... else {
  alert("Who are you?");
}

Note: technically you could write this code in the way like below (but don't do it, ever) :) This is something like you originally tried to do. Beware: a simple equal sign means assignment, i.e. assigning a value to a variable. Checking for equality is achieved by triple equals: === (this is a Javascript speciality, in other languages it is usually a double equal sign). And if you want to check if multiple statements are true at the same time, then you use the logical operator AND (&&).

if ( isAdmin ) {
    alert('Welcome administrator');
} else if (isStudent) {
    alert('Welcome student');
} else if (isAdmin === false && isStudent === false) {
    alert("Who are you?");
}
Mathias Nicolajsen
Mathias Nicolajsen
3,042 Points

Wait I have found out, I was doing it wrong :D