ovidnine
ovidnine

Reputation: 55

Javascript - Basic if/else statement

I'm just learning JS and am confused as to why this if/else statement isn't going to the "else."

If you put in Monty or Chip, you get prompted for the password, if you put in Frank (or anything else) you STILL get prompted for the password, though it does say wrong login or password.

What am I missing to make it go to the "else" if you put in "Frank" or whatever as the login?

var password
var login = prompt('Enter your login.');


if (login === 'Monty' || 'Chip') {
    password = prompt('Enter your password.');
  if (login === 'Monty' && password === 'Cheese') {
    alert('Access Granted Monty');
  } else if (login === 'Chip' && password === 'Gadget') {
    alert('Access Granted Chip');
  } else {
    alert('Wrong login or password!');
  }
} else {
  alert('Wrong login!')
}

Upvotes: 0

Views: 163

Answers (3)

ezpn
ezpn

Reputation: 1748

In the line:

if (login === 'Monty' || 'Chip') {

What actually happens is:

  • comparison of variable login and string 'Monty'
    • if this is true parser enters an if statement
    • otherwise parser converts string 'Chip' to boolean. Because it isn't an empty string, this will always result in true.

You can read more about boolean conversions here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

To fix this try:

if (login === 'Monty' || login === 'Chip') {

This code will compare both strings with login variable before entering an if statment.

Upvotes: 3

kemiller2002
kemiller2002

Reputation: 115488

JavaScript is weird beast in some respects:

This:

if(login === 'Monty' || 'Chip')  

is really doing

login === 'Monty' || 'Chip' is not null or undefined

In JavaScript there is a concept of truthy, which is if a value can be converted into a truthful statement, then it is true. if('Chip') {alert('HI');} would always execute, because the constant 'Chip' will never be null or undefined. In other languages that are stricter about conditionals this wouldn't be allowed, but in JavaScript this is considered correct syntax and is therefore evaluated.

What you want to do is: login === 'Monty' || login === 'Chip'

Upvotes: 3

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

There is a small error in your code. You need to update your if statement

from

if (login === 'Monty' || 'Chip') {

to

if (login === 'Monty' || login === 'Chip') {

Upvotes: 7

Related Questions