Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it legal to have expressions not assigned to values in Javascript functions?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading