简体   繁体   中英

Understanding for loops: use of undefined variables inside the loop

Ok, so i have a very simple for loop inside a function that takes an array as its only argument. I have set the array.length as the condition for the loop.

Inside the loop i use an undefined variable and a document.write.

Why is it, that javascript exits the loop after 1 run because the variable y is not set? I was expecting the loop to continue for (array.length).

See this codePen: http://codepen.io/anon/pen/wmlBC (uncomment var y).

    function checkName(array){

    var i = 0;
    var y = "";

    for(i = 0; i < array.length; i++){

        y += array[i]

    }

    return y;


}

var arrayNames = ["liselore", "karel", "david", "stefan", "kevin", "sandy"];

console.log(checkName(arrayNames));

If you look in your browser console, javascript returns an error:

ReferenceError: y is not defined

Because y isn't defined, the loop stops due to the ReferenceError thrown.

Your code throws a ReferenceError . Error s in JavaScript work like Exceptions in other languages. They break normal program flow and bubble up till they find a catch statement that satisfies their type.

If the Error is not caught the engine will report it as an Uncaught [error] and current the event ends.

All errors are fatal in JavaScript (except if you catch them, and even then only if it's catchable).

Therefore, the loop will exit immediately, regardless of there being any other iterations to run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM