-2

the full code is in the link I am to trying declare an arrow function by assigning it to the variable randomColor using the array.push() method, but I am getting the error "randomColor is not defined" when I run the code. Please help.

function generateRandomColors(num){
 let arr = [];
 for(let i=0;i < num;i++){
     arr.push(randomColor());
 }
 return arr;
}

let randomColor = () => {
    //random for red
    let r = Math.floor(Math.random() * 256);
    //random for blue
    let g = Math.floor(Math.random() * 256);
    //random for green
    let b = Math.floor(Math.random() * 256);
    //return rgb
    return "rgb(" + r + ", " + g + ", " + b +")";
};
nishant
  • 117
  • 3
  • 13
  • 1
    I'm not getting an error with the code you've given – VLAZ Oct 14 '18 at 18:50
  • 1
    Please post your *full* code, including the invocation of `generateRandomColors`, so that the problem can be reproduced – CertainPerformance Oct 14 '18 at 18:51
  • Hello , have shared the drive link for the full code ,but in the code have used var instead of let , https://drive.google.com/open?id=1ZPqm5xZ95cnwsCeF6_QqhRWNlBomtNud – nishant Oct 15 '18 at 05:17

1 Answers1

0

When you use let (e.g. let randomColor), the variable you declare isn't usable before its declaration. So if you try calling generateRandomColors before your let randomColor = ... declaration, you'll find that generateRandomColors isn't yet defined.

See especially the Temporal Dead Zone for let and const:

Temporal Dead Zone

let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

If that doesn't solve your problem, can you share the code where you try calling generateRandomColors?

Nicholas Barry
  • 558
  • 2
  • 5
  • 15