They are a way to store information in your web browser for a short period of time. You can then use the stored data to build programs that make your web page interactive.
Without variables, your browser has no way of remembering information.
Without a variable, our browser won’t be able to check if the user has entered a correct password. Variables store data in the form of words or numbers.
You have to code variables in a certain way. You always have to tell your browser you are creating a variable. This is called defining a variable. Let’s have a look at how we create a variable that will store users name:
var userName = "Bob";
Let us simplify the above code:
var is the Variable keyword. Tells browser your declaring a variable. userName is the Variable Name. = “Bob”; assigns the Value inside the brackets to the userName variable. In this case assigns Bob text to userName variable.
- A keyword: To define a variable you have to use the variable (var) keyword. It tells your browser you are creating a variable.
- A variable name: The next part of a variable is the variable name. You can give your variable any name you like. The only rule with variable names is that they can’t have spaces (so use camelCase instead) and can’t begin with a number.
- A value: You then have to give your variable a value using the equals sign (=). Doing this is called assigning a value. If the value of your variable is text, you have to put the value in double quotes (” “). You can include spaces in your values. After the value, you have to include a semi-colon (;).