1

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?

Pszemko
  • 95
  • 2
  • 7
  • 2
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Konrad Aug 26 '22 at 17:10
  • so what? this demonstrates that the scope of your 2 const cannot be accessed outside of your if – Mister Jojo Aug 26 '22 at 17:13
  • @KonradLinkowski probably, so if/else is a block scope and only there I can use a. What's the best solution then with three conditions? – Pszemko Aug 26 '22 at 17:19
  • What are you using this variable for? It would be easier to understand with context. – Konrad Aug 26 '22 at 17:25
  • Let's say I want to pass it as a function parameter: `doStuff(a);` – Pszemko Aug 26 '22 at 17:27

3 Answers3

1

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)
IT goldman
  • 14,885
  • 2
  • 14
  • 28
0

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?

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • I wrote that in question. What if there are three conditions? No, I don't want nested ternary. – Pszemko Aug 26 '22 at 17:10
  • That depends on the situation, you can use object/switch case/break your code into functions so it will be more clean and wont have if and else's in one place. – Tamir Abutbul Aug 26 '22 at 17:11
0

You can use an IIFE (Immediately Invoked Function Expression) if you want to stick to functional programming style.

This is especially useful when dealing with multi-level if and switch statements:

const a = (() => {
    if (1 === 1) {
        return 'first'
    } else if (1 === 2) {
        return 'second'
    } else {
        return 'third'
    }
})()

// 'first'
console.log(a)
zabdalimov
  • 38
  • 7