Search code examples
javascriptshorthandshorthand-if

javascript shorthand if the else callback


the long hand if in javascript would look:

function somefunction(param){

    if(typeof(param) != 'undefined'){
           var somevar = param;
         } else {

           alert('ERROR: missing parameter in somefunction. Check your form'); 
           return;

         }

}

AND MY SHORT HAND VERSION IS:

function somefunction(param){

    param = typeof(param) != 'undefined' ? param : function(){alert('ERROR: missing parameter in somefunction. Check your form'); return;}

}

BUT it does not work.

How could I?

Thank you


Solution

  • You are only declaring the function. you have to execute it. Add () next to the definition ..

    function somefunction(param){
        param = typeof(param) != 'undefined' ?
                    param :
                    function() {
                        alert('ERROR: missing parameter in somefunction. Check your form'); 
                        return false;
                    }();
    }
    

    EDIT: The above is not functionally equivalent to the original as the function itself doesn't return anything and doesn't end the function execution.

    function somefunction(param) {
        if (typeof(param) == 'undefined') {
            alert('ERROR: missing parameter in somefunction. Check your form'); 
            return false;
        }
    
        // Use param
    }