Specify & Ideate

Hi Guys,

So I’m going back over some Javascript fundamentals because I feel like I’m not grasping the specify, ideate, and implement principles right.

I find myself sticking to my favorite operators/methods.

For instance,

I love the ternary operator…so I used that.
Example:

inRange(x, y, z){
z === undefined ? [z, y] = [y , 0] : z;
y > z ? [y , z] = [z, y]: y;
let isInRange = y <= x && x < z ? true : false;
return isInRange;
};

Besides the “if” conditional statement, are there any other ways to implement this method?

I would love some of the insight on how to improve on specifying functionality and ideate game plans.

1 Like

Hello, @glennlaw.

Not sure you’re gaining anything by using the ternary expressions. They are shorthand for if ... else. What you really have are 2 if's. There is no true else. There’s also no possible need to swap y & z if z was originally undefined, so a if ... else if approach saves testing an impossible condition every time the method is called. You could do that with a ternary expression, but again, you have no actual else logic to implement if neither of the conditions is true.

Lastly, there’s no real need to define a variable if all we need to do is return its value. We can simply return the value:

return y <= x && x < z
A take on using ternary expression with an `else if` condition:
  inRange(x, y, z) {
    z === undefined ?
    [z, y] = [y , 0] : 
    y > z ?
    [y , z] = [z, y] :
    null; //this could be any value since it isn't used for anything
    return y <= x && x < z;
  },
//since it's a ternary expression we have to have an else, but we don't need one
//which is why an if..else if might be more efficient and appropriate
1 Like

@glennlaw, here’s another way using a ternary expression:

  inRange(x, y, z) {
    return z && x >= Math.min(y, z) && x < Math.max(y, z) ? true : !z && x >= 0 && x < y ? true : false
  },

Here’s a version using only one if statement, and a default return:

 inRange(num, sVal, eVal) {
    if(!eVal) {return num >= 0 && num < sVal};
    return num >= Math.min(sVal, eVal) && num < Math.max(sVal, eVal);
  },
2 Likes

Thanks for breaking this down for me. So the main area I comprehended was that an if…statement would be appropriate for this scenario since we don’t need an else statement.

I think that’s where I realized that I wasn’t sure if I was using ternary right.

After all, I thought shorthand would make it easier for me to read but I believe

inRange(num, sVal, eVal) {
if(!eVal) {return num >= 0 && num < sVal};
return num >= Math.min(sVal, eVal) && num < Math.max(sVal, eVal);
},

Thanks for your insights. I still have a lot more learning to do.

1 Like