Javascript error/IIFEs

When I run this, I get error of "cannot set property “helloSpeaker” of undefined. Didn’t I define helloSpeaker when I made it an object (line 2)? This code is part of a set of three JS files, the main of which runs through an array, checks the first letter of each string, and returns “hello” or “goodbye” based on the first letter, if that means anything.

(function (window) {

var helloSpeaker = {};

var speakWord = "Hello";

helloSpeaker.speak = function (name) {
  console.log(speakWord + " " + name);

window.helloSpeaker = helloSpeaker;

Maybe if instead of doing

helloSpeaker.speak = …

do like:

helloSpeaker[“speak”] = …

same is valid to window.helloSpeaker…

@imerljak`s response has nothing to do with OP’s problem.
The error is in

window.helloSpeaker = helloSpeaker;

because window refers to your IIFE’s window parameter which is undefined.
Therefore, you get an error that says you cannot set property of undefined.

Think about why the window parameter is undefined.

if I type “window, document” does that solve my issue? I thought “window” was universal.

In this function, which window does #3 refers to?

window //#1

function(window) { // #2
    console.log(window) // #3

#3 refers to the “window” passed through the function as an argument?

Yea, it refers to #2. So what does window in your function’s body refers to and what is the value of it?

okay, I think i get it. so “window” when I invoke window.helloSpeaker refers back to the “window” i passed through the function, but what does that window (#1) refer to?

I modeled this code off of a similar snippet so I sort of don’t completely understand what I’m doing… I know I need to reference “window” in my IIFE because I need to make helloSpeaker visible to the top level, but I’m not totally clear on how or why.

In Javascript, unassigned parameters are undefined. Now find the difference between these two.

(function(myArg) {
    // some codes

(function(myArg) {
    // some codes

You should be getting what you did wrong by now

okay I think i’ve got it. I didn’t pass “window” as a parameter before, I just said that it was a parameter. if I put (window) between my last two parentheses, which invokes the functions, will this work?

thanks for your help and patience by the way!

Yea that’s right. In this case, you can simply remove the parameter. But in other environments where global environment is not window you might want to keep it.

1 Like