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

132
Views
print foo by modifying the below piece of code

Without hardcoding the string, 'foo', how can i modify the code above so that it prints out 'foo 1', 'foo 2', and 'foo 3' each on separate lines.

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(this.x, num);
    });
  }
}

obj.f();

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

0

Classic "function" declarations will bind to the caller's "this" environment instead of how most languages do it. Traditionally, this can be fixed with the bind method on a function as follows:

const obj = {
     x: 'foo',
      f: function() {
          [1, 2, 3].forEach(function(num) {
              console.log(this.x, num);
          }.bind(this))
        }
    };

The simpler approach is to just use the new arrow syntax, which will bind the function as you would naturally expect.

This line:

[1, 2, 3].forEach(function(num) {

To this:

[1, 2, 3].forEach((num)=> {
about 4 years ago · Juan Pablo Isaza Report

0

const obj = {
  x: 'foo',
  f: function() {
    [1, 2, 3].forEach(function(num) {
      console.log(`${obj.x} ${num}`);
    });
  }
}

obj.f();
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!