Home > Enterprise >  Different variable values assigned conditionally
Different variable values assigned conditionally

Time:05-16

I have a result coming from an AJAX call which I would like to test: in case it's equals to 'nobody' then I want a variable people assigned to 'No people', otherwise I want to output whatever I get.

This is my code:

const result = JSON.parse(oReq.responseText);
for (var dinner of result) {
    if (dinner.diners.name != 'nobody')) {
    const res = dinner.diners.name.map(diner => {
    return obj.person
    })
    let people = res.join('<br/>* ')
    }
    [...]
    let output = dinner.diners.name == 'nobody' ? 'No-one' : people

Why am I always getting people is not defined, even when dinner.diners.name == 'nobody'?

CodePudding user response:

It's time to get a better JS development environment set up! A linter should be able to detect the fact that the variable people does not exist in the scope you're trying to access it in.

The assignment keywords let and const are block scoped (whatever is wrapped in curly braces). That means that the variable is only available within the block and blocks within it. To fix this, declare people in the right scope: outside of the for..of loop.

const result = JSON.parse(oReq.responseText);
let people
for (var dinner of result) {
    if (dinner.diners.name != 'nobody')) {
        const res = dinner.diners.name.map(diner => {
            return obj.person
        })
        people = res.join('<br/>* ')
    }
}
let output = dinner.diners.name == 'nobody' ? 'No-one' : people

Notice that I took out the let assignment of people inside the loop. If you assign it there, then people in the loop is different from the people above the loop

  • Related