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 trialCasey Dixon
8,920 PointsScope and template data
Are you able to pass a variable from outside the scope of a router function, such as a global variable, into a route's template data? Or must the variable come from within the scope of the route function?
router.get('/:id', (req, res) => {
const { side } = req.query;
const { id } = req.params;
const text = cards[id][side];
const { hint } = cards[id];
const numberOfCards = cards.length;
const randomId = Math.floor(Math.random() * numberOfCards);
const templateData = { text, id, randomId };
This works, where the randomId is declared in the scope of the function, but when it is declared outside of the function it does not work:
const numberOfCards = cards.length;
const randomId = Math.floor(Math.random() * numberOfCards);
router.get('/:id', (req, res) => {
const { side } = req.query;
const { id } = req.params;
const text = cards[id][side];
const { hint } = cards[id];
const templateData = { text, id, randomId };
I know functions have access to variables outside their scope, but I'm wondering if there is an issue with passing that global variable into a route's template data.