-1

I am new to JavaScript.

I have an index.html file with following content:

...

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Section 2: JavaScript Language Basics</title>
    </head>

    <body>
        <h1>Section 2: JavaScript Language Basics</h1>
    </body>

    <script src="script.js"></script>
</html>

...

Following are the contents of script.js:

var name = ['John', 'Mark', 'Jane'];

console.log(name[0]);

And the output I am getting in console window is 'J'. When I change the name of the variable to names or something other valid name, the output is correct: 'John'

Could you please help me in understanding what is causing this behavior?

Thanks

rsp
  • 537
  • 2
  • 13
  • Please also see [Why is the variable `closed` being logged as `false`, if I define it globally as `0`?](https://stackoverflow.com/a/51062916/4642212). – Sebastian Simon Jun 06 '20 at 16:47

1 Answers1

0

because there is already a variable exit as window.name that can only have string values and specifies window name. when you assign name = ['John', 'Mark', 'Jane']; the browser converts it to "John,Mark,Jane" Where name[0] is J;

for experiment We just assign

window.name or name = 4

and when you check it's type

console.log(typeof window.name) or console.log(typeof name)

it always return string

detail guide at w3school

w3school window.name

Community
  • 1
  • 1
Gaurav Bhardwaj
  • 328
  • 2
  • 8