JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Linking Around the Application

Casey Dixon
Casey Dixon
8,920 Points

Scope 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.