falsey javascript | Cell 4 | Cell 6 | Search

The JavaScript code attempts to log the type of an undefined variable undef to the console, but throws a ReferenceError instead. When trying to log the result of the expression undef || {"too much": false}, it returns the object literal {"too much": false} to the console due to the undefined value of undef.

Cell 5

console.log(typeof undef)
console.log(undef || {"too much": false})

What the code could have been:

// Define a constant for the undefined variable
const UNDEF = undefined;

/**
 * Returns the type of the undefined variable.
 * 
 * @returns {string} Type of the UNDEF.
 */
function getTypeOfUndef() {
  return typeof UNDEF;
}

/**
 * Returns a fallback object if UNDEF is truthy.
 * 
 * @returns {Object} Fallback object.
 */
function getFallbackObject() {
  return UNDEF || { "too much": false };
}

// Use the functions to print the results
console.log(getTypeOfUndef());
console.log(getFallbackObject());

Code Breakdown

Line 1: console.log(typeof undef)

Line 2: console.log(undef || {"too much": false})