1

I am using the ternary operator as my if else condition. However, I am getting the not defined error using it. Here's my sample code below.

let a = 'apple'

let res = b ? b : a
console.log(res)

From what I know it will check the variable b if it has value and since it is not defined it should go to else and display the word apple?

But using the code above gives b is not defined error.

3
  • 1
    Hi Marie, I believe this answer may also help: stackoverflow.com/questions/48659442/… Basically, I understand that a ternary operator takes three arguments. The first one (1st) is the condition, the second one (2nd) is executed if the condition is true, and the third one (3rd) is executed if the condition is false. Here, you don't have any condition set. Commented Dec 21, 2020 at 12:48
  • yes, thanks. how do I upvote your answer? Commented Dec 21, 2020 at 12:48
  • It is clear for me me now. I am expecting it to be just undefined but its not just that it is undeclared. Commented Dec 21, 2020 at 12:51

1 Answer 1

3

You have to at least define the variable b in order to use it like that.

Something as simple as this would fix your issue:

    let a = 'apple'
    let b
    let res = b ? b : a
    console.log(res)

Or you could also do something like this to check if the variable is undefined:

        let a = 'apple'
      
        let res = typeof(b) !== 'undefined' ? b : a
        console.log(res)

I don't know your full use case to provide a better context.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I think that is the case I am expecting it to be undefined but it is undeclared in the first place.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.