3

If I run this code in the jsFiddle it correctly seems to log the typeof, first six are strings then the seventh index is an object. However in my personal local code, all seven indexes are a string, and if you copy and paste this code into the console it logs all also as a string. Why is this?

jsFiddle: https://jsfiddle.net/xcuje23q/

JS:

var someArray = ['Mike','Brett','Kim','Steve','Amy','Tanner',{name:'Oliver'}];

for(var i = 0; i < someArray.length; i++){

  var name = someArray[i];
  console.log(typeof name)

}
Chipe
  • 4,641
  • 10
  • 36
  • 64

2 Answers2

8

Javascript follows function level scope, there is property name for window object(global) and in console, it refers to property of window as it is executed in global context(window.name)

Use IIFE((function(){ /*your code */ })()) to get expected output as name does not belong to window anymore. function(){ } has its own scope

(function() {
  var someArray = ['Mike', 'Brett', 'Kim', 'Steve', 'Amy', 'Tanner', {
    name: 'Oliver'
  }];

  for (var i = 0; i < someArray.length; i++) {
    var name = someArray[i];
    console.log(typeof name)
  }
})()
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Edit: Refer WebKit Bugzilla for some interesting discussion about window.name

Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
2

There is one more alternative you may like. Do not use the variable name. Check this fiddle

var someArray = ['Mike','Brett','Kim','Steve','Amy','Tanner',{name:'Oliver'}];

for(var i = 0; i < someArray.length; i++){

  console.log(typeof someArray[i])
  // o/p 6 string and 1 object

}

OR

var someArray = ['Mike','Brett','Kim','Steve','Amy','Tanner',{name:'Oliver'}];

for(var i = 0; i < someArray.length; i++){

  var name2 = someArray[i]; // change name of the variable.
  console.log(typeof name2)

}
Kaushik
  • 2,072
  • 1
  • 23
  • 31