Hướng dẫn dùng r/loops JavaScript

Loops are handy, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

Instead of writing:

text += cars[0] + "
";
text += cars[1] + "
";
text += cars[2] + "
";
text += cars[3] + "
";
text += cars[4] + "
";
text += cars[5] + "
";

You can write:

for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "
";
}

Try it Yourself »


Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) {
  // code block to be executed
}

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed.

Example

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "
";
}

Try it Yourself »

From the example above, you can read:

Expression 1 sets a variable before the loop starts (let i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5).

Expression 3 increases a value (i++) each time the code block in the loop has been executed.



Expression 1

Normally you will use expression 1 to initialize the variable used in the loop (let i = 0).

This is not always the case. JavaScript doesn't care. Expression 1 is optional.

You can initiate many values in expression 1 (separated by comma):

Example

for (let i = 0, len = cars.length, text = ""; i < len; i++) {
  text += cars[i] + "
";
}

Try it Yourself »

And you can omit expression 1 (like when your values are set before the loop starts):

Example

let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
  text += cars[i] + "
";
}

Try it Yourself »

Expression 2

Often expression 2 is used to evaluate the condition of the initial variable.

This is not always the case. JavaScript doesn't care. Expression 2 is also optional.

If expression 2 returns true, the loop will start over again. If it returns false, the loop will end.

If you omit expression 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.


Expression 3

Often expression 3 increments the value of the initial variable.

This is not always the case. JavaScript doesn't care. Expression 3 is optional.

Expression 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.

Expression 3 can also be omitted (like when you increment your values inside the loop):

Example

let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
  text += cars[i] + "
";
  i++;
}

Try it Yourself »


Loop Scope

Using var in a loop:

Example

var i = 5;

for (var i = 0; i < 10; i++) {
  // some code
}

// Here i is 10

Try it Yourself »

Using let in a loop:

Example

let i = 5;

for (let i = 0; i < 10; i++) {
  // some code
}

// Here i is 5

Try it Yourself »

In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.

In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop.

When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

+ continue không có trong forEach, nhưng chúng ta có thể sự dụng return trong forEach để thay thế chúng.

ví dụ:

      var myArr = [1,2,3,4];
//return in forEach
myArr.forEach(function(elem){
if (elem === 3) {
return;
}

console.log(elem); //1,2,4
});
//continue in for
for(var i = 0; i < myArr.length; i++){
if (myArr[i] === 3) {
continue;
}

console.log(myArr[i]); //1,2,4
}

+ continue có thể thay thế nhưng break thì không. Bạn không có cách nào để dùng break trong forEach. 

+ scope index trong internal function. 

+ forEach nhìn code đẹp hơn kakaka, ai cũng đồng ý điều này.

 - Về performance thì chúng ta không cần bàn vì ai cũng biết forEach không có tuổi so với for. 


- Còn về scope thì chúng tôi sẽ nói rõ hơn về vấn đề này, vì điều này rất quan trọng, để dễ hình dung hơn chúng tôi sẽ lấy một ví dụ để các bạn hiểu hơn.

    var elements = ["element1", "element2", "element3"];
//và đây cũng chính là vì sao forEach lại ra đời.

elements.forEach(function(element) {
// The asynchronous action simulator
setTimeout(function() {
console.log(element);
}, 100);
});
//result: 
(index):39 element1
(index):39 element2
(index):39 element3

//và khi sử dụng for nguyên thủy =]

for (var i = 0; i < elements.length; i++) {
setTimeout(function() {
console.log(elements[i]);
}, 100);
}
//result: 
(index):39 undefined
(index):39 undefined
(index):39 undefined

Tại sao lại như vậy thì đó là do phạm vi của index hay nói chuyên nghiệp hơn là scope index. Thực chất khi dùng for thì index i vẫn không sai cho đến khi nhận ra giá trị i =3 cho nên mới print ra undefined.  Bạn nào chưa hiểu thì có thể đặt câu hỏi comment trong bài viết này nhé.