Home > Blockchain >  Why does return statement in this function throws an error?
Why does return statement in this function throws an error?

Time:08-18

I have a function that tests if the passed value is an object. If the passed value is an object, I want to console.log the value. Else, I want to return false. However, I got an syntax error stating that invalid return statement is used in the console. Here is the code:

function a(value){
  typeof value === 'object'?console.log(value):return false;
}
a({});

Any help will be apreciated.

CodePudding user response:

Statement cannot be used as an expression

return is a statement

?: requires an expression

function a(value){
  return typeof value === 'object' ? console.log(value) : false;
}
a({});

CodePudding user response:

This is an inappropriate use of the conditional operator. Use it when you're selecting different values, not actions. Choose between statements with if.

function a(value) {
    if (typeof value == 'object') {
        console.log(value);
    } else {
        return false;
    }
}

console.log() doesn't return a value, so there's little point in using it in a conditional operator.

  • Related