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!
2 Answers 2
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.
1 Comment
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.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.
Comments
Explore related questions
See similar questions with these tags.
data
in the array (you are creating a new local variable calleddata
at that time. Why not create a variable that containsvar fooArr = ["foo", 23], barArr = ["bar", foo[1]+6], data = [fooArr, barArr];
. More interesting would be why you think that you need this kind of constructvar data = [["foo",23]["bar",29]]
if the number 23 comes from a variable (let's saynum
) 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