SaaS Developer   
   About    Testimonials    Contact   

If (if-else loop is shorter) {...

It turns out that it’s not only just architects who love minimalism, but JavaScript developers do too. :)

John Pawson Interior

Check out another, shorter, way of writing the if-else loop. It’s really useful to have a short loop that can be easily understood in just one line:

(if condition is true) ? this happens : else;

Sweet! Let’s eat some apples! First, here’s an example of some classic If-Else syntax:

var oneApple = {
    color: 'red',
    status: 100

function bite(apple) {
    if (apple.color === 'red') {
        apple.status = apple.status - 25;
        alert ('There is only '+apple.status+' % of apple available now.');
    } else {
        alert ('Apple is still ripening.')


Now, let’s write If-Else using a new, shorter method:

var anotherApple = {
    color: 'yellow',
    status: 0

function check(apple) {
    return (apple.status === 0) ? alert ('There is only stub left...') : alert ('There is still '+apple.status+'% of apple available.');


You can try both of these functions live at JSFiddle, or below by clicking ‘Result:

comments powered by Disqus