0

If i us "var" to declare array given as below. Why give me 6

var name = ['Rohan', 'Google', 'Student'];
console.log(name.indexOf('Google'));

Otput is 6

If i use "let" to declare array give me right answer why

let name = ['Rohan', 'Google', 'Student'];
console.log(name.indexOf('Google'));

Otput is 1

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
Gagan
  • 13
  • 5
  • 1
    the one where you have use `let` is correct, have you declared the variable `name` is any other part of the code? Javascript can actually pick it up and then show the result – tsamridh86 Jul 29 '21 at 13:10
  • Do you use the variable `name` anywhere else? – zero298 Jul 29 '21 at 13:10
  • 1
    `var name` refers to [`window.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name). It will always be a string. If you do `console.log(name)`, it will show `"Rohan,Google,Student"` and not `['Rohan', 'Google', 'Student']`. Please check the duplicates for more details. – adiga Jul 29 '21 at 13:11
  • that's super weird, i think the problem is that javascript considered the first name (var) as string not array because when you do ```typeof(name)``` it gives **string**, which explains why indexof is returning 6 ( because G of Google is the 7th character, and when you declare it using let, typeof returns **Object** which is what you want – oubaydos Jul 29 '21 at 13:13
  • no i don't before because in my JS page has only tow line – Gagan Jul 29 '21 at 13:15

1 Answers1

2

Instead of naming your variable as name change it to some other name and you will get a right result.

var myArray = ['Rohan', 'Google', 'Student'];
console.log(myArray.indexOf('Google'));

The reason is there is some global variable called name whose result is being shown (If you check developer console and search window.name you can know what that variable is).

var has global scope in this case pointing to window object.

And in case of let name, we should know that let has local scope within the context so this time name points to your array not global name. Infact ES6 introduced let, const to avoid global spacing issue that we were facing with var

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35