-1

i m just learning es 6 and i just socked when... i run this code..

var name = ["Rahul","Ritika","Amit","Radhika"]; console.log(name.length);

the answer is 25.. 25 why? it must have the answer 4 but gives 25 i don't know why?

i just run the code in browser console the answer is same... 25

but when i change the name of the variable name to something else like "c_name" it works fine...

let c_name = ["Rahul","Ritika","Amit","Radhika"]; console.log(c_name.length);

when i m trying to execute this code the out is again miss behaving...

// with name varible let name = ["Rahul","Ritika","Amit","Radhika"]; for(let i = 0 ; i < name.length; i++) console.log(name[i]);

****output****
"Rahul"
"Ritika"
"Amit"
"Radhika"

// other variable let c_name = ["Rahul","Ritika","Amit","Radhika"]; for(let i = 0 ; i < c_name.length; i++) console.log(c_name[i]);
output

"R"
"a"
"h"
"u"
"l"
","
"R"
"i"
"t"
"i"
"k"
"a"
","
"A"
"m"
"i"
"t"
","
"R"
"a"
"d"
"h"
"i"
"k"
"a"

for loop

Output with name

Output with c_name

Amritesh
  • 87
  • 1
  • 7
  • [`window.name`](https://developer.mozilla.org/en-US/docs/Web/API/Window/name) is a pre-defined property that can only contain a string value. – 4castle Jun 05 '18 at 22:59

1 Answers1

1

This is because name is a property on window object.

If you run your code other than the global scope, it will give you the correct result. The following code example shows that how to do that usingIIFE (Immediately Invoked Function Expression):

(function(){ 
  var name = ["Rahul","Ritika","Amit","Radhika"];  
  console.log(name.length);
})();
Mamun
  • 66,969
  • 9
  • 47
  • 59