0

I'm learning JS and quite confused about variables:

Short Story: How browsers determine the type of data under var tag, how they determine storage requirements for the type of data under var tag, what happens when two different types of data are assigned one-after-another to the same variable and why these variables're all warped up under var name? It would make more sense if JS had different types of data as integers, strings etc.

Long Story: Normally, when we want to declare a variable, we define its type: integer, string or char etc. This way, we make sure enough storage is allocated for variable and most of the time, there're some special functions for that specific variable type. In JS, variables -and apparently functions too- are simply used under var name. So, we store anything under var name. My question is this: how browsers/JS compilers differentiate types of data in variables as string/char etc, how they decide the bit-length required for that data, and how they handle which functions will suit that data? What happens when I assign an integer to that variable first, then a string later? Also, wouldn't it be easier to define different types of variables?

I'm a beginner on JS, so go easy on me please. Cheers!

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management – DontVoteMeDown Jun 09 '17 at 14:23
  • 3
    Welcome to learning JavaScript, you've asked the question that in my mind is what makes JS the best and the worst. – George Jun 09 '17 at 14:23
  • 2
    Javascript has types, it's just dynamically typed instead of statically typed. And I think you're thinking too low level for a language like JS. That's not something you should need to worry about unless you're writing an engine. – Carcigenicate Jun 09 '17 at 14:24
  • Ultimately, everything in JavaScript is an object. – Baruch Jun 09 '17 at 14:27
  • You should look into TypeScript. It's a transpiled variation of Javascript where you can strongly type your variables. It's for debugging purposes only, really, as it is transpiled back to Vanilla JS before it's run. But variables are typeless in Vanilla JS. `var thing = 4; thing = 'asdf'; thing = [];` is perfectly valid. – SethWhite Jun 09 '17 at 14:28
  • 1
    The advantage is that you don't have to worry about types unless you're dealing with floating point numbers. Almost everything will be converted implicitly. This can lead to some weirds results, but leads to shorter code. The downside is that you'll have some type and type conversion errors you won't catch at compile time. But the shorter syntax and autoconversion makes up for it tremendously. I cry every time I have to write like SQL code where I have to recast every result and end up with 5 lines that would be one line in JS. If you really do want static types, check out typescript. – Shilly Jun 09 '17 at 14:28
  • 1
    Also keep in mind that JS does all memory allocation inside its heap automatically. So you never have to like malloc manually. For example, no matter how long or which type a number has, they are all stored as (un)signed 32 bit floating points. – Shilly Jun 09 '17 at 14:31

4 Answers4

4

JavaScript variables are not typed but their values do have a type. The same variable can be assigned new values.

var i;  
console.log(typeof i);
i = true; 
console.log(typeof i);
i = 0;      
console.log(typeof i);
i = "hello";
console.log(typeof i);

As far as the memory allocation is concerned, its nicely explained here.

Yog
  • 88
  • 7
2

Variable's in JS are untyped manually.

As @DontVoteMeDown mentionned; they are dynamically typed : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures

This is your responsibility as a developer to manage your types and control on your JS variables.

aorfevre
  • 5,034
  • 3
  • 21
  • 51
  • 1
    Actually variables do have types, they are just [*Dynamically typed*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures). That is why [`typeof()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) exists. – DontVoteMeDown Jun 09 '17 at 14:25
  • 2
    Covering the use of the term "untyped": https://stackoverflow.com/questions/964910/is-javascript-an-untyped-language. Related to saying that JS isn't typed. – Carcigenicate Jun 09 '17 at 14:26
  • @DontVoteMeDown No, the statement is totally fine. *Variables don't have types*. Values do. – Bergi Jun 09 '17 at 14:29
  • 1
    I have updated my answer to be more correct on my statements. – aorfevre Jun 09 '17 at 14:44
2

This is really broad, so I will break it down.

How browsers determine the type of data under var tag

The JavaScript Runtime Engine can determine the variable type by the type assigned, either a literal or another variable. This is different than a compiled language that requires type information at compile time, before runtime.

How they determine storage requirements for the type of data under var tag

This is partially defined in the spec, partially implementation specific. For example var i = 0 is a number but how that is implemented depends on the JavaScript Runtime Engine.

What happens when two different types of data are simultaneously assigned to the same variable and why these variables're all warped up under var name?

You actually can't assign at the same time, but you can assign one after the other. When you assign the second time, the value and the type are changed!

var o = 5; // variable 'o' is a number with value 5
o = 'Hello'; // variable 'o' is a string with value 'Hello'
o = {foo: 'bar'}; // variable 'o' is an object with value {foo:'bar'}

It would make more sense if JS had different types of data as integers, strings etc.

JavaScript does have different types!

JavaScript is a loosely typed or a dynamic language. That means you don't have to declare the type of a variable ahead of time. The type will get determined automatically while the program is being processed.

Example:

var o = 5;
console.log(typeof o); // number
o = 'Hello';
console.log(typeof o); // string
o = {foo: 'bar'};
console.log(typeof o); // object

I strongly recommend reading the MDN Data Structures docs for more info.

styfle
  • 22,361
  • 27
  • 86
  • 128
  • No, the parser doesn't figure out any types for `var` declarations. An engine might do type inference, but that's not part of the parsing. – Bergi Jun 09 '17 at 14:31
2

Javascript is loosely-typed. Which means variables don't have a specific type for the developer. This doesn't mean a variable has no type for the system.

Let's look at the following example:

var string = "foo";
var number = 2;
var boolean = true;
var object = {rhymes: "on blue"};
console.log(typeof string); //string type
console.log(typeof number); //number type
console.log(typeof boolean); //boolean type
console.log(typeof object); //an object

//you can also "reassign" a new type to a variable just by reassigning a new value:

var string = 2;
console.log(typeof string) //number type

Here you see that the system does in fact know the type of the variable.

The system also doesn't care that much about the type. Like a string or object doesn't have a pre-defined bit length because their value and/or length is arbitary.

This, let's call it feature, is a great benefit of Javascript but it can be a pain in the a** as well.

If you want to use the best part of both, loosely-typed and strongly-typed (if you have to define a type) you should learn about Typescript. This is just a superset of Javascript that compiles to plain Javascript but offers types.

Spitzbueb
  • 5,233
  • 1
  • 20
  • 38