<script> i=3; // variable declaration(Not Recommended); var x="Tech Altum"; // value of x is "Tech Altum"; var y='Tech Altum'; // value of y is also "Tech Altum"; var z=9; // value of z is 9 numeric. var a=2, b=3, c=5; // multiple variables in single line var u; // u is undefined </script>
- variables cannot starts with numbers and hyphen, use alphabets or underscore(_).
- variables can have strings followed by numbers, like x1 and x2 are allowed but 1x, 2x is not allowed.
- For separation in variable names, use underscore (_) or camel casing, do not use hyphen (-) separation and white space, i.e, user_name is valid, username is also valid, but user-name is invalid.
- variables names are case sensitive, i.e, x1 and X1 are different.
let and Const
let and const were introduced in ECMA 6. let is used to declare temporary values with limited scope, like inside a function. Whereas const is used to declare permanent values, which can't be change. Like value of pi, e, G and other constants.
<script> let x="user"; // to store temporary values const pi=Math.PI; // pi is a constant, and can't change </script>
Although it is not compulsory to start variables with var keyword, but still we prefer var. let and const are supported in IE 11 and above, edge, firefox 36 and above, chrome 21 and above, safari 5.1 and above.