3

I was just randomly practicing JS code today and I put this line of code and ran the code.

var name = 45;
console.log(typeof name);

It told me the type of variable name is a string. It's very strange but type of Name is String yet when I typed this:

var age = 45;
console.log(typeof age);

But here type of variable age is Number. Why am I observing this kind of inconsistency? is it some convention or something like this?

Dan Homola
  • 3,819
  • 1
  • 28
  • 43
rameezmeans
  • 830
  • 1
  • 10
  • 21
  • 3
    Have you considered that `name` is either a reserved word or identifier? http://www.javascripter.net/faq/reserved.htm – random_user_name Apr 21 '18 at 22:56
  • do JS assign Types on names of variables? like 'name' will be assigned String type no matter value is 45 which is a number. – rameezmeans Apr 21 '18 at 22:59
  • 1
    Possible duplicate of [Using the variable “name” doesn't work with a JS object ?](https://stackoverflow.com/questions/10523701/using-the-variable-name-doesnt-work-with-a-js-object) – Paul Apr 21 '18 at 23:01
  • no no. no duplicate declaration sir. – rameezmeans Apr 21 '18 at 23:02

1 Answers1

5

If you were running this in a browser, then I think it's because the default execution context is the window object. Basically, every global value you declare becomes a property of the window object, and vice versa: every property of the window object is available as a global variable (e.g console). Window objects have a name property by default, and redeclaring it as a variable doesn't affect that. Anyway, that's the closest I can get to an explanation.

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
  • thanks. there are 2 Variable names. 'name' and 'status' these 2 are String. No matter you assign numbers to them. – rameezmeans Apr 21 '18 at 23:10
  • If you look up the window object on MDN you can get a complete list of its properties, which will be the names you can't/probably shouldn't use for global variables. – Máté Safranka Apr 21 '18 at 23:18