Variables in JavaScript

Introduction to variables:

Variables are used to store data values.

Declaring and assigning values to variables:
ex. var fullName = ‘John Doe’;
Here, we have declared a variable called “fullName” and stored value “John Doe” in it.

Best practice for naming the variables:

You can give variables names as you like. But, giving meaningful and descriptive variable names is a good programming practice.

Rules for declaring variables:

  1. All variables must be unique. They are also called as identifiers.
  2. You can create a variable containing letters, digits, underscore, and dollar sign.
  3. Variables can also start with _ and $.
  4. Variables are case sensitive. This means that variables names like “car” and “Car” are different.
  5. Javascript reserved keywords cannot be used as variables. Example: for, var, switch, try, catch. etc.

Expressions:

We can create expressions like algebraic expressions.

Example:
var a = 10;
var b = 20;
var c = a + b;

**Notes:

You can also declare a variable without giving value. But if you try to get value of that variable, you will get undefined.

You can also declare multiple variables in one statement.

Example: var firstName = “John”, lastName=”Doe”, gender=”Male”;

Simple Arithmetic Calculation program in javascript:

We will create a simple calculation program with the help of javascript variables and expressions.

Step1: Create an HTML file and paste the following code.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Arithmetic Calculation</title>
    <script type="text/javascript">
      var a = 20, b = 10;
      var addition = a + b;
      var subtraction = a - b;
      var multiplication = a * b;
      var division = a / b;

      document.write("Addition is :", addition);
      document.write("<br />");
      document.write("Subtraction is :", subtraction);
      document.write("<br />");
      document.write("Multiplication is :", multiplication);
      document.write("<br />");
      document.write("Division is :", division); 
    </script>
  </head>
  <body>
  </body>
</html>

Step 2: Open the HTML file in a browser. You will see the result as follows.

arithmetic calulation program in javascript

Additional Links:

Strings in Javascript

Loops in javascript

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments