Not understanding how scopes work
A difficult concept for beginners to understand is JavaScript’s scoping rules and closures. Functions retain visibility to variables in their parent scopes. But because we are delaying the execution with a setTimeout, when the time comes for the functions to actually run, the loop has already finished and the I variable is incremented to 6. The self-executing function in the comment works because it copies the I variable by value and keeps a private copy for each timeout function.
Example:
javascript
// Output will be 6 for (let i = 0; i < 5; i++){ setTimeout( function (){ console.log(i+1); }, 100*i); } |
JavaScript Common Mistakes
JavaScript is an easy language to get started with, but achieving mastery takes a lot of effort, time, and patience. Beginners often make a few well-known mistakes.
In this article, we’ll cover some of the most common learning mistakes people make and find out how to overcome them. Many of these tips will be applicable outside of JavaScript or even web development.
Contact Us