how do I fix undefined error with Javascript

Viewed 711

(function(window) {
  var name = {};
  Greeter.name = "John";
  var greeting = "Hello ";
  Greeter.sayHello = function() {
    console.log(greeting + johnGreeter.name);
  }
  window.johnGreeter = johnGreeter;
})(window); //
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="script.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>

  <div class="container">
    <h1>My First Bootstrap Page</h1>
    <p>This part is inside a .container class.</p>
    <p>The .container class provides a responsive fixed width container.</p>
  </div>

</body>

</html>

hi I am getting an undefined error when adding a greeter and no matter how I try to fix it, it keeps coming up I have tried taking the greeting out and just using the name not sure how to fix this. please help.

1 Answers

You are getting undefined because the Greeter-object is indeed undefined. This is a more detailed explanation of all the parts:

(function(window) {
  var name = {}; // make an object and store it in the "name" var
  name.Greeter = "John"; // give the "name" object an attribute called "Greeter"
  var greeting = "Hello"; // store a string in a variable

  name.sayHello = function(greeting) { // give the "name" object a function called "sayHello" and give it an argument ("greeting")
    console.log(greeting); // pass that argument to console.log
  }

  window.johnGreeter = name; // assign your "name" object to the globally available "window" object
})(window); 

If you'd like to call the function you made, you would use something like

name.sayHello("This is my message to you");

Or since it's globally available, you can alternatively use

window.johnGreeter.sayHello("This is my message to you");
Related