Skip to content

Commit

Permalink
feat: Explain the behavior of const keyword in JavaScript
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 9, 2024
1 parent 8049b64 commit ac44eb2
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions Questions-Answers/76.const.md
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)

0 comments on commit ac44eb2

Please sign in to comment.