-1

I was working with the variables and datatypes and found that I can also define variables without initializing it with var, let or const. But when I defined a variable without var, let or const it becomes the type of "string" always. If I assigned my variable with number then too its type becomes string. If I add two numbers let's say 10 and 20, it gets add and results 30 but the type still shows its a string. So if anyone could explain me why is it always showing string.

car = "Mercedes";
console.log(car); // outputs Mercedes
console.log(typeof car); // outputs string

car = 123;
console.log(car); // outputs 123
console.log(typeof car); // outputs string

car = 10 + 20;
console.log(car); // outputs 30
console.log(typeof car); // outputs string
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320

1 Answers1

-1

Without var, let, or const, a variable is global, i.e. a property on the global object. In a browser, it is the window object. Setting car=123 is the same as setting window.car=123, and will produce a value of type number.

Some window properties are special though. E.g. setting name=123 or window.name = 123 actually invokes a setter, and the property name will always have type string.

Any property can be made special in this way. E.g. the following definition will make your example work as you described:

Object.defineProperty(window, 'car', { 
  set: function(x) { this._car = String(x); },
  get: function() { return this._car; } 
});
DS.
  • 22,632
  • 6
  • 47
  • 54
  • 1
    But OP says: *I am using variable named car from the very start*, and `car` is not one of those special global properties – Snow Apr 11 '20 at 04:33
  • I typed this before seeing that comment. But a property with custom getter/setter still a likely explanation of what OP is seeing. Updating to clarify. – DS. Apr 11 '20 at 04:37
  • 1
    @Snow Yeah, I got it. I used `name` as a variable name and it only shows string. If I use `car` then it follows the rule. Thank You. – Jainam Parikh Apr 11 '20 at 04:42