1

In Javascript, I can assign a global variable in different data types in different function scope. For example:

var a = 1;
function foo(){
  a = a + 10;  //a is number in foo
}

function bar(){
  a = a + "hello";  //a is string in bar
  foo();  //a is string in foo now
}
foo();
bar();

My example is just a simple demo and I believe most Javascript programmers won't write it. However, is there any practical usage for such dynamic feature that global variable changes its data type in different functions?

Alex Celeste
  • 12,824
  • 10
  • 46
  • 89
shwu
  • 37
  • 4
  • 1
    dynamic typing can be useful, but there's a big debate about this topic http://en.wikipedia.org/wiki/Type_system#Static_and_dynamic_type_checking_in_practice – Doug T. Aug 04 '14 at 03:46
  • Thanks @DougT. for your information. But I still want to know is there a real or practical usage in my case even that I see most JavaScript programmers won't do it? – shwu Aug 04 '14 at 03:55

3 Answers3

1

Dynamic typing allows you to do stuff like this :

var a = false;    
if(need to show msg 1){a="message 1"};
if(need to show msg 2){a="message 2"};     
if(a){display(a);}

The example is not very good, but the idea is that you can use the same variable as a condition and content, or as an array element and as an error message if what you are looking for is not in the array,...

By the way, when you write a = 1, it is practically equivalent to window.a = 1; global variables can be considered as properties of the window object (.see here for precisions).
So when you write a = a + "hello";, a becomes a string everywhere and not just 'in foo'.

Community
  • 1
  • 1
IazertyuiopI
  • 488
  • 2
  • 12
0
  1. var a = 1; //global variable
  2. In foo() if (1) is defined

function foo(){ a; //In this case a will be global variable and a = 1 } function foo(){ var a; //In this case a will be private variable, a = undefined but global varibale a not change }

HDT
  • 2,017
  • 20
  • 32
0

It depends on what you're trying to do. With Javascript, global variables that are manipulated into different types can be dangerous if you're using a lot of callbacks. Callbacks functions triggering a lot (of course asynchronously) and manipulating a global variable can make it so you end up reading the wrong data in one or more callback functions and an unexpected result will follow deviating from your code's intention.

Mike D
  • 11
  • 3