Skip to content
Advertisement

Uncaught ReferenceError: candle1 is not defined at :1:1 (anonymous) @ VM12033:1

I’m trying to figure out why I am able to console.log candle1, but I cannot type it directly into the console without an error.

Here is the Candle.js code:

class Candle {
  constructor(scent, material, color, numWicks, waxColor) {
    this.scent = scent;
    this.container = {
      material: material,
      color: color,
      numWicks: numWicks,
    };
    this.waxColor = waxColor;
  }
  newNumWicks(numWicks) {
    this.container.numWicks = numWicks;
  }
  newMaterial(material) {
    this.container.material = material;
  }
  newScent(scent) {
    this.scent = scent;
  }
  newColor(color) {
    this.container.color = color;
  }
  newWaxColor(waxColor) {
    this.waxColor = waxColor;
  }
}

export default Candle;

Here is the script.js code:

import Candle from "./Candle.js";

const candle1 = new Candle(
    "Midnight Blue Citrus", 
    "Glass", 
    "Blue", 
    3, 
    "White");

console.log(candle1);

console.log(candle1.container.material);

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Practice: Making classes and objects</title>
    <script type="module" src="Candle.js"></script>
    <script type="module" src="Backpack.js"></script>
    <script type="module" src="script.js"></script>
  </head>
  <body></body>
</html>

This is the result of running the code: console.log results

The red error message is me trying to type candle1 directly into the console.

Please ignore the two yellow messages, they are due to a couple of extensions that I use.

Advertisement

Answer

This is an issue with ES6 modules and their variables being access limited to the script (CS term: scoping).

You can make the make candle1 accessible everywhere by adding window.candle1 = candle1 to the bottom of the script. window being the global scope in this case.

The window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, the window interface is a suitable place to include these items that need to be globally available. (…)

See this question for more information about this problem.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement