The title says it all, but I will provide more clarification:
After seeing many samples of javascript where all variables are declared as type var
, and seeing support for other datatypes, why aren't variables of a specific datatype declared as such? Meaning, why isn't this:
string hello = 'Hello, World'
used instead of
var hello = 'Hello, World'
Looking at sites like OReilly Javascript shows that there are reserved words for other types. Again, why aren't they used? Wouldn't it make lines like this: typeof(variable)==='string';
no longer needed?
JavaScript is a loosely typed language. It means it does not require a data type to be declared. You can assign any literal values to a variable, e.g., string, integer, float, boolean, etc.
4 Ways to Declare a JavaScript Variable:Using var. Using let. Using const. Using nothing.
Variable naming There are two limitations on variable names in JavaScript: The name must contain only letters, digits, or the symbols $ and _ . The first character must not be a digit.
Quite simply, JavaScript variables do not have types. The values have types.
The language permits us to write code like this:
var foo = 42; foo = 'the answer'; foo = function () {};
So it would be pointless to specify the type in a variable declaration, because the type is dictated by the variable's value. This fairly common in "dynamic" languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With