JS Dasar: 52. Scope
by istiq20
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Scope</title>
</head>
<body>
<script>
// global scope
let counter = 0;
// global scope
function hitMe() {
// local scope hitMe
counter++;
}
// global scope
function other() {
// local scope other
}
hitMe();
hitMe();
console.info(counter); // 2
// nested function scope
function first() {
// local scope first
let firstVariable = "First";
function firstNested() {
console.info(firstVariable); // can access local scope first function
const firstNestedVariable = "First Nested";
}
firstNested();
// console.info(firstNestedVariable); // ERROR
}
function second() {
// local scope second
let secondVariable = "Second";
// console.info(firstVariable); // ERROR
}
first(); // First
second();
// global scope
// console.info(firstVariable); // ERROR
// console.info(secondVariable); // ERROR
</script>
</body>
</html>