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.

  • 1
    Hi Marie, I believe this answer may also help: https://stackoverflow.com/questions/48659442/how-to-check-undefined-variable-in-a-ternary-operator 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. – GuiFalourd Dec 21 '20 at 12:48
  • yes, thanks. how do I upvote your answer? – Marie Biscuits Dec 21 '20 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. – Marie Biscuits Dec 21 '20 at 12:51

1 Answers1

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.

maxshuty
  • 9,708
  • 13
  • 64
  • 77