Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Viola Chyu
Viola Chyu
6,432 Points

Why is 'id' passed into templateData?

Elementary question but I just can't figure out why is id variable passed in templateData, according to the exercise in this video (#Express Basics #Parameters #Randomize Cards):

router.get('/:id', (req, res) => {
    const { side } = req.query; //variable holding side property
    const { id } = req.params; //variable holding id property
    const text = cards[id][side]; //access to pieces of text we want ot use
    const { hint } = cards[id];

    const templateData = { id, text }; //pass in id

    if (side === 'question') {
        templateData.hint = hint;
        templateData.sideToShow = 'answer'; //URL: side=answer
        templateData.sideToShowDisplay = 'Answer';  //webpage display: Answer
    } else if (side==='answer'){
        templateData.sideToShow = 'question';  //URL: side=question
        templateData.sideToShowDisplay = 'Question'; //webpage display: Question
    }

    res.render('card', templateData);
})

The way I comprehend is that templateData is an Object(locals) that will be rendered in the webpage, so :

  1. ID is a variable, why can it be passed into an object? (I thought it's only for key:value pairs?)
  2. while passing in ID, should templateData also take in the variable "sideToShow" and "sideToShowDisplay" since they are both appearing in pug?

I'm always frustrated when watching Chalkley's videos-- he just don't elaborate enough! Can someone kindly explain how this works? Thanks in advance.

1 Answer

Blake Larson
Blake Larson
13,014 Points

In es6 this

const templateData = { id, text }; 

is shorthand for

const templateData = { id: id, text: text };

The answer to the second question is you are already doing that in the conditional blocks when you check the side variable.

If side is question you are also sending a hint along.

templateData.hint = hint;

So that templateData object is being populated throughout this express route.