1

var employee = {
  ["Last Name"]: "Smith",
  ["First Name"]: "Josh",
  ["Full Name"]: function() {
    return this["First Name"] + this["Last Name"]
  }
};
document.write("Good day" + this["Full Name"])

I'm currently learning JavaScript and I wanted to create an object with properties in two words using the bracket notation, unfortunately it gives me a result of Good dayundefined instead of Good day Josh Smith. I don't know what supposed to be the problem of my code...

Barmar
  • 596,455
  • 48
  • 393
  • 495
Jake Go
  • 13
  • 3
  • 1
    https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Barmar Mar 31 '18 at 00:03
  • You'll need to invoke the function to get the result you want. You're just writing the function itself, not it's return value. So change to `document.write("Good day" + employee["Full Name"]())`, note the extra set of parens at the end. – CRice Mar 31 '18 at 00:03
  • You're using `this` outside an object method. – Barmar Mar 31 '18 at 00:03
  • 2
    It should be `employee["Full Name"]()`. – Barmar Mar 31 '18 at 00:04

3 Answers3

3

Two problems.

  1. You need to use employee["First Name"], not this["First Name"], since you're not inside an object method.
  2. You need to call the function with ().

var employee = {
  ["Last Name"]: "Smith",
  ["First Name"]: "Josh",
  ["Full Name"]: function() {
    return this["First Name"] + this["Last Name"]
  }
};
document.write("Good day" + employee["Full Name"]())
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • Thank you so much! I'm currently learning JavaScript and your remarks with those problems are very helpful. Thank you. – Jake Go Mar 31 '18 at 00:18
2

Convert "Full Name" to a getter, and refer to employee instead of this when you call it:

var employee = {
  "Last Name": "Smith",
  "First Name": "Josh",
  get "Full Name"() { // convert to getter
    return `${this["First Name"]} ${this["Last Name"]}`;
  }
};

document.write("Good day " + employee["Full Name"]) // refer to  employee instead of this
Ori Drori
  • 145,770
  • 24
  • 170
  • 162
  • Can you explain the reason behind wrapping `this["Last Name"]` and `this["First Name"]` inside the double bracket , knowing that it work fine without them ? – Abslen Char Mar 31 '18 at 00:08
  • You need to use the bracket notation to get the value. If you're talking about the curly brackets - this is an expression inside a [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). – Ori Drori Mar 31 '18 at 00:10
1

var employee = { 
  "Last Name":"Smith", 
  "First Name":"Josh",
  "Full Name": function() {
    return  this["First Name"] +" "+ this["Last Name"];
  }
};
document.write("Good day " + employee["Full Name"]());
Javier S
  • 329
  • 3
  • 10