A fruity way to remember Javascript’s not defined and undefined

Jason Sigmon
JSON’s Coding Adventures
2 min readJan 27, 2017

One day you go to grocery store and purchase three fruits: a banana, an apple, and a pear. Later that day, you decide you are going to eat the banana. Meanwhile, your roommate knew you were going shopping and also really wanted the banana. Unfortunately for him, the banana is already gone :(.

A few days later you suddenly have a craving for an orange. You think you bought one; so, you go to check where your fruits are stored. Much to your surprise, there is no orange. You go and check your receipt and you realize you never purchased an orange. Javascript essentially functions as your receipt. It will tell you if it has seen something before, or if what you are doing does not exist in memory

Variables

let test;
console.log(test); // undefined
console.log(result) // error: not defined

For empty variables their result will always be undefined until you set them equal to something. This means that the variable is taking up memory but has no value. Variable ‘result’ in the above example has never been declared; so, Javascript does not know what it is.

Arrays and Objects

let test = [1,2,3];
console.log(test[0]); // 1
delete test[0]
console.log(test[0]); // undefined
console.log(test[50]); // undefined

Arrays and Objects work slightly different than a plain variable. If you delete the value in a position, or a key in an object, Javascript will return undefined. It will even return undefined for a key you have not ever declared, or a position beyond the length of the array. In conclusion, the only time you should encounter not defined is when you are using a variable that was declared in an inner function scope or never declared.

--

--

Jason Sigmon
JSON’s Coding Adventures

Founder of Arternic, LCS Fan, and tweet @jaysig91. Feel free to reach out and say hello