- Variable is like an empty box that can be used to store information. You can place anything inside the box.
- It’s a temporary place to store values.
- Variables are pieces of memory allocated to store information.
- Variables are defined using keyword var in JavaScript. You can assign any name to variable, just like you can place any name on your empty box however there are some rules for naming variables.
- Variable values can be used by calling the name of variable.
JavaScript Variable Syntax
var name_of_var = VALUE;
or in ES6+ version of JavaScript, we can use this syntax
let name_of_var = VALUE;
const name_of_var = VALUE;
JavaScript Variable Example
1 2 3 4 |
<script type="text/javascript"> var myname = "John" document.write(myname) </script> |
- In above example var is used to create a variable.
- myname is the name we assigned to our variable
- John is the value we saved in our variable
- on this HTML page we can use document.write followed by the name of variable and it will show the value of variable.
JavaScript Variable Example ES6
1 2 3 4 5 6 7 |
<script type="text/javascript"> let myName2 = "John" document.write(myName2) const myName3 = "John" document.write(myName3) </script> |
- In above example keywords like let and cont are used to create a variable instead of var.
- In ES6 version of JavaScript variables are created using either let or const keyword
var vs let vs const
- var, let and const can be used to create a variable.
- var allows using one name for multiple variables, however let and cont only allow using one name for one variable.
- let and const are blocked scoped.
- const variable values can’t be changed but let variable value can be changed.
- var can be used in ES6, however it’s a good idea to avoid using var from ES6 onwards.
Rules for Naming Variable
- Variable names are case sensitive
- Variable names cannot start with numbers
- Variable names cannot contain spaces
- Variable names can contain letters, numbers, $, _
- Variable names can not use reserved keywords