dreamsys software

JavaScript Shell Scripting Tutorial

Looping


While Loop

The while statement is used when you want to loop while a statement is true. This is the same in many other programming and scripting languages. The body of the loop is contained within curly braces, same as in the if/else condition. Suppose that we have an array of items and we want to remove the first item then print the list. Now suppose we want to do this continually until the list is empty. We can use the while loop for this:

#!/usr/bin/env node

var list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

while(list.length > 0) {
        list.splice(0, 1);
        console.log(list);
}

This code will remove the element at index 0 and then print the contents of the list, it will continually do that while the length of the list is greater than zero.

To loop forever in your script, you can put the number 1 or true in your while statement condition. Let's write a simple program that will print out how long it has been running until the user presses Ctrl+C to terminate the program.

#!/usr/bin/env node

var counter = 0;

while(true) {
        console.log(counter);
        counter++;
}

This program will loop until the user presses Ctrl+C. The counter variable is updated using the ++ operator, which will increment the variable by 1.

For Loop

The for loop is used when you want to loop through a list of items or between a range of numbers. The body of the loop works the same as it does in a while loop. Let's say that we want to write a program that will validate numbers in a given list. These numbers can be loaded from a file, hard coded, or manually entered by the user. For our example, we will ask the user for a list of numbers separated with spaces. We will validate each number and make sure that it is between 1 and 100. The best way to write a program like this would be to use a for loop.

#!/usr/bin/env node

console.log('enter a list of number between 1 and 100, separated by space');

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
        var input = chunk.trim().split(" ");

        for (index in input) {
                var n = input[index];

                if (isNaN(n)) {
                        console.log(n + ' is not a number!');
                } else if (n < 1) {
                        console.log(n + ' is less than 1!');
                } else if (n > 100) {
                        console.log(n + ' is greater than 100!');
                } else {
                        console.log(n + ' is valid!');
                }
        }

        process.exit();
});

If you enter the text "5 2 7 0 100 101 1 45 a b c", the function String.split will convert this into an array by taking each item separated by a space and converting it into a new array element. Next the for loop will loop through each index of the array and put the index value in the "index" variable we created. To access a given number in the list, we create a new variable "n" and assign it the value input[index].

Now that we have the n object, first we need to make sure that it's a number, we can do this with the isNaN (is Not a Number) function. If it is not a number, it will return true, then we will print out the validation error. If it is a number, then the else if conditions will continue, the next condition checks to see if the number is less than 1, if so it prints the error. Next it checks for greater than 100 and prints an error. If all checks pass, the else block is called, printing the valid number message. Here is an example run:

Enter a list of numbers between 1 and 100, separated by spaces: 5 2 7 0 100 101 1 45 a b c
5 is valid!
2 is valid!
7 is valid!
0 is less than 1!
100 is valid!
101 is greater than 100!
1 is valid!
45 is valid!
a is not a number!
b is not a number!
c is not a number!

There is an alternate way to write this for loop, you can also loop while a variable is less than a value. In the below example the for loop has 3 sections separated by semicolon. The first section is called only once before the loop. The second section is a check that will tell the loop to stop if the check fails (returns false). The third section is called at the end of each loop. So in this example we start with index at a value of 0 then loop while index is less than the length of the input array and after each loop we increment the value of index.

#!/usr/bin/env node

console.log('enter a list of number between 1 and 100, separated by space');

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
        var input = chunk.trim().split(" ");

        for (var index = 0; index < input.length; index++) {
                var n = input[index];

                if (isNaN(n)) {
                        console.log(n + ' is not a number!');
                } else if (n < 1) {
                        console.log(n + ' is less than 1');
                } else if (n > 100) {
                        console.log(n + ' is greater than 100');
                } else {
                        console.log(n + ' is valid!');
                }
        }

        process.exit();
});

When your scripts start to get large or repetitive, it's time to start learning about functions, which are described in the next section.

Prev (If/Else) | Next (Functions)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6