"To Be or Not to Be" about variables in JavaScript -


just doing little introduction javascript. i'm used more testing existence of pointers in c++ not crash.

never did read hamlet, read this page null , undefined in javascript.

and in nutshell can:

if (varname == null) if (varname === null) if (typeof(varname) != 'undefined')  if (varname != undefined) if ('varname' in object)  if (object.hasownproperty('varname'))  

honestly little me :). classical way in javascript testing variables avoid crashes?

because of errors thrown reading undeclared globals, checking variable best done using third example, typeof example.

if (varname == null) 

will tell whether value defined , nullish , throw error if undeclared.

if (varname === null) 

will tell if value defined , null , throw error if undeclared.

if (typeof(varname) != 'undefined') 

will tell if variable defined or not without throwing error.

if (varname != undefined) 

is opposite of first.

if ('varname' in object) 

will tell if object has property either in or somewhere along prototype chain. not guaranteed work host objects.

if (object.hasownproperty('varname')) 

will tell if object has own property, ignoring prototype chain. break if property named 'hasownproperty' has been set.

if (object.hasownproperty.call(object, 'varname')) 

is more reliable version of last.


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -