Did I finish the task with broken code?



So this is the code I used:

"var list = function() {
var contactsLength;
for(var i = 0; i < contacts.length; i++) {

And when I go to the next excercise, this is the code I "probably" should have used:

function list() {
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
Why does the first one work? And why do I need to make that variable in the first place? Didn't really understand that part.


The reason it passes (assuming it did) is because the lesson checker was satisfied the expected elements are present. It runs (sort of) to completion because there are no exceptions raised. Truth is it is very close to complete. Not broken, just incomplete.

Consider contactsLength. It is declared so will not raise an exception when referred. But since it is undefined the loop condition is not met so the loop does not run.

Short answer is so that we see how it is done and how it works. This is the only lesson that checks for it, assuming it's the one that asks for it. We can use the contacts.length attribute going forward.

There are special cases where caching the array length is necessary. This would asssume that the array size is going to change. Comparing its finished length with the cached value is one way to confirm a change in length.


Thank you! I kinda understands now, guess I have to read it some more times :wink: Thank you so much for your help!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.