0

I've a function inside an object. When I console.log the function variable, it's showing the name of function as an empty object instead of the data returned from the function.

Here's My JavaScript Code

var Obj = {
    x: function() {
        return 'Hello World';
    }
}

var data = new Obj.x();
console.log(data);

Current Output

x {  }

Expected Output

Hello World
  • 3
    Remove the `new`, otherwise you're treating `x: function() {}` as a constructor function which will always return an object – Nick Parsons Mar 25 '23 at 05:40

1 Answers1

0

To call a function, do not use new

Just call it with ().

var Obj = {
  x: function() {
    return 'Hello World';
  }
}

var data = Obj.x();
console.log(data);

@Nick Parsons has given a great explanation - thanks

When you use new, you are forcing Javascript to create an Object.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26