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?

5
  • 2
    Does this answer your question? What is the scope of variables in JavaScript? Commented Aug 26, 2022 at 17:10
  • so what? this demonstrates that the scope of your 2 const cannot be accessed outside of your if Commented Aug 26, 2022 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? Commented Aug 26, 2022 at 17:19
  • What are you using this variable for? It would be easier to understand with context. Commented Aug 26, 2022 at 17:25
  • Let's say I want to pass it as a function parameter: doStuff(a); Commented Aug 26, 2022 at 17:27

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

var is very old-fashioned speaking euphemistically
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?

2 Comments

I wrote that in question. What if there are three conditions? No, I don't want nested ternary.
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.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.