Patty C.
Patty C.

Reputation: 31

Having a hard time making function inside of an object show in the console log

I'm new to JS so apologies for this possibly stupid question. I'm learning about object constructor syntax but I'm confused about why the console log won't show the result of a function that is part of that object. Here is the code:

var sportsCar = {
    name: "Lamborghini",
    color: "red",
    horsepower: "100mph",
    electric: true, 
    showModelName: function() {
      return(this.name);
      console.log(this.name);
    }
  };

The result after inputting this object into the developer tool was blank when I thought it would say "Lamborghini." I thought about putting the console.log(showModelName) outside of the object but remembered the function is not globally scoped. Can anyone explain why the console log doesn't show the name?

Upvotes: 3

Views: 35

Answers (4)

essleeung
essleeung

Reputation: 11

  1. your function hasn't been invoked, so nothing will be returned. Adding the following line will invoke the function.

sportsCar.showModelName()

  1. As mentioned by some people above, the return statement ends the function execution. Take a look at the MDN page for more clarification.

If you change the order of the return statement and console log, this is what you would get:

Option 1 (returns Lamborghini and ends function):

showModelName: function() {
      return(this.name);
      console.log(this.name);
    }

Option 2 (returns Lamborghini 2 times):

showModelName: function() {
      console.log(this.name);
      return(this.name);
    }

Upvotes: 1

dave
dave

Reputation: 64657

Not sure exactly what you are trying to do, but it seems like there are two issues, first because you return before you log it, and because you still need to use this.showModelName, not just showModelName

return(this.name); // nothing after this line will run
console.log(showModelName);

var sportsCar = {
    name: "Lamborghini",
    color: "red",
    horsepower: "100mph",
    electric: true, 
    showModelName: function() {
      console.log(this.showModelName);
      return(this.name);
    }
  };
  
  console.log(sportsCar.showModelName())

Upvotes: 3

Hyetigran
Hyetigran

Reputation: 1215

Your console.log needs to be above the return statement. Anything below the return statement will be ignored.

Also, the main reason why you aren't seeing the statement is because you defined a function. But it doesn't look like you've invoked it.

try running sportsCar.showModelName() below the sportsCar object

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4562

This is the correct syntax

var sportsCar = {
    name: "Lamborghini",
    color: "red",
    horsepower: "100mph",
    electric: true, 
    showModelName: function() {
      console.log(this.name);
    }
  };

sportsCar.showModelName();

Upvotes: 1

Related Questions