Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring javascript variables as specific types [closed]

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?

like image 333
CBredlow Avatar asked Jan 07 '13 19:01

CBredlow


People also ask

Can you declare variable type in JavaScript?

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.

What are the 4 ways to declare a JavaScript variable?

4 Ways to Declare a JavaScript Variable:Using var. Using let. Using const. Using nothing.

Which you Cannot use at the time of declaring a variable in JavaScript?

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.


1 Answers

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.

like image 82
Matt Ball Avatar answered Oct 04 '22 14:10

Matt Ball