0

I have recently started learning Javascript and want to understand how functions declared inside an object work. i have defined a function inside an object and just logged a message "Function functionName is called" inside it. When i call the function the console logs the message but along with it "undefined" also gets printed on the subsequent line. i understand that my function doesn't return anything and hence by default javascript returns undefined. But i need to know is there a way to write functions that return nothing similar to void functions() in java?

Here's my code -

const circle = {
    radius : 5,
    location : {
        x: 10,
        y : 1
    },
    isVisible : true,
    draw : function(functionName){
        console.log('Function '+functionName+' is called. ');
    }
};

console.log(circle.isVisible);              // true
console.log(circle.radius);                 //  5
console.log(circle.location);               // { x: 1, y: 1 }
console.log(circle.location.x);             // 10      
console.log(circle.draw('draw'));
Sid_83
  • 21
  • 2
  • 2
    This is how JS is designed - there's no "non-existent" values, only `undefined`. – iBug Mar 19 '21 at 06:54
  • Every expression results in a value. If there’s no value, then it’s `undefined`. Why do you *need* something else? – deceze Mar 19 '21 at 06:57
  • 1
    "*But i need to know is there a way to write functions that return nothing similar to void functions() in java?*" note that in Java *the compiler* will stop you from capturing the return of `void`. There is usually enough information at compile time to determine if the result *should* be used (it's non-void) or not (is void). Wrong code just fails to compile. In JS you often don't have this information ahead of time. Therefore, this is unenforceable - you just have code that calls an unknown function. You're just not comparing Java and JavaScript equally - the situations are different. – VLAZ Mar 19 '21 at 07:05
  • I figured out what i needed to know. Actually the fact that i am calling the draw() inside console.log() is the reason it returns undefined. Anyway Thank you all ! – Sid_83 Mar 19 '21 at 11:10

0 Answers0