dcp3450
dcp3450

Reputation: 11187

Can you run part of an if statement conditionally?

Let's say I have this if statement:

if (
  username === firstname &&
  password !== fakePassword &&
  givenname === lastname

) {
  console.log(`Hi ${firstname}`)
}

Now I want to make the given name required if it's longer than 3 characters:

const givennameRequired = givenname.length > 3;

can I alter the if statement in a way that says "If the givennameRequired variable is true then worry about this part"

This way the console logs against two params or three depending on the validity of givennameRequired. Obviously I'm trying to avoid using an if/else and having two console logs

In a rough "sudo-code" way (I know this isn't valid):

if (
  username === firstname &&
  password !== fakePassword &&
  (
    if (givennameRequired) {
      givenname === lastname
    } else {
      return true;
    }
  )
) {
  console.log(`Hi ${firstname}`)
}

Basically, if the length is greater than three evaluate givenname === lastname otherwise, return true and don't worry about it.

Upvotes: 0

Views: 56

Answers (3)

Andrew Daly
Andrew Daly

Reputation: 537

This can be easily achieved with an if statement

if (givenname.length > 3){
    //do something
}
else {
//do something else
}

Upvotes: 0

FunkyMonk91
FunkyMonk91

Reputation: 1481

Trying to keep in line with your syntax. Something like this should work. For your own sanity I'd consider nesting the if statements so you can provide more accurate feedback to the user.

if (username === firstname && password !== fakePassword && (givennamerequired == true && givenname === lastname && givenname.length() > 3))

) {
  console.log(`Hi ${firstname}`)
}

Upvotes: -1

cybersam
cybersam

Reputation: 66967

This may do what you want:

if (
  username === firstname &&
  password !== fakePassword &&
  (givenname.length <= 3 || givenname === lastname)

) {
  console.log(`Hi ${firstname}`)
}

The if condition only bothers to check givenname === lastname if givenname.length > 3

Upvotes: 4

Related Questions