Home > Software engineering >  Javascript: conditional variable initialization in if/else
Javascript: conditional variable initialization in if/else

Time:08-27

I'm initializing a variable conditionally with if/else. I want to follow functional programming rules.

My eg.:

  if (1 === 2) {
    const a = false;
  } else {
    const a = true;
  }

  console.log(a);

Linter say: ESLint: 'a' is not defined.(no-undef).

As you know there is no way that a would not be defined. Another approach could be:

const a = 1 === 2 ? false : true;

But what if there were three conditions in if/else? How do I achieve that and avoid error?

CodePudding user response:

That's why I always use var. But for your example you can have define const a using a function or a intermediate variable.

const a = init_a()

function init_a() {
  if (1 == 2) {
    return 1;
  } else {
    return 2;
  }
}

console.log(a)

CodePudding user response:

You need to define your variable in a scope that you can access and print.

You can use something more elegant like this:

const a = (1 ==2) ? 'A' : 'B'
console.log(a)

For more info check What is the scope of variables in JavaScript?

CodePudding user response:

you need initialize it out of the if scope.

const a = true;
if (1 === 2) {
 const a = false;
}
console.log(a);
  • Related