JavaScript ternary operator example with functions Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JavaScript ternary operator example with functions without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am using jQuery 1.7.1

I am just starting to use the JavaScript ternary operator to replace simple if/else statements. I have done so successfully in several places. I was surprised when I successfully made something else work when I thought for sure it wouldn’t, but I tried anyway.

Here’s the original statement:

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    if (IsChecked == true){
        removeItem($this);
    } else {
        addItem($this);
    }
}

Here’s the same function using the ternary operator:

function updateItem() {
    $this = $(this);
    var IsChecked = $this.hasClass("IsChecked");
    (IsChecked == true) ? removeItem($this) : addItem($this);
}

I was surprised because all of the examples I saw being used were merely setting variables like this:

x = (1 < 2) ? true : false;

My question is whether this is “normal” use and will it work in most versions of JavaScript? Where will it fail? Are there other less obvious uses for it?

UPDATE — Thanks for the “real world” advice!!!

I am using this as my function:

function updateItem() {
    $this = $(this);
    $this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}

Answer

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best…

x = (1 < 2) ? true : false;

The use of ternary here is totally unnecessary – you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It’s a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

We are here to answer your question about JavaScript ternary operator example with functions - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji