-7
const numbers = [1,2,3,4,5]
let luckyNum = numbers.pop()

What will be the value of numbers?

Hint: numbers is stored in a constant not a variable

Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
Henree_01
  • 9
  • 1
  • 7
    Just run and look at the result. –  Jun 03 '19 at 21:24
  • 2
    What do you find confusing? Have you tried running this code and seeing what happens? – Brad Jun 03 '19 at 21:25
  • 2
    numbers being a `const` rather than a `var` will not impact this particular code in any way. – JohnSnow Jun 03 '19 at 21:26
  • 2
    From MDN: _Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through **reassignment**, and it can't be redeclared._ In you particular case `numbers` holds a reference to the array and that reference will remain constant, not the array itself. – Shidersz Jun 03 '19 at 21:29
  • @brad yes i have but it brought out an uncaught error – Henree_01 Jun 03 '19 at 22:23

2 Answers2

-1

From the MDN you can read:

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can't be redeclared.

In you particular case the numbers variable holds a reference to the array and that reference will remain "constant", not the array itself. As you can check on next example:

const numbers = [1,2,3,4,5];
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);

// Now, next line will trhow an error, because we are
// trying to do a reassingment on a const variable:
numbers = [];

In the particular case you are interested, you can use Object.freeze() to prohibit changes on an array of primitives values:

const numbers = [1, 2, 3, 4, 5];
Object.freeze(numbers);

// Now, next line will thrown an error.
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);

I Hope this clarifies your doubts.

Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • I will try these out thanks – Henree_01 Jun 03 '19 at 22:24
  • @Henree_01 Ok, tell me when you have understood the concept. So I can delete the answer. People dislike answers on question that do not show efforts (keep this in mind next time), but I felt like helping you anyway. – Shidersz Jun 04 '19 at 00:33
-1

Even though it's a const, it will be modified and the new value will be [1,2,3,4].

Sloan Tash
  • 36
  • 4