I'm sure this is a duplicate but I cannot find the original question, so please link to it if you know of it.
In Javascript I am currently writing a function and I am tempted to write it like this:
function toggleDropdown() {
isOpen() ? closeDropdown() : openDropdown();
}
However, this feels a bit strange, as the ternary operator is an expression, and neither closeDropdown
or openDropdown
return values (save for an implicit undefined), and I am not assigning the return value of the ternary to anything.
This I realized that Javascript seems to allow you to just arbitrarily calculate and have expressions not assigned to anything. For example, apparently this code below doesn't throw any errors:
function test() {
55;
"asdf";
let x = 12;
"qwer";
12;
}
Which seems kind of strange to me? I'm wondering, is this code "okay" to write? It doesn't seem to throw any errors, but I'm worried that it will break during some sort of compilation step with Babel or something, as this code seems a bit unorthodox. Or maybe it is completely supported?
Its all good. You do not have to do anything with the result of an expression.
It is really no different than calling a function that returns a value, and not assigning or using the value.
In the case of the primative values, they would most likely just get optimized out if you were optimizing your code.
With that said, you may have a linter that is configured to actually emit a warning or an error for an unassigned expression, so your valid syntax would be shown as an issue in that case.