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?

//the function:
var isValid = value => typeof value !== 'undefined' && value ? true : false;

How to Works:

var isValid = value => typeof value !== 'undefined' && value ? true : false;

var is_exists = 1;

console.log('//normal expression test with existing variable:');
console.log(typeof is_exists !== 'undefined' && is_exists ? true : false);

console.log('//normal expression test with nonexistent variable:');
console.log(typeof is_noexists !== 'undefined' && is_noexists ? true : false);

console.log('//arrow function test with existing variable:');
console.log(isValid(is_exists));

console.log('//arrow function test with noexisting variable:');
console.log(isValid(is_noexists));

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:

const obj = {
  value1: 'foo
};

// dynamically added property:
obj.value2 = 'bar';

// ...

console.log(Boolean(obj.value1));
console.log(Boolean(obj.value2));

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