Javascript: Assignment of Variables

Once you have learned about the naming and declaration of variables in Javascript, let’s proceed further to know more about the usage of variables.

Let’s begin with a simple example in C/C++.

void print_number() {
    int num;
    printf("%d", num);

Those of you who are not familiar with C/C++, the above function declares a variable to be of type integer and prints it. There are two important things that should be noticed.

  1. We didn’t assign any value to the variable.
  2. What’s the value for an unassigned variable?

In C/C++, the value printed will be some junk value. By junk, we mean, it can print some random value on every execution. This is because C/C++ doesn’t guarantee any fixed value for an unassigned variable.

Let’s explore in Javascript

var count;

alert("The value of count is " + count );

You will see the alert message “The value of count is undefined”

So for a declared and unassigned variable, Javascript guarantees that it contains the value undefined. With this logic, you can write your programs

We discussed how Javascript is dynamically typed. So let’s see how to assign values.

During declaration of variables

var count = 34;

You can change the value at a later point

count = 56;

Let’s try more experiments

var sitename = "Joys of Programming";
var percentage = 90.34;

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