0

my JavaScript object has an array in it but when I try to return an element of the array I get the function as a string instead of the value of the array element.

My code is

  function Car(make, model){
    this.make = make;
    this.model = model;
    this.dimensions = [4, 3, 1.8];
    this.carLength = function(){ return this.dimensions[0]; };
  }

  var c = new Car("Ford", "Escort");

  alert(c.make);
  alert(c.model);
  alert(c.dimensions[0]);
  alert(c.carLength);

The first 3 alerts show the data expected, ("Ford", "Escort" and 4), the forth one displays the following output

function(){ return this.dimensions[0]; }

Why is the function being listed and not executed?

2
  • 3
    CarInstance.carLength is a method. You have to call it, or you'll just get the function. console.log(c.carLength()) Commented Sep 1, 2020 at 0:45
  • 3
    Because this is a function, to execute use () at the end. Example: alert(c.carLength()) Commented Sep 1, 2020 at 0:45

1 Answer 1

1

You need to include parentheses to execute the function.

alert(c.carLength());

If you don't include the parentheses, then you are just passing a reference to the function into the alert function as a variable. Then alert will execute toString() on that variable.

When you include the parentheses, you are passing the value that is returned from executing the function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.