Search code examples
arraysloopsvarlet

get value name from array for specific index


In the code below, if I use 'let' instead of 'var' for declaration of array , it seems to work fine. I am not able to figure out why is this case in the below code.

And the second case is when I change the name of array from 'name' to something else like 'itemNames' , the code seems to work fine, is it something i am missing? I thought it might have to do with reserved keywords in JavaScript , however i had no luck with it . I have tried giving reserved keywords name to array for testing purpose (which is not recommended ) and the output was fine.

var name = ["ravina","Aditya","Rohit","shruti"]
function checkThree() {
    for(var i = 0; i<name.length; i++) {
        if (name[i].length == 3) {
            return name[i];
        }
    }
}
console.log(checkThree())

Solution

  • Maybe this can help: https://developer.mozilla.org/en-US/docs/Web/API/Window/name 'var name' refers to the global window.name. this global.name will be converted to a string of you log it to the console. (see output below)

    console output

    With 'let name' you declares a block-scoped local variable. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#:~:text=Description,function%20regardless%20of%20block%20scope.)