Home » Javascript » Javascript: How can I access a function-scoped variable within a do while loop?

Javascript: How can I access a function-scoped variable within a do while loop?

Posted by: admin August 19, 2018 Leave a comment

Questions:

This do while checks the user input. However, the console gives me an error, saying “size is not defined” which I think is because size is within the function whereas the while condition is outside the function

const newGrid = document.getElementById('new-grid');
newGrid.addEventListener('click', createGrid);

const main = document.querySelector('main');

function createGrid() {
    do {
        let size = parseInt(prompt("Please enter a number from 1 to 64", ""), 10);

        const numPx = (600 / size) - 2;
        let px = numPx + 'px';

        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const div = document.createElement('div');
                div.setAttribute('class', 'grid');
                main.appendChild(div);
                div.setAttribute('style', `width: ${px}; height: ${px}`);
            }
        }

    } while(isNaN(size) || size > 64 || size < 1);

}
Answers: