<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
let pi = 3.14
console.log(`pi = ${pi}`)
//scope of block
{
let pi = 3.141592
console.log(`pi = ${pi}`)
}
console.log(`pi = ${pi}`)
//scope of function
function sample(){
let pi = 3.141592
console.log(`pi = ${pi}`)
}
sample()
console.log(`pi = ${pi}`)
</script>
</head>
<body>
</body>
</html>
### Variable Scoping Demonstrated
- **Global Scope**: Initially, a variable `pi` is declared with the value `3.14`. This variable has a global scope, meaning it can be accessed anywhere in the script.
- **Block Scope**: The script then enters a block (denoted by curly braces `{}`). Inside this block, another `pi` variable is declared with the value `3.141592`. This declaration of `pi` is separate from the global `pi` due to block scoping introduced by `let`. The block-scoped `pi` shadows the global `pi` within the block, so the `console.log` inside the block outputs `pi = 3.141592`. Once execution leaves the block, the global `pi` is accessible again, and its value remains unchanged (`3.14`).
- **Function Scope**: Next, a function `sample()` is defined and called. Within `sample()`, `pi` is once again declared with the value `3.141592`. Like block-scoped variables, this function-scoped `pi` is separate from the global `pi` and only accessible within the function. The `console.log` inside the function outputs `pi = 3.141592`. Outside the function, the global `pi` remains accessible and unchanged.
### Output
The console output of the script will be:
```
pi = 3.14
pi = 3.141592
pi = 3.14
pi = 3.141592
pi = 3.14
```
This sequence of outputs demonstrates how JavaScript treats variable scoping:
- The first and third `console.log` calls reference the globally scoped `pi`, printing `3.14`.
- The second `console.log` call references the block-scoped `pi`, printing `3.141592`.
- The fourth `console.log` call (inside `sample()`) references the function-scoped `pi`, again printing `3.141592`.
- The fifth `console.log` call, like the first and third, references the globally scoped `pi`.
### Key Takeaway
This example effectively shows how `let` allows for defining variables with block-level and function-level scope, contrasting with `var`, which defines variables with a function-level scope or globally if declared outside of a function. Scoping is a fundamental concept in JavaScript, crucial for managing variable lifetimes and visibility within different parts of a program.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 5) callback (1) | 2024.12.10 |
---|---|
chapter 5) expansion operator (2) | 2024.12.09 |
chapter 5) function_type (0) | 2024.12.07 |
chapter 5) strict mode (0) | 2024.12.06 |
chapter 5) Troubleshooting Using Immediately Called Functions (0) | 2024.12.05 |