Home › Forums › JavaScript › Is there a better way of duplicating elements? › Reply To: Is there a better way of duplicating elements?
It can be tricky to know what method to use when checking for whether a variable exists. Check out this stackoverflow link where people smarter than me can’t agree on the best method:
The problem with checking against undefined is that undefined is mutable for whatever reason. Also, you can define a variable with the value of undefined, so… yeah. Not as reliable as it should be.
Just checking like this:
if (batman) { }
won’t account for booleans that are false or anything that has a converted value of 0 and you’ll get an uncaught referenceerror.
It generally depends on the application, but since I try to always know what type my variables are going to be I often just check whether typeof equals what I expect. This is pretty good to do, for instance, with functions if you’re working in a big modular code base that you aren’t in total control of.
if (typeof someFunction === ‘function’) {
someFunction();
}