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

115
Views
Set Trap execute for two times - JS Proxy

Im working with proxies in js, but something is weird =>

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.count(); //this execute for two times!
    if(typeof val === 'string') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

The Set trap should call only once when i push to the array, but it executed twice.

And there is an error in the console, when i push to array =>

Uncaught TypeError: proxy set handler returned false for property '"length"'

How can i fix this and what's wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Calling Array#push causes set to be called two times:

  1. target=[], prop=0, val=Manuel: Adds a new value to an index
  2. target=["Manuel"], prop=length, val=1: Updates length of array

In your case, the second call is returning false since the length value is numeric.

A possible solution:

let _usernames = [];

_usernames = new Proxy(_usernames, {
  set(target, prop, val) {
    console.log(target, prop, val);
    if(typeof val === 'string' || prop === 'length') {
      target[prop] = val;
      return true;
    } else {
      return false;
    }
  }
});

_usernames.push('Manuel');

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!