Skip to content
Advertisement

have a solution for (typeof !== ‘undefined’) in functions?

I want to create a arrow function to check my vars or values, but I don’t know how to resolve this. In normal expression(out the function) it’s works, but in a function the value is checked before the condition and returns a error. Have a way to ignore or remove this error similar to ‘@’ in PHP?

JavaScript

How to Works:

JavaScript

NOTE: The condition can be reduced to typeof value !== 'undefined' && !!value

Advertisement

Answer

For the general case, it’s not possible, at least not in any reasonable way.

When you pass an argument to a function, the interpreter must be able to extract the value that the argument contains at that point, before anything inside the function runs. If someVar has never been defined, you cannot reference it unless you do a typeof check first. So, the logic you’re trying to implement is not possible to abstract into a separate function; you must check that the variable is defined at the call site, before each function call.

That said, this is a weird problem to have. Dynamic variable names are quite strange and should be avoided in most cases. If you find yourself having to do something like this, consider if it would be at all possible to structure your data differently, such as putting the possibly-existing values into a single object instead, eg:

JavaScript

This way, even if the properties inside obj can vary dynamically, the only variable name – the obj – remains constant. This pattern is much easier to manage.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement