Hello fast question, its possible to use if inside var?
I want to do:
when x field is empty do this, and if not do this. I need to run the same IF multiple times so I want to use some kind of var reference and use it for all the cases.
No i was referring to @m3g4p0p 's answer (which is the right answer) var mysupervar = input.value === '' ? something : somethingElse
vs var mysupervar = (input.value === '') ? something : somethingElse
well youāre defining a variable. so there will ALWAYS be āsomethingElseā. You can hand it null if you want, but the variable has to be assigned SOMETHING.
Incidentally, convention would be to define the test the other way around in this case, because the āelseā is the optional part.
var mysupervar = (input.value !== "") ? input.value : null;
1: Youāre actually assigning ānothingā as SOMETHING. Specifically, an empty object.
An empty object is still an Object. You can do things like {}.hasOwnProperty("a") and get a sensible value out. You can assign things to properties of an empty object. nothing.athing = "wark" still works.
2: Youāre doing the negative as the actual result. Consider how you would revert this back to ifā¦thenā¦else. What youāve tried to write is:
else(input.value === "") { var mysupervar = something; }
Which makes no sense because thereās no if.
If you wanted to write it in full form, youād have to write:
if (input.value !== "") { var mysupervar = something; }
I should use IF/else to try to do something only when the input.value is not empty? I donāt need to do anything if its empty, just run something when itās not.
Maybe thereās a better expression to do that? Thanks for your great information.
No, if is the appropriate way of checking if (see how the language construct came to be?) the value is empty.
Perhaps its easier to see what i mean if I write it out in sentence form.
āI want to check if the input value is empty; if it is, do nothing, if it isnt, do somethingā
You can say the same thing, but easier, by simply saying:
āI want to check if the input value is not empty; if it is, do somethingā
Both sentences mean the same thing.
In programming speak, those two sentences are expressed in long form as:
if (input.value === "") { }
else { something; }
vs
if(input.value !== "") { something; }
or in ternary form, where they are almost identical: (input.value === "") ? null : something;
vs (input.value !== "") ? something : null;