Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Is there a better way of duplicating elements? Reply To: Is there a better way of duplicating elements?

#190547
GSutherland
Participant

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:

http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized-which-method-is-b

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();
}