add isUndefined checking
re-factorize code