A JavaScript error: what does undefined mean?
A variable with no value, a missing index and the difference from null.
All lessons · JavaScript lessons: learn from scratch
A variable with no value
undefined is not always an error. If a variable was created but never given a value, its value is undefined.
let ad; console.log(ad); // undefined ad = "Murad"; console.log(ad); // Murad
A missing index or property
A missing array index and a missing object property also return undefined. That says the data is not there. It does not stop the program by itself.
let meyveler = ["Alma", "Armud", "Banan"];
console.log(meyveler[5]); // undefined
let telebe = { ad: "Aysel", yas: 20 };
console.log(telebe.soyad); // undefinednull and TypeError
null is an empty value the programmer set on purpose. undefined means a value was never given. Reading a property from undefined throws a TypeError. Check first.
let secilmis = null;
let telebe;
if (telebe !== undefined) {
console.log(telebe.ad);
} else {
console.log("Tələbə məlumatı yoxdur.");
}Questions
Is undefined an error? By itself, no. A value was not given, or the data you asked for is missing.
How is it different from null? null was left empty on purpose. undefined was never set.
When does a TypeError happen? When you read a property from undefined with a dot. For example telebe.ad while telebe is undefined.
How do I check? if (ad === undefined). If there is a value, ad !== undefined.