JavaScript loop an array - ReferenceError | i is not defined

Viewed 1150

newbie at JavaScript and Postman here.

I have set up a basic test in postman using JS to compare names in a web response to names in a data file. The array of names is in an external data csv file.

I want to loop through the array, but I get an error:

"ReferenceError | i is not defined"

Code:

var newResponse = responseBody;

let nameArray = data.name;

for (let i = 0; i < nameArray.length; i++) {
  console.log(nameArray.length);
}

pm.test("Web vs. Data: Person", function() {
  pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);
});

console.log(newResponse.Item[i].name);
console.log(nameArray.Item[i].person);
2 Answers

Your end scope "}" character missing please change with this code;

var newResponse = responseBody;

let nameArray = data.name;

for (let i = 0; i < nameArray.length; i++) {

    console.log(nameArray.length);

    pm.test("Web vs. Data: Person", function () {
        pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);

    });

    console.log(newResponse.Item[i].name);
    console.log(nameArray.Item[i].person);
}

let is block scoped so it will cause ReferenceError out of the for loop. The variable i will not be referred outside of the for loop. So you've to move your codeblock inside the for loop like below. Hope this helps :)

var newResponse = responseBody;
let nameArray = data.name;

for(let i = 0; i < nameArray.length; i++){
  console.log(nameArray.length);
  pm.test("Web vs. Data: Person" ,function(){
  pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);
  });

  console.log (newResponse.Item[i].name);
  console.log(nameArray.Item[i].person); 
}
Related