2

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...

4
  • 1
    stackoverflow.com/questions/3127429/… Commented Mar 31, 2018 at 0: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. Commented Mar 31, 2018 at 0:03
  • You're using this outside an object method. Commented Mar 31, 2018 at 0:03
  • 2
    It should be employee["Full Name"](). Commented Mar 31, 2018 at 0:04

3 Answers 3

5

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"]())

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I'm currently learning JavaScript and your remarks with those problems are very helpful. Thank you.
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

2 Comments

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 ?
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.
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"]());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.