JavaScript For/of Loop

avatar


image.png

Image Source

JavaScript has a new different kind of loop apart from other programming language which is For/of loop. It uses the keyword for but is different than the regular for loop that we use. It is one of the new feature introduced in JavaScript ES6, which was one of the major milestone in the enhancement of JavaScript introducing programmers to many new cool features and making JavaScript more alive than ever. The for/of loop is used to iterate over the iterable objects. These objects are the one which contain sequence of elements or data like arrays, strings(it is usually a set of characters) and so on. The syntax of for/of loop is:

for ( var variable_name of iterable)
{
 //Body of loop.
}

You can use let and const instead of var keyword. The variable_name can be anything and iterable is the name of iterable objects that you define. Since, I haven't reached myself on array topics in JS, I would like to run the example of this loop on strings. We will use this loop to print each character of string in uppercase.

<!DOCTYPE html>
<html lang="en">
<head>
<title>For/of Loop</title>
<script>

    var prog_language = "javascript";

    for(var characters of prog_language)
    {
        document.write(characters.toUpperCase() + "<br>");
    }

</script>
</head>
<body>
</body>
</html>

The output as seen on the browser is as below:

image.png



0
0
0.000
0 comments