Scope.
As Danny has already mentioned, its better to use collection variables to avoid scope issues.
Once youâve reduced your array using shift(). You need to re-save the array.
Iâm surprised your case 1 actually works, as the variable you set using pm.variables.set() will not be available to request 2.
Let me show you an example of scope issues.
Request 1. (Just so I have an array to work with).
let toolIds = ["123", "456", "789"]
pm.collectionVariables.set("toolIds", toolIds);
console.log(pm.collectionVariables.get("toolIds")); // ["123", "456", "789"]
Request 2. All code in pre-request script.
let toolIds = pm.collectionVariables.get("toolIds");
console.log(toolIds); // ["123", "456", "789"]
pm.collectionVariables.set('currentToolId', toolIds.shift());
console.log(toolIds); // ["456", "789"]
console.log(pm.collectionVariables.get("toolIds")); // ["123", "456", "789"]
console.log(pm.collectionVariables.get("currentToolId")); // "123"
The following is what is actually returned in the console logs.
The console log for the collection variable toolIds is only showing two elements when it should be showing all three still.
This is due to having toolIds set at the collection and local level.
If you move the last two console logs to the tests tab, then it works correctly as the local variable for toolIds no longer exists after the pre-request script has completed. Itâs not available to the tests tab.
It is better to use different variable names for the collection variables and the local variables that you use temporarily.
It is more code, but it removes any potential scope issues.
let array = pm.collectionVariables.get("toolIds");
console.log(array); // ["123", "456", "789"]
let currentToolId = array.shift();
console.log(currentToolId); // "123"
console.log(array); // ["456", "789"]
pm.collectionVariables.set("toolId", currentToolId);
pm.collectionVariables.set("toolIds", array);
console.log(pm.collectionVariables.get("toolIds")); // ["456", "789"]
console.log(pm.collectionVariables.get("toolId")); // "123"