Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does return statement in this function throws an error?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading