0

I was wondering whether I could refer to the array I am declaring in Javascript in its own declaration... See code

var data = [["foo",23],["bar",data[0][1]+6]];

I would like that array to be ["foo",23]["bar",29]

Thank you!

EstevaoLuis
2,5887 gold badges36 silver badges43 bronze badges
asked Apr 1, 2018 at 22:12
2
  • you cannot really use data in the array (you are creating a new local variable called data at that time. Why not create a variable that contains var fooArr = ["foo", 23], barArr = ["bar", foo[1]+6], data = [fooArr, barArr];. More interesting would be why you think that you need this kind of construct Commented Apr 1, 2018 at 22:19
  • It's kind of a strange question or bad practical example. I wonder why you would do that since 23 is a hard coded number and 23+6 is 29 you may as well do var data = [["foo",23]["bar",29]] if the number 23 comes from a variable (let's say num) then you can do ["foo",num]["bar",num+6] if you have an existing array and need an array from this based on previous value you can use reduce or zip/map Commented Apr 2, 2018 at 0:02

2 Answers 2

3

The JavaScript engine would first parse the array initializer, it won’t find any definitions for "data" and will throw an error. So, it wouldn’t work.

answered Apr 1, 2018 at 22:25

1 Comment

To clarify: an error will be thrown, because data will be undefined at that point and no property 0 can exist on it. It won’t throw an error merely because data doesn’t exist (var data; is hoisted), but something like let or const will, because of that.
1

It won't work as your referring to a variable that was not created yet. At this point data it still undefined. So you need first finish the declaration statement and then refer to the variable.

answered Apr 1, 2018 at 22:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.