0

I need to write a constructor for an object that gives a random value to the object's color property. This is what I wrote

var Ghost = function() {
  // your code goes here
  var num = Math.floor(Math.rand()*4);
  if(num === 0){
    this.color = "white";
  }
  else if(num === 1){
    this.color = "yellow";
  }
  else if(num === 2){
    this.color = "purple";
  }
  else if(num === 3){
    this.color = "red";
  }
};

I get an error message from the test suite on code wars

TypeError: Object #<Object> has no method 'rand'
   at new Ghost
        at Test.describe

Am I not allowed to use functions inside a constructor or is there something about the test suite I don't understand?

1
  • 3
    Do you mean Math.random()? There's no Math.rand() function. Commented Dec 6, 2014 at 4:12

1 Answer 1

3

The name of the function is Math.random, not Math.rand.

To interpret the error message:

TypeError: Object #<Object> has no method 'rand'

First try to find the object with the "rand" method you are trying to call. In this case, it is Math. Then verify that the object in question indeed has the method.


On an unrelated note, your selection code can be simplified to:

var COLOURS = ['white', 'yellow', 'purple', 'red'];
this.color = COLOURS[Math.floor(Math.random() * 4)];
Sign up to request clarification or add additional context in comments.

1 Comment

Even better to change the 4 to COLOURS.length.

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.