Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
How to access a variable which is updated inside the function in outer scope in Cypress/Javascript?

Here is the problem statement. I am trying to find all items on a webpage and find the item with the minimum price using Cypress. The problem is, as long as I am inside the inner function, minPrice is correct. However when I try to print minPrice in the outer function, minPrice again gets assigned to it outer scope value. I am fairly new to JS, so looks like I am missing some basic JS concept here. I tried a lot of things like variable scoping, async/await (which cypress claims it doesnt need), but no success. Please help!

Below is the code.

getMinPrice(){
//Initialize to a very big number
  var minPrice = 10000;
 
  cy.get('.btn.btn-primary').each(function ($el, index,$list) {

    //For each element, do some parsing to get the price for the item
    var textToParse = $el.attr('onclick');
    var price = textToParse.slice(-4,-1);
    price = parseInt(price,10);
    
   //compare price with current MinPrice
   if (price < minPrice)
          minPrice = price; 
  });
 
  cy.log(minPrice); // Logs 10000 which is not what I am expecting
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It is because JS works asynchronously your log statement is running before the value of minPrice is updated. To make sure that the log has the updated minprice, we can use then to make sure the log statement is run only after each has finished executing.

cy.get('.btn.btn-primary')
  .each(function ($el, index, $list) {
    //For each element, do some parsing to get the price for the item
    var textToParse = $el.attr('onclick')
    var price = textToParse.slice(-4, -1)
    price = parseInt(price, 10)

    //compare price with current MinPrice
    if (price < minPrice) minPrice = price
  })
  .then(() => {
    cy.log(minPrice) //should have the updated value
  })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!