Home > front end >  Is it possible to use ternary operator for console.log?
Is it possible to use ternary operator for console.log?

Time:10-30

I thought this would be something simple to do, but I don't think it's possible, why is that?

This is what I'm trying to do.

console.log("hello") ? bool : "";

This gives me an error: Expected an assignment or function call and instead saw an expression. Not sure exactly what that means.

CodePudding user response:

From my understanding, you want to "conditionally" console.log via the tenery operator.

It is possible to conditionally (via ternary) change the output of console.log() based on a bool like so:

console.log(bool ? "hello" : "")

In this case though, it will output an empty string to the console.

My guess is that you only want to log if the bool is true. It's quite trivial to add a quick if statement:

if (bool) console.log('hello')

Via Ternary, if you ultimately wish to do this, you'd need to do something like the following:

bool ? console.log("test") : null;

In my opinion, this looks less cleaner than a simple bool statement as you'd need to provide some value (Simplest probably being null or 0) which is then assigned to nothing.

CodePudding user response:

Yes. you have to evaluate the expression at runtime. Do I like this.

const someBool = true;
console.log(someBool?'hello':'goodbye');
  • Related