[JavaScript] Please explain the control flow and scope of this code. via /r/learnprogramming


[JavaScript] Please explain the control flow and scope of this code.

function lastIndexOf (array,value){ var found = false; var result = 0; for (var i = array.length - 1; i >= 0; i--){ if (array[i] === value) { result = i; found = true; break; } } if (found === true){ return result; }else { return -1; } } 

Objective:

Define a function lastIndexOf, which, given an array and a value, returns the index of the last time the value occurs in the array. If the value never occurs, the function should return -1.

My Confusion:

On lines 6 and 7, we changed the variable of "result" and "found". We use this change on lines 11 and 12. However, how is this possible when they are of different scopes? Lines 6 and 7 are 3 indents in, while lines 11 and 12 are 1 and 2 indents in. At an earlier point, I had my code like this, with the "found" and "result" inside the for loop.

function lastIndexOf (array,value){ for (var i = array.length - 1; i >= 0; i--){ var found = false; var result = 0; if (array[i] === value) { result = i; found = true; break; } } if (found === true){ return result; }else { return -1; } } 

With this format, I was told that on lines 11 and 12, that these variables were out of scope.

I appreciate your time and effort. Thank you.

Submitted July 10, 2017 at 12:45AM by NewbiusCoder
via reddit http://ift.tt/2tF1nZA

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s