Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

ilovecode
ilovecode
8,071 Points

Getting undefined outside of function, even though return is working fine

Hi guys, I hope someone can help me. I don't understand why I am getting 'undefined' when I log 'spellBody' outside the function. I am defining 'spellBody' outside the function, which is how it must be, right? This is the reason that I am getting the error at the end. Can someone maybe help out?

let spellContainer = document.querySelector('.spell-container');

function createElements(element, type, parent, elementClass, elementID = '') {

    element = document.createElement(type);
    parent.appendChild(element);
    element.className = elementClass;
    element.id = elementID;
    console.log(element);  //returns the element as HTML, gives correct output

    return element;
}

let spellBody;
createElements(spellBody, 'div', spellContainer, 'spell-cast', 'some-id');

console.log(spellBody); //returns undefined

let spellRes;
createElements(spellRes, 'div', spellBody, 'spell-info');

//get error Cannot read property 'appendChild' of undefined

1 Answer

Steven Parker
Steven Parker
231,141 Points

The statement "let spellBody;" creates the variable, but does not assign any value to it. So it contains "undefined".

Since nothing is assigned to it before it is passed as an argument or logged, it will still be "undefined".

The assignment of the parameter "element" inside the "createElements" function does not change the original argument. You probably want to catch the return value from the function:

let spellBody = createElements(undefined, 'div', spellContainer, 'spell-cast', 'some-id');

The first parameter isn't needed and could be removed. Then declare "element" within the function.

ilovecode
ilovecode
8,071 Points

Thank you. I knew it was something simple, my brain had this 'its on the tip of my tongue' feeling. I kept arguing with myself about the 'element' parameter and I knew it was my problem, just couldn't figure out why. Thanks!