-2

I'm not sure why my 'name' variable is undefined when you click the 'Add List' button.

Here's the suspected problem code:

function addList() {
            let name = prompt("What would you like your list to be called?");
            console.log(name);
            if (name != null) {
                console.log(name);
                let name = new list(`${name}`, "[]");
                const markup = `
                    <div id="${name}">
                    ${this.name} List:
                    <br>
                    ${this.items}
                    <br>
                    ${this.button}
                    <br>
                    </div>
                    `;
                document.getElementById("Shopping").append(markup);

            }
            return;
        }

Here's the codepen: https://codepen.io/vaughnick/pen/YYBoeq

Thanks for any insight/ tutorials you can link for me in my journey :)

imnickvaughn
  • 2,774
  • 9
  • 25
  • 42
  • Which variable? Tell us where you're seeing the problem; nothing immediately obvious happens in the codepen. – Herohtar Jan 21 '18 at 21:21
  • The pen does not reproduce the issue you're describing. It's recommended you add a [mcve] in the question itself, so your question remains relevant for future users. – tao Jan 21 '18 at 21:22
  • Sorry, the name variable is undefined. – imnickvaughn Jan 21 '18 at 21:22
  • Ill be deleting this, or I will make it useful for others as soon as I know whats going on. Thank you – imnickvaughn Jan 21 '18 at 21:27

2 Answers2

2

That's because you have two variables called name. As let is block-scoped variable, name which you are referring to is declared in the next line. This causes your error. You can either change second variable name or remove let to avoid creating new variable with the same name.

pwolaq
  • 6,343
  • 19
  • 45
1

let is scoped and by redefining it in the if {} block, it creates a new temporary variable. Before it creates it, it is therefore undefined. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let