Let or const with use of if statement

Which is the better method of writing JavaScript functions? 1st one uses let variable and 2nd uses a const variable.

let isRadioOn;
 if (global.get("radios").length !== 0) {
    isRadioOn = 1
 }else  
   isRadioOn = 0;

or

const isRadioOn = function() { 
   if (global.get("radios").length !== 0) {
    return 1;
 }else  
   return 0;
 }

Thanks in advance...

Honestly, if your not going to alter the value of isRadioOn after it's been evaluated,
I would go with the function method - I don't think there is much of a difference

BONUS - this is my preference so is neither right or wrong, but I tend to use arrow functions, especially if dealing with outer context

const isRadioOn = () => {
 if (global.get("radios").length !== 0) {
    return 1;
 } else {
    return 0;
}

However!
You might need to consider if using the value multiple times in your code block - therefore another run off the function methods, might yield an updated output

What about something like:

const isRadioOn = global.get("radios").length !== 0

Executed only once in the function node which is the more common use-case and returns true or false.

If you really want a numeric return:

const isRadioOn = global.get("radios").length !== 0 ? 1 : 0;
1 Like

I like it. I just learned about ternary operators but the trick is know when to use it... Appreciate the schooling..

I also wanted to add that I was familiar with

const isRadioOn = global.get("radios").length !== 0

and it produces a Boolean value. However the course I am taking the instructor advised they never used. That is why I did not use it.

Regards

2 Likes

I generally don't use it if the ternary version is longer than a standard if :slight_smile:

There is an occasional exception though. When wanting to use a const assignment, you can't do that inside an if block if you want the const outside the block. So if you don't want to use let instead, then a ternary is still useful.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.