- 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.
- Variable values can be used by calling the name of variable.
var name_of_var = VALUE;
let name_of_var = VALUE;
const name_of_var = VALUE;
var myname = "John"
- 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.
let myName2 = "John"
const myName3 = "John"
- In above example keywords like let and cont are used to create a variable instead of var.
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