refactor and handle undefined