0

I've created an object using object literal notation and in it I have a couple of methods that I've logged to the console to make sure they are working. Each method shows in my console. But right after each method is logged, 'undefined' is returned and I cannot figure out why.

I have searched questions related to object literal notation but have not seen anything that pertains to this specific issue.

I've even gone through the MDN for working with objects. Something tells me it's probably a simple mistake. Does anyone have any suggestions?

Here is the code I'm using:

var car = {
    name: 'Magic',
    make: 'Nissan',
    model: 'Sentra',
    mileage: 79000,
    year: 2002,
    owned: true,
    start: function() {
        console.log('Car is turned on!');

    },
    off: function() {
        console.log('This car has not been turned on. Do you have the key?');
    }

};

console.log(car);
console.log(car.start());
console.log(car.off());
  • [This perhaps?](https://stackoverflow.com/questions/14633968/chrome-firefox-console-log-always-appends-a-line-saying-undefined) – SuperPrograman Aug 15 '18 at 22:19
  • Thanks, I read the post just now and I see I'm actually running this code from a js file which would mean undefined should not append if I'm understanding correctly. Perhaps it's b/c javascript is a dynamically typed programming language as another user suggested? – Quintessa Anderson Aug 15 '18 at 22:32

2 Answers2

1

By passing car.start() to console.log you are logging the return value of car.start, which is implicitly undefined. To fix, just change your code to just call the methods on the object, which are already logging to the console.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Brett Peters
  • 141
  • 3
1

When you execute car.start() it will print your string to the console and console.log() will return undefined. When you wrap it in another console.log() call, it will print the string and the returned value (e.g., undefined).

You can simply call the methods directly like this:

console.log(car);
car.start();
car.off();
Antonio Cangiano
  • 776
  • 6
  • 10
  • Thanks! That's exactly how I have mine now and it works. – Quintessa Anderson Aug 15 '18 at 22:56
  • Great. :) A couple of cool tips: 1) In ES6 you can replace `start: function()` with the more concise `start()` if you wish; 2) Try `console.table(car)` to see a neat presentation of your object's properties and values. – Antonio Cangiano Aug 15 '18 at 23:03
  • 1
    Wow, thanks for the tips! I must admit, I'm excited to use the new ES6 feature and the console.table(car) method is actually really nice - very neat and easy to read. Thanks! – Quintessa Anderson Aug 16 '18 at 03:41