Variable scope and precedence help you understand where your variables live and which value is used when multiple variables have the same name.
Variable scope and precedence in Postman
pm.variables.get('variableName') pm.environment.get('variableName') pm.collectionVariables.get('variableName') pm.globals.get('variableName')
Postman variables have scopes: local (pm.variables), environment, collection, and global.
When resolving a variable with {{variableName}}, Postman checks scopes in this order: local → environment → collection → global.
pm.variables.set('userId', '123') console.log(pm.variables.get('userId'))
pm.environment.set('userId', '456') console.log(pm.environment.get('userId'))
pm.collectionVariables.set('userId', '789') console.log(pm.collectionVariables.get('userId'))
pm.globals.set('userId', '000') console.log(pm.globals.get('userId'))
This script sets a variable named 'var' in all scopes with different values. When we get 'var' using pm.variables.get(), it returns the local scope value because local has the highest precedence.
// Set variables in different scopes pm.globals.set('var', 'global') pm.collectionVariables.set('var', 'collection') pm.environment.set('var', 'environment') pm.variables.set('var', 'local') // Get variable without specifying scope console.log(pm.variables.get('var'))
Local variables exist only during the request or script execution.
Environment variables change when you switch environments in Postman.
Collection and global variables persist until you change or delete them.
Postman variables have scopes: local, environment, collection, and global.
When accessing a variable, Postman uses the value from the highest precedence scope available.
Understanding scope helps avoid confusion and bugs in your tests.