Updated code to add a check of undefined