-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Explain the behavior of
const
keyword in JavaScript
- Loading branch information
1 parent
8049b64
commit ac44eb2
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
# 76. const | ||
|
||
### Problem | ||
|
||
https://bigfrontend.dev/quiz/const | ||
|
||
# | ||
|
||
### Problem Description | ||
|
||
What does the code snippet below output by `console.log`? | ||
|
||
<!-- prettier-ignore --> | ||
```js | ||
function func() { | ||
const a = b = c = 1; | ||
} | ||
func(); | ||
console.log(typeof a, typeof b, typeof c); | ||
``` | ||
|
||
# | ||
|
||
### Answer | ||
|
||
``` | ||
"undefined","number","number" | ||
``` | ||
|
||
### Explanation | ||
|
||
- `typeof a` returns `"undefined"`, because constants are block-scoped. We declared `a` with `const` inside the function `func()`, therefore `a` is local only to the `func() {}` block. When we access `a` outside of that scope, i.e., in the global scope, `a` is `undefined`. | ||
|
||
- `typeof b` and `typeof c` both return `"number"`, because `b` and `c` are declared globally. | ||
|
||
`const a = b = c = 1` is equivalent to the following: | ||
|
||
```js | ||
c = 1; | ||
b = c; | ||
|
||
const a = b; | ||
``` | ||
|
||
Since there are no declarations for `b` and `c`, both of them are created as global variables. Therefore, the code snippet in the problem statement is essentially the same as the following: | ||
|
||
```js | ||
var b; | ||
var c; | ||
|
||
function func() { | ||
c = 1; | ||
b = c; | ||
|
||
const a = b; | ||
} | ||
func(); | ||
console.log(typeof a, typeof b, typeof c); | ||
``` | ||
|
||
First, we call `func()`; `c` and `b` are assigned to `1`. Then we log the type of `b` and `c`. Since now `b` and `c` are pointing to the number value `1`, `typeof b` and `typeof c` return `"number"`. | ||
|
||
It's worth noting, when declaring a constant, we must specify its value in the same statement in which it is declared: | ||
|
||
```js | ||
// throws an error | ||
// Uncaught SyntaxError: Missing initializer in const declaration | ||
|
||
const a; | ||
``` | ||
|
||
# | ||
|
||
### Reference | ||
|
||
[Initialization of several variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#initialization_of_several_variables) |