Stefan
Stefan

Reputation: 2613

How does Javascript know what type a variable is?

I don't know why I never asked myself that questioned the last years before, but suddenly I could not find any answer for myself or with google.

Javascript is known to have no types for variables. A really nice thing. But somehow it must determine the type and work with it.

var a = 1;
var b = 2.0;
var c = 'c';
var d = "Hello World!";

So what we have is an Integer, Double/Float, Character, String (which may be teared down as char*)

I know that JS works with a runtime interpreter, but thinking of that the logic and "type" must be implemented in any way..

So how does a Javascript Interpreter recognize and internally handle the variables? In my imagination, assuming I would write C++, I would think of a sort of template and container and a bit of a logic that overloads operators and try to check, what it really is. But that's not thought to the end.

Share your knowledge with me please :-)

Upvotes: 5

Views: 3025

Answers (4)

6502
6502

Reputation: 114461

One simple way to imagine an implementation is that all values are kept in objects and that all variables are pointers... in C++:

struct Value
{
    int type;
    Value(int type) : type(type) { }
    virtual ~Value() { }

    virtual std::string toString() = 0;
};

struct String : Value
{
    std::string x;
    String(const std::string& x) : Value(STRING_TYPE), x(x) { }
    virtual std::string toString()
    {
        return x;
    }
};

struct Number : Value
{
    double x;
    Number(double x) : Value(NUMBER_TYPE), x(x) { }
    ...
};

struct Object : Value
{
    // NOTE: A javascript object is stored as a map from property
    //       names to Value*, not Value. The key is a string but
    //       the value can be anything
    std::map<std::string, Value *> x;
    Object() : Value(OBJECT_TYPE), x(x) { }
    ...
};

For example whenever an operation has to be performed (e.g. a+b) you need to check the types of the objects pointed by the variables to decide what to do.

Note that this is an ultra-simplistic explanation... javascript today is much more sophisticated and optimized than this, but you should be able to get a rough picture.

Upvotes: 0

talha2k
talha2k

Reputation: 25650

JavaScript sets the variable type based on the value assignment. For example when JavaScript encounters the following code it knows that myVariable should be of type number:

var myVariable = 10;

Similarly, JavaScript will detect in the following example that the variable type is string:

var myVariable = "Hello World!";

JavaScript is also much more flexible than many other programming languages. With languages such as Java a variable must be declared to be a particular type when it is created and once created, the type cannot be changed. This is referred to as strong typing. JavaScript, on the other hand, allows the type of a variable to be changed at any time simply by assigning a value of a different type (better known as loose typing).

The following example is perfectly valid use of a variable in JavaScript. At creation time, the variable is clearly of type number. A later assignment of a string to this variable changes the type from number to string.

var myVariable = 10;
myVariable = "This is now a string type variable";

The variable’s data type is the JavaScript scripting engine’s interpretation of the type of data that variable is currently holding. A string variable holds a string; a number variable holds a number value, and so on. However, unlike many other languages, in JavaScript, the same variable can hold different types of data, all within the same application. This is a concept known by the terms loose typing and dynamic typing, both of which mean that a JavaScript variable can hold different data types at different times depending on context.

Complete article here: http://www.techotopia.com/index.php/JavaScript_Variable_Types

Another Article Which may help you: http://oreilly.com/javascript/excerpts/learning-javascript/javascript-datatypes-variables.html

Useful links:

ECMAScript Language Specification

ECMAScript BNF Grammar

JAVAScript BNF Gramar

Upvotes: 2

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76405

JavaScript itself does have types, and internally, each assignment receives an appropriate type. In your example var foo = 2.0; the type will be float. The programmer needn't worry about that too much (at first) because JS is loosly typed (!== type-free).
That means that if I were to compare a numeric string to a float, the engine will coerce the string to a number so that the comparison can be preformed.

The main difference between loose typed and strong typed languages is not type coercion, though. It's quite common in C(++) to cast to the type you need, and in some cases values are automatically converted to the correct type (2/2.0 == 2.0/2.0 == 1.0 ==> int is converted to float, implicitly). The main difference between loosly typed and strong typed languages is that you declare a variable with a distinct type:

int i = 0;//ok
//Later:
i = 'a';//<-- cannot assign char to int

whereas JS allows you to do:

var i = 1;//int
i = 1.123;//float
i = 'c';//char, or even strings
i = new Date();//objects

But, as functions/keywords like typeof, instanceof, parseFloat, parseInt,toString... suggest: there are types, they're just a tad more flexible. And variables aren't restricted to a single type.

Upvotes: 1

James Allardice
James Allardice

Reputation: 165961

The only useful line I can find in the ES5 spec is this:

Within this specification, the notation “Type(x)” is used as shorthand for “the type of x” where “type” refers to the ECMAScript language and specification types defined in this clause.

I assume that when the runtime needs to perform an operation that needs to know the type of some value, it will check that value against the grammar defined in the spec for each type, until it finds a match.

For example, the grammer for a boolean literal is as follows:

BooleanLiteral ::

  true 
  false

If the value is exactly true or exactly false (e.g. with no quotes) then that value is of type boolean.

Upvotes: 1

Related Questions