Javascript: Variables

For any programming language, you first learn how to represent the various day to day usage like bill amount, name of a person, count of things. So the first step is to know whether there is support for Integers (to measure count), Floating point numbers (to express bill amount) and Strings (to write name). If you are from the C/C++/Java background, you would have probably used int, float and Java String(c: char *, c++ string ) for the above purposes. Let’s see what are the equivalent for these in Javascript.

Of course in Javascript you can use the following

  1. 9
  2. 100.23
  3. “This is a JavaScript Tutorial”

But there must be a way to store them so that you can reuse them at a later point of time. These stoage units are generally called variables. In the programming languages discussed above, you must specify the type of the variable like int, float. But here’s the surprise, in Javascript you need not specify the type. What?

Yes, you read it right. Javascript is a dynamically typed language. As the name suggests, Javascript assigns the type dynamically. That means to use a variable in Javascript you need to simply write

var varname [= value];

Let’s see some examples

var count = 34;
var amount = 100.24;
var message = "This is a javascript tutorial"

That’s it. Isn’t it simple.

We just mentioned that javascript is a dynamically typed language. So what do you expect for the following code?

var count = 34;
count = 100.24

Do you expect an error? What is the value of count? Yes, you guessed it right. It is 100.24. This is because in the second line, Javascript dynamically casts the type of the variable to a floating point number.

Now let’s discuss about the naming. You can give the names of the variables in the following manner


Is the above declaration clear to you? Those of you who are not familiar with this declaration. It means the following.
A declaration needs to be of length one or more.
The first character can be any of these: $, _, any character from a to z or A to Z
The remaining characters can be any numeral 0-9, $, _, any character from a to z or A to Z.

So the following variables are correct
$, _, a, b, A, $A, _a, a0e, name
Let’s see more on assignment of variables.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s