0

Can anyone explain why this is not working:

var todayDate = new Date();
var todayYear = todayDate.getFullYear();

var User = {
  firstName: "John",
  lastName: "Doe",
  email: "email@email.com",
  dob: new Date(85, 1, 1),
  userBirthYear: dob.getFullYear(),
  age: todayYear - userBirthYear,
  url: "http://www.google.com",
  bio: "I love pizza",
  interests: ["food", "NBA", "movies"]
}

The userBirthYear doesn't seem to be initializing. If I move the userBirthYear outside the object as a separate variable, it works fine.

1 Answers1

1

dob isn't a variable, it is a property of the User object.

But you can't directly access object properties until that whole object has been compiled

You could do it this way;

var User = {
  firstName: "John",
  lastName: "Doe",
  email: "email@email.com",
  dob: new Date(85, 1, 1), 
  age: todayYear - userBirthYear,
  url: "http://www.google.com",
  bio: "I love pizza",
  interests: ["food", "NBA", "movies"]
}
// User object now exists, modify it any way you need
 User.userBirthYear = User.dob.getFullYear();
charlietfl
  • 170,828
  • 13
  • 121
  • 150