getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
178.28k stars 33.43k forks source link

A question about syntax for defining functions inside an object #1654

Closed hatemhosny closed 4 years ago

hatemhosny commented 4 years ago

Please type "I already searched for this issue": I already searched for this issue

Edition: (1st or 2nd) 2nd

Book Title: Get Started

Chapter: Chapter 2: Surveying JS

Section Title: Functions https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch2.md#functions

Question:

first, I want to thank you for the great books and courses. I learnt a lot!

My question is about this code you included in the "Functions" section:

var whatToSay = {
    greeting() {
        console.log("Hello!");
    },
    question() {
        console.log("What's your name?");
    },
    answer() {
        console.log("My name is Kyle.");
    }
};

whatToSay.greeting();
// Hello!

I'm not familiar with this syntax for defining functions. There is no function keyword and no arrows.

I know these:

var whatToSay = {
    greeting: function() {
        console.log("Hello!");
    },
    question: () => {
        console.log("What's your name?");
    }
};

I also know about shortcuts like that

function greeting() {
        console.log("Hello!");
}
var whatToSay = {
        greeting
};

but in the syntax you used, how do we say that we are defining a function? I have tested your code and indeed it works perfectly fine. Would you please explain that a bit?

I notice that the syntax is similar to defining methods in a class. Is that related?

Thank you

again, very grateful for all what I learnt from your teaching πŸ™

Hatem

getify commented 4 years ago

I notice that the syntax is similar to defining methods in a class. Is that related?

Yep, when class was added to ES6, they added "concise methods" (the syntax you're referring to) to object literals to keep parity. It's essentially the method form of "concise propeties", which is the "shortcut" you illustrated.

hatemhosny commented 4 years ago

Thank you. That's clear now πŸ‘