How does Javascript know what type a variable is?

后端 未结 4 609
遇见更好的自我
遇见更好的自我 2020-12-06 13:52

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

4条回答
  •  余生分开走
    2020-12-06 14:42

    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

提交回复
热议问题