- var
- let
- const
Scope of variables
examples/js/scope.html
<script src="scope_bare.js"></script> <script src="scope_var.js"></script> <script src="scope_let.js"></script> <script src="scope_const.js"></script>
examples/js/scope_bare.js
x = 1; { console.log(`inside before: ${x}`); x = 2; console.log(`inside after: ${x}`); } console.log(`outside: ${x}`);
examples/js/scope_var.js
var x = 3; { console.log(`inside before: ${x}`); var x = 4; console.log(`inside after: ${x}`); } console.log(`outside: ${x}`);
examples/js/scope_let.js
let x = 5; console.log(`before: ${x}`); { //console.log(`inside before: ${x}`); // Uncaught ReferenceError: Cannot access 'x' before initialization let x = 6; console.log(`inside after: ${x}`); x = 7; console.log(`inside end: ${x}`); } console.log(`outside: ${x}`);
examples/js/scope_const.js
const z = 10; console.log(`before: ${x}`); { console.log(`inside before: ${x}`); const z = 11; console.log(`inside after: ${x}`); z = 12; // Uncaught TypeError: // console.log(`inside end: ${x}`); } console.log(`outside: ${x}`);