Samik Sengupta
Samik Sengupta

Reputation: 1973

Javascript - Array keeps being interpret as String

I have this code -

var status = ["A", "B", "C", "D", "E", "F"];


$(function() {
  console.log(window.status);
  console.log(typeof window.status);
  var status = ["A", "B", "C", "D", "E", "F"];
  console.log(status);
  console.log(typeof status);

});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Outside of $(function() {}); the var status is declared as an array. Yet when it comes to logging it to console, it shows up as a String.

I repeat with the same thing inside the ready function and it behaves as it should this time. What's wrong with this code?

Upvotes: 0

Views: 258

Answers (2)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Check with other name its using default by javascript

var my_status = ["A", "B", "C", "D", "E", "F"];


$(function() {
  console.log(window.my_status);
  console.log(typeof window.my_status);
  var status = ["A", "B", "C", "D", "E", "F"];
  console.log(status);
  console.log(typeof status);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Stephan
Stephan

Reputation: 2115

window.status was the property which defined the browser's status bar text (a string). Therefore your array got automatically converted to a string.

You could prevent that from happening if you move status into its own closure, for example by wrapping it within a (function(){...})(); and accessing it by status, not window.status.

Upvotes: 3

Related Questions