0

I have a function, which works fine with if/else, but not with ternary. Anyone knows the reason? Also, if anyone could tell me a way the make it look nicer I'd really appreciate it.

function print(){
    for (const book of myLibrary){
        let cover = document.createElement('div')
        cover.textContent =`title: ${book.title} 
                            author: ${book.author}
                            pages: ${book.pages}` 
        
        // this line: (book.finished) ? cover.classList.add('bookStyle') : cover.classList.add('bookStyle2');
        
        if (book.finished){
            cover.classList.add('bookStyle')
        }
        else{
            cover.classList.add('bookStyle2')
        }

        books.appendChild(cover)
    }
}
minho-sama
  • 27
  • 4
  • 1
    "_if anyone could tell me a way the make it look nicer_" I'd start by not using a ternary. It is generally used to return a value depending on a condition. You're not doing anything with the return value. IMO it only makes things harder to read. – Ivar Apr 03 '21 at 21:40
  • 3
    [Add semicolons after your statements](https://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript). Your `(book.finished)` is interpreted as if you try to invoke a function on the template literal before it. – Ivar Apr 03 '21 at 21:47
  • 4
    @Ivar The return value would be used if the ternary looked like `cover.classList.add(book.finished ? "bookStyle" : "bookStyle2")`. – Sebastian Simon Apr 03 '21 at 21:48
  • 1
    See [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283/4642212). – Sebastian Simon Apr 03 '21 at 21:50
  • This might work `((book.finished) ? cover.classList.add('bookStyle') : cover.classList.add('bookStyle2'))` –  Apr 05 '21 at 09:12

1 Answers1

1

Ternaries are great when they are used to return values, not perform or invoke actions.

Here is how I would improve your ternary.

// Old
this line: (book.finished) ? cover.classList.add('bookStyle') : cover.classList.add('bookStyle2');
// Prefered
cover.classList.add(book.finished ? 'bookStyle' : 'bookStyle2');
John Pavek
  • 2,165
  • 2
  • 14
  • 30