undefined is a value in JavaScript that is used to represent nothingness. When a variable is declared, it is assigned to undefined by default.
var bb;
bb === undefined; // true
Remember that variables can be reassigned to other values after they are initially declared.
var abc;
abc === undefined; // true
abc = "happy";
abc === undefined // false
Functions that do not use the return keyword to explicitly return a value will return undefined by default.
function boring() {}
var result = boring();
result === undefined; // true
Functions can perform operations, but will still return undefined if the return keyword is forgotten.
function add(a, b) {
a + b;
}
var result = add(44, 55);
result === undefined; // true
undefined is a separate type:
typeof(undefined); // "undefined"
Strings ("bob", "i like cheese"), numbers (4.55, 77), and booleans (true, false) are other types we've already covered in this book.
Question | Click to View Answer |
What does the following code print to the console? var x = 11;
console.log(x);
|
11 The variable x is assigned to the value 11 and is then printed to the console. |
What does the following code print to the console? var lol;
var zyz;
console.log(lol);
|
undefined The variable lol is declared but is not assigned to any value. When variables are declared but not assigned to a value, they are automatically assigned to undefined. |
What does the following code print to the console? function fullName(x, y) {
x + " " + y;
}
console.log(fullName("Mr", "Powers"));
|
undefined The fullName() function does not use the return keyword, so nothing is returned from the function. JavaScript returns undefined from a function when the return keyword does not specify a return value. |