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

有帮助吗?

解决方案

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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top