newman newman - 2 months ago 8
Javascript Question

Shorthand if statement always returns 'false' instead of value assigned

I am trying to use the shorthand if statement in Javascript to find out if one of my arguments is a negative number, and if it is, I want to change it to a specific value. Here is my code:

var findDigit = function(num, nth){
nth = nth < 0 ? nth === -1: nth;

I am trying to ask is if nth is less than 0, then change nth to -1, if it is not less than 0, do nothing, or keep nth the way that it is. When I console log the nth argument, I get 'false'.

I have run into this issue other times too. So I guess what I'm asking is, how do you write a shorthand if-statement without an 'else' section? I have a block of code I want it to run if the if-statement is true, but if it's false I don't want it to do anything. Thanks!


Because of your if-statement: nth < 0 the following code gets executed: nth === -1 which is a check (including the type) if nth is exactly -1. Just omit this part and print

var findDigit = function(num, nth){
  nth = nth < 0 ? -1: nth;