0

for example, I have code like this:

var test = function() {
   return Math.random();
}

var randomNumber = test();


// I want to call test() via the randomNumber variable, 
// use this variable on another function or etc...
// for example here
for (var i = 0; i < 5; i++) {
   console.log(randomNumber); // and it should be show 4 random numbers
}

Is this possible?
Thanks to advance.

5
  • do you mean to use a variable when calling a function? like randomNumber = test(); console.log(randomNumber); ? Commented Dec 12, 2017 at 23:46
  • I guess you might want to create a so-called "getter". To do so, have a look at Object.defineProperty Commented Dec 12, 2017 at 23:47
  • I have updated question. Commented Dec 12, 2017 at 23:49
  • Now I have just 1 number, which was generated when I create a randomNumber variable. Commented Dec 12, 2017 at 23:50
  • If you want a new random number in each iteration just call the function - ... console.log(test()); Commented Dec 12, 2017 at 23:51

2 Answers 2

2

I believe you want to assign the function reference to randomNumber instead of calling the function and assigning its return value.

var test = function() {
   return Math.random();
}

// Assign test to randomNumber, but don't call it here
var randomNumber = test;

for (var i = 0; i < 5; i++) {
   console.log(randomNumber()); // call it here
}

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

Comments

0

You could assign the value returned by the function to the variable inside the loop and then display it.

Kinda like the code below

// define function
var test = function() {
  return Math.random();
}

// define variable
var randomNumber;

// loop
for (var i = 0; i < 5; i++) {
  // invoke function, assign value to variable
  randomNumber = test();

  // output it to console.
  console.log(randomNumber);
}

UPDATE

If you do not want to write code to 'loop' thru your array, you can use a fake array and map the same function to it.

You are not looping thru it yourself but looping thru the array is being performed nonetheless.

// array of fake values
var iterations = [0, 1, 2, 3, 4];

// returns an array of random numbers
console.log(iterations.map(function(elem) {
  return Math.random();
}));

3 Comments

yes this way works already, but I wanna find a way without simple loop (if it possible of course)
@ArikDonowan I am not sure I understand what you mean by without simple loop - can you explain?
Perhaps better questions for you are: what are you trying to achieve? and why are you trying to avoid a loop?

Your Answer

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