2

I used

const args = process.argv; args.shift(); args.shift()

to line up my command line arguments and ignore the first 2 words node index.js

My code works just fine but it gives me a bit of anxiety regarding const as a word in NodeJS.

args is not a constant if i'm allowed to change it. Does anybody know why it works the way it does?

  • 1
    Does this answer your question? [Const in JavaScript: when to use it and is it necessary?](https://stackoverflow.com/questions/21237105/const-in-javascript-when-to-use-it-and-is-it-necessary) – joshwilsonvu Apr 24 '20 at 20:27

2 Answers2

3

const doesn't make something immutable, it just means you can't re-assign it to a new value. You can add whatever you want to existing object and array consts. For immutability, you would want a 3rd party library.

Regarding using args.shift();, I would caution against it since it mutates the args array in place. Why not do something like const myArgs = args.slice(2); which returns a copy of the array minus the first two items?

sdotson
  • 790
  • 3
  • 13
0

Let us take an example:

const arr = ["a", "b", "c"]

arr will be assigned an address to an object created in the heap, which has keys 0, 1, 2 i.e indexes as a key.

As arrays are nothing but an object in js.

When you do shift operation on const arr, we are not changing the value of address assigned to variable arr in stack memory, we are just removing 0th key from the object at that address.

Stack memory       Heap Memory
|        |        | {         |
|        |        |   0 : "a" |
|        |        |   1 : "b" |
|        |        |   2 : "c" |
|arr = 8k|        |  }        |
----------        -------------

Here, 8k is the address of the object created in heap memory.
Which is assigned to variable arr in stack memory.

So, after doing a shift operation our arr changes to ["b", "c"]

Stack memory       Heap Memory
|        |        | {         |
|        |        |           |
|        |        |   1 : "b" |
|        |        |   2 : "c" |
|arr = 8k|        |  }        |
----------        -------------

0th key from object in heap memory is removed.
Hritik Sharma
  • 1,756
  • 7
  • 24