JavaScript Variables have three types of scope:
- Global – a global variable can be accessed from anywhere in the code. by default it is global if nothing specify.
- Local- a local variable will be visible only within a function.
- Const – declare a constant. Once assigned value, it cannot be reassign. if tried to reassign, it will give TypeError: Assignment to constant variable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="mydiv1"></p> <p id="mydiv2"></p> <p id="mydiv3"></p> <script type="text/javascript"> function checkscope() { var globe = "global "; // Declare a global variable let local = "method local "; // Declare a local variable const myConst = "Constant "; // declare const variable document.getElementById("mydiv1").innerHTML = 'Local Variable: ' + local; document.getElementById("mydiv2").innerHTML = 'Global Variable: ' + globe; document.getElementById("mydiv3").innerHTML = 'Const Variable: ' + myConst; } checkscope(); </script> </body> </html> |
JavaScript Reserved Words
- Below table list of all the reserved words in JavaScript are given in the following table.
- These cannot be used as JavaScript variables, functions or any object names.
abstract | else | instanceof | switch |
boolean | enum | int | synchronized |
break | export | interface | this |
byte | extends | long | throw |
case | false | native | throws |
catch | final | new | transient |
char | finally | null | true |
class | float | package | try |
const | for | private | typeof |
continue | function | protected | var |
debugger | goto | public | void |
default | if | return | volatile |
delete | implements | short | while |
do | import | static | with |
double | in | super |