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 🙂
JavaScript sets the variable type based on the value assignment. For example when JavaScript encounters the following code it knows that
myVariableshould be of type number:Similarly, JavaScript will detect in the following example that the variable type is string:
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.
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