Code Snippets #5 – This introduces you to the for() statement

posted in: Software Testing | 0

Sometimes, when we are looking at our returned response, we have more than one possible answer and as such, we need to look through all of the possibilities to find our matches. This is where the for() statement comes in handy. There are other statements to achieve this, but for now, let’s look at this one.

The basic syntax is

for (statement 1; statement 2; statement 3)
code to be executed which for the purpose of this snippet will involve an if() statement.

A typical for statement would look like this:

for (var i=0; i < 10; i++)

{do some thing here and loop}


Let’s say our response has a surname field and we want to find nicoll. We will search all of the returned response for the text “nicoll” and when we have found it, we will stop looking (this is where the break comes in.)

var data = JSON.parse(responseBody)

for(var i =0; i< data.length; i++) {
var surname = data[i].surname;

if (surname === "nicoll") {
console.log("Has Found");


You could include another if statement outside of the final brace to add a response if nicoll was not found. 

console.log("the Surname "Nicoll" was not found);



Leave a Reply