0

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;

}


function curveScore(original, curveAmount) {
  return original + curveAmount;
}

//Generate a random array
const testScores = Array.from({
  length: 20
}, () => getRandomIntInclusive(60, 100));
console.log(testScores);

// Updated testScores with curved scores
testScores.forEach((el, i, curvedScores) => {
  curvedScores[i] = curveScore(el, 10);
});
console.log(testScores);

So, everything works fine here. Essentially, a random array of 'test scores' is generated, and those scores are logged, then 'curved' by 10 points, and then logged again.

The interesting thing is that the first time I open this in the browser, I don't get the proper results. The same Array is displayed 2x (no 10 points added).

Once I refresh browser, then I get the correct output.

Why? I guess somehow console.log() is firing 2x before forEach() is finished? Would this require a Promise or something to display the proper results consistently?

Ele
  • 33,468
  • 7
  • 37
  • 75
CodeFinity
  • 1,142
  • 2
  • 19
  • 19
  • Seeing expected results here, what environment are you using? – Behrooz Mar 27 '18 at 02:44
  • You code is working as expected if i understand correctly. Run the above snippet. Two arrays will be printed in logs and 2nd array's each element is increased by 10. This is what you wanted. Right? – Vikasdeep Singh Mar 27 '18 at 02:45
  • 3
    You are running into [this problem](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays). The object is referenced, not the values, and updates live. If you want to retain the original array, I recommend you print some stringified version of it. – Alexander Nied Mar 27 '18 at 02:46
  • Yes...except, every time I open index.html with this file in Dev Tools, the **first time,** it shows the same array (no increase by 10). **Only after refreshing browser does it show the updated Array 2nd time!** @VicJordan – CodeFinity Mar 27 '18 at 02:47
  • That is strange... however, nothing about your code is inherently asynchronous, so Promises are probably not your answer here. Nor is any of your code interacting with the DOM in any way, so I _doubt_ you'd need to rely on any sort of "document ready" type hooks/events... but I wouldn't call it impossible. What browser? – Alexander Nied Mar 27 '18 at 02:49
  • @AlexanderNied Yes, that's it! So, this is not actually a coding bug, but a 'dev tools' bug! Ugh! Always something. Coding sux! *LOL* JK – CodeFinity Mar 27 '18 at 02:49
  • 1
    Consider using `map` function instead of `forEach`. – Behrooz Mar 27 '18 at 02:53

2 Answers2

0

The interesting thing is that the first time I open this in the browser, I don't get the proper results. The same Array is displayed 2x (no 10 points added).

Once I refresh browser, then I get the correct output.

Chrome logs, roughly speaking, references.

With the console tools closed (does not matter if first time opening the page or not[1]), chrome doesn't actually log the array, it just sort of records it did. When you open the dev tools, it prints the current version of the reference twice.

If the dev tools are open, on the other hand, the logging actually happens at every call, which is why you see the two versions of the array.

To work around this issue, just actually print the contents of the array. For instance, calling JSON.stringify:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;

}


function curveScore(original, curveAmount) {
  return original + curveAmount;
}

//Generate a random array
const testScores = Array.from({
  length: 20
}, () => getRandomIntInclusive(60, 100));
console.log(JSON.stringify(testScores));

// Updated testScores with curved scores
testScores.forEach((el, i, curvedScores) => {
  curvedScores[i] = curveScore(el, 10);
});
console.log(JSON.stringify(testScores));

[1]: Just close dev tools, hit refresh and open it again, you'll see the problem (the same array printed twice) happens still.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • Rite. That's pretty annoying - I see it as a 'dev tools' bug more than a coding bug. However, I am going to rework this for the class that I teach using ```map()``` as per comment above. That's probably better solution anyway, and will see if that also solves this other 'bug.' – CodeFinity Mar 27 '18 at 10:44
  • Yes, sure thing, do use `.map()`, it will generate a new array, thus a different reference, and there won't be room for this problem to appear. My answer was more an attempt to explain the issue (since the core of the question was "why?), but the `.map` is a good way out! – acdcjunior Mar 27 '18 at 11:18
0

There are below two options:

  1. Using Jquery

    $(document).ready(function() {
      // you code here
    });
    
  2. Pure JavaScript

    window.onload = function() {
     // Your code here
    }
    
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104