0

I'm pretty new to coding and can't find out why this is outputting undefined:

var var0, list = [var0];
list[0] = true;
console.log(var0)
7
  • 1
    You never assign anything to var0. What do you expect it to be? Commented Nov 1, 2020 at 14:03
  • I'm assigning true to list[0] which from what I understand should be var0 Commented Nov 1, 2020 at 14:06
  • No, list[0] is the first item of the list. You don't have pointers and references here, just values - [var0] just creates an array [undefined], nothing more. There is no relation with the variable after the creation of list. Commented Nov 1, 2020 at 14:08
  • 2
    Does this answer your question? Is JavaScript a pass-by-reference or pass-by-value language? Commented Nov 1, 2020 at 14:08
  • 2
    @HarryLandesburg why? It very clearly explains that it's not a pass-by-reference language, hence you cannot expect changing a variable to change a copy of it or vice versa. I'm not sure what other explanation you're looking for. Commented Nov 1, 2020 at 14:21

2 Answers 2

1

On line 1 you copy the value of var0 into the array.

On line 2 you replace the value in the array.

This doesn't have any effect on var0. That is just a variable that used to have a copy of the same value. It is not a reference.

Sign up to request clarification or add additional context in comments.

8 Comments

That makes sense, but how then can I store var0 inside that array so that it's value can be modified?
You can't. JavaScript doesn't have explicit references.
@HarryLandesburg it's impossible. If you share what your overall goal is, we can probably advise how to approach it. Right now, it sounds like you probably just want to store your values in an object.
Darn, I'd expect that to be possible :/
@VLAZ I was attempting to check which arrow key is pressed making the code shorter than with if statements: window.addEventListener('keydown', KD); var left, up, right, down, list = [left, up, right, down]; function KD(event) { let LA = 0; for (a = 37; a !== 41; a++) { if (event.keyCode == a) { list[LA] = true; } LA++ } LA = 0; } I guess I'll have to go back to using a bunch of if statements...
|
1

You never use or define the value of var0.

list[0] = true;

This line replaces the value of the object in the 0 position (which is var0 because of the first line) to a boolean variable with the value "true".

What you mean to do is

var var0 = true, list = [var0];
console.log(list[0])

2 Comments

I know I could assign it true already but I'm trying to store it inside an array then set the first variable to true
@HarryLandesburg - you can't because that's not how javascript works. You never pass a variable, just the value of the variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.