Javascript : lesson 7 nested objects


#1

Regarding this lesson: https://www.codecademy.com/courses/introduction-to-javascript/lessons/objects/exercises/nested-objects?action=resume_content_item

I’m working on question 1. I defined an object literal that I named ‘capFave’. In order to get the value ‘cookies’ from another object literal, I used a function.

const capFave = {
  favFood () {
    return spaceship.crew.captain['favorite foods'][0]
    // not correct i'm pretty sure
  }
}

when I console.log it:

console.log(capFave.favFood); 

I expected ‘cookies’ instead I get “[Function: favFood]”.

There is no review video on this exercise. Any insight would be greatly appreciated.


#2

calling functions requires parentheses, if you exclude the parentheses you literally get the function object ([Function: favFood])


#3

Thank you for taking the time to try and help me. I wasn’t sure what you meant about “requires parentheses” or where to put them. I changed my code to:

let capFave = {
  capFavFood: spaceship.crew.captain['favorite foods'][0]
}
console.log(capFave);

it seems to work. The response is :

{ capFavFood: 'cookies' }

#4

general syntax of calling a method:

object.methodName(arguments)

see the parentheses? Of course, if your method doesn’t have parameters, no arguments are required


#5

When written in such a way it is referred to as a callback.

var func = capFave.favFood;

We can now invoke this function from within another function, say, or from wherever it is declared.

console.log(func())    //  ‘cookies’

#6

Thank you. I understand about the parentheses. I think I was just way off in my original attempt.