Before understanding variables, let’s first understand what are the datatypes. Datatypes are basically the type of value like number, string, boolean.
- Numbers are like 100, 45, 8990 etc. These values are not included in double quotes. These include both integers and floating-point numbers.
- String values are like “Hello World”,”This is a test value” etc. These values are included in double quotes.
- Boolean values include only two values that are true and false.
Variables: Variables are the names in which data is stored in the form of numbers or string values. They are defined by the keyword var. Variables should have unique names and should not be declared twice. For example:
var age = 18; var name = "David";
Here age, name is the variable in which we are storing the numeric value 18, David. In JavaScript, we do not define the datatype to be stored in variable. It is determined by the value assigned in it. We use Assignment Operator (=) to assign a value to the variable. If we do not assign a value to the variable, it automatically takes the undefined value.
There are two types of variables: Global Variables and Local Variables.
Global Variables: These types of variables have global scope. They can be defined once and used anywhere in the JavaScript code.
Local Variables: These types of variables have local scope. For example, if you define a variable within a function, you can use that variable within that function only. NOTE: Within a function, a local variable will always have priority then the global variable, provided they have the same name.
There are some rules that we use to define the variable names:
- Variables names can have numbers, alphabets, underscore and dollar sign.
- Variable names should begin with a letter, but can also begin with a dollar sign or an underscore like _Age or $age. Variable names should not start with a number.
- Variable names are case-sensitive that is Age and age are different variables.
- We cannot use reserved words as variable names like if, break, case, switch, var, else etc.