The name of the variable that we choose must be meaningful to understand, what it represents in the program.
var Price = 100;
Rules to follow:
- The name of the variable can contain a letter, digits, underscore(_), and dollar sign($).
- They must begin with a letter, not with a digit.
- Uppercase and Lowercase are distinct. That means the variable Total is not the same as total or TOTAl.
- It should not be a keyword.
- White space does also not allow.
- Variable can be any length.
There are two types of variables.
- Local Variable
- Global Variable
Local Variable: Local variables are variables that are defined within the function. The scope of this is local. This means you only can use the local variable within the functions that define them.
Global Variable: The global variables are that defined outside of the function. The scope of this variable is Global. That means you can use any function without passing them to the function as parameters.
<html> <body> <script> var x = 10; var y = 20; var z=x+y; document.write(z); </script> </body> </html>
As a result:
Think about calculating the area of a wall. In math, the area of the rectangle is fined by multiplying two numbers.
width x height = area
We can be able to calculate the area of the wall in our mind. But when we write a script to do this calculation, We need to give very detailed instructions to the computer. We tell the computer to perform some steps. As following order.
- Remember the value of width
- Remember the value of height
- Multiply the width by height to get the area
- Return the result to the user
It’s a bit complicated. In this care, we use variables to “remember” the values for width and height. We also can compare variables to short-term memory because once we leave the page, the browser will forget any information it holds.