What are variables used for in Javascript programs

Variables is used to store data and numbers and it’s values can be changed. Unlike constant whose value is fixed.
For example if variable x = 5 then in the future we can change the value of x to 8 or x to 100.
Whereas if value of constant is c = 4 then in the future we cannot change it’s value to 8 or 100 or anything.

In Javascript variables is used to store data like numbers, string, objects or any other type.
Variables are declared using var or let keyword and constant is declared using const keyword.

var x; // declaring variable x
let y; // declaring variable y
const c; // declaring constant c

x = 5; // initializing varaible x
y = 11; // initializing variable y
c = 8; // initializing constant c

x = 14; // changing the value of x from 5 to 14
x = 12; // again changing the value of x from 14 to 12

c = 21 // this will throw error because the value of c cannot be changed.

A simple program to add two numbers in Javascript two variables x and y and storing the result to variable sum.

var x; 
var y;
var sum;

x = 4;
y = 5;

sum = x + y;
console.log("The sum of x and y is "+sum);

The output of the code is

The sum of x and y is 9

In the above program we declare three variables x, y, and sum.
And then we initialize x and y with numbers 4 and 5 respectively.
After adding two numbers x and y we are storing the value to the third variable sum.

Facebook
Twitter
LinkedIn
Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME !!
Johan William

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

RECENT POSTS

TEST