LILLY ROBOT |
Variables are containers that stores values of various data type. A variable has a name and a value.
Reserved and Keywords | |||||
---|---|---|---|---|---|
abstract | boolean | break | byte | case | catch |
char | class | const | continue | debugger | default |
delete | do | double | else | enum | export |
extends | false | final | finally | float | for |
function | goto | if | implements | import | in |
instanceof | int | interface | long | native | new |
null | package | private | protected | public | return |
short | static | super | switch | synchronized | this |
throw | throws | transient | true | try | typeof |
var | void | volatile | while | with |
A variable starts with the keyword var followed by the name of the variable and ends with a semi-colon. It is helpful to declare variables with meaningful names.
var nameOfVariable;
You can declare more then one variable in a single line followed by a comma after each name and end it with a semi-colon.
Once a variable has been declared you have to initialise it in other words assign a value. The equal sign is used to assign the value.
The values of a variable can change from a number to a string. If you are going to declare a variable that
holds numbers then stick to numbers. Otherwise, your codes could get messy.
Let us declare a variable age as a number and then change the variable age to a string.
Displays
The keyword const is used instead of var, so the variable value remains constantly the same through out the program.
Let's write a program that finds the area of a circle. We want the value of pi to be constant, so the keyword const will be used instead of var.
Displays
There are functions, which you can use to convert the value of a string to a number or vice versa.
The parseInt() functions lets you convert a string to an integer. The value of the string conversion must be inside the parseInt parentheses with quotation marks.
Displays
The parseFloat() converts a string to a decimal number.
Displays
There are two variable scopes local and global.
If you assign a variable outside a function it is called a global variable. It can be accessed by any of the functions on that page.
If you assign a variable inside a function it is called a local variable. It can only be accessed by that particular function.
However, if you declare a variable inside a function without the keyword var then it becomes a global variable.
In the example below we have declared two global variables a and b and have assigned the values 10 and 12. Inside the function we have declared a variable called answer, which has not been assigned a value.
However, when the function addition() is called the the value of answer will be the sum of a and b.
Displays