<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
let pi = 3.14
console.log(`pi = ${pi}`)
</script>
<script>
(function () {
let pi = 3.141592
console.log(`pi = ${pi}`)
})()
</script>
</head>
<body>
</body>
</html>
### Breakdown of the JavaScript Code
#### First `<script>` Tag
- A variable `pi` is declared using `let` with a value of `3.14`. This variable has a script-wide scope (global to the script block in which it is declared).
- `console.log(`pi = ${pi}`)` then logs this value to the console, resulting in the output: `pi = 3.14`.
#### Second `<script>` Tag
- An IIFE `(function () { ... })()` is defined and executed immediately. This is a JavaScript pattern used to create a new scope by defining an anonymous function and invoking it right away.
- Inside the IIFE, another `let pi` variable is declared with the value `3.141592`. This `pi` variable is scoped to the IIFE and does not affect or get affected by the `pi` variable in the first `<script>` tag.
- `console.log(`pi = ${pi}`)` within the IIFE logs this second `pi` value to the console, resulting in the output: `pi = 3.141592`.
### Key Takeaways
- **Variable Scoping**: The example illustrates how `let` allows for block scoping of variables. The two `pi` variables, although named the same, are scoped differently—one is scoped to its `<script>` block, and the other is scoped within an IIFE, demonstrating how variable names can be reused in different scopes without conflict.
- **IIFE Usage**: The use of an Immediately Invoked Function Expression (IIFE) showcases a common pattern for encapsulating a part of a program to both avoid polluting the global namespace and to create private variables and functions that can't be accessed from the outside world. This is particularly useful in larger, more complex applications where namespace management is critical.
### Output
When the document is loaded in a web browser, the console will display two messages:
- `pi = 3.14`
- `pi = 3.141592`
These messages reflect the values of the `pi` variable from the global scope of each `<script>` tag and the isolated scope within the IIFE, respectively.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 5) function_type (0) | 2024.12.07 |
---|---|
chapter 5) strict mode (0) | 2024.12.06 |
chapter 5) use to remaining parameters make array (0) | 2024.12.04 |
chapter 5) arguments (0) | 2024.12.03 |
chapter 4) for (0) | 2024.12.02 |