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

181
Views
"this" isn't working as I expected using string concatenation in Javascript

const user1 = {
    name: 'Sherlock Holmes',
    address:{
        street:'Baker street',
        number:"221B",
    },
    sayMyAddress:function (){
        console.log(`My address is ${this.address}`)
        console.log(this.address)
    }

}

user1.sayMyAddress()

The result:

My address is [object Object]

{ street: 'Baker street', number: '221B' }

Why the this keyword shows the address value in the second case and doesn't in the first? the scope in this case isn't in the object user?

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

0

The result of the conversion of the address to a string is '[object Object]' as we'd expect. For example, if you do

console.log({}.toString()) 

you'll get an output of:

[object Object]

A small change in the code will give the desired result:

const user1 = {
  name: 'Sherlock Holmes',
  address: {
    street: 'Baker street',
    number: "221B",
  },
  sayMyAddress: function() {
    console.log(`My address is ${this.address.number} ${this.address.street}`)
  }

}

user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }

You could also add a toString() function on the address object:

const user1 = {
  name: 'Sherlock Holmes',
  address: {
    street: 'Baker street',
    number: "221B",
    toString() { return `${this.number} ${this.street}` }
  },
  sayMyAddress: function() {
    console.log(`My address is ${this.address}`)
  }

}

user1.sayMyAddress()
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report

0

this.address is an object, so even if the console.log is sympatic enough to output the full object with values if you pass it the object directly, if you use it in a string you'll get [object Object].

Just try it like this

console.log(`My address is ${this.address.street} ${this.address.number}`)
about 4 years ago · Juan Pablo Isaza Report

0

You are trying to log the object itself. So the output result is pretty much expected.

Change the log line from:

console.log(`My address is ${this.address}`)

to:

console.log(`My address is ${this.address.street} ${this.address.number}`)
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!