0

Hello I have array outside function like below :

var daily = [];
daily["data"]=[];
daily["data"].push('hello');

function demo()
{
console.log(daily); // not working here
}

How to declare this object as global in Javascript ?

5
  • 1
    Use {} for objects. [] are used for arrays. But then you can't use push so you need to make up your mind what type of structure you're using. Commented Feb 4, 2014 at 16:03
  • ok but push is not working in object Commented Feb 4, 2014 at 16:04
  • @Andy This is wild: jsfiddle.net/2NSUQ. Take a look at the console output...at least tested in Chrome. Seems to be an associative array... Commented Feb 4, 2014 at 16:06
  • @crush, see my amendment. If you try to find the length it returns 0. See also: andrewdupont.net/2006/05/18/… Commented Feb 4, 2014 at 16:10
  • @Andy I guess I just forgot that JavaScript arrays actually have the ability to use a string value as an index. It's probably been a decade since I attempted that, if ever... Commented Feb 4, 2014 at 16:13

1 Answer 1

1

It could be because your function is being hoisted. Try this instead for your function.

var demo = function(){
  console.log(daily);
}

You might also considering just passing that daily variable into your function like so,

var demo = function(d){
  console.log(d);
}

then when you want to call it.

demo(daily);
Sign up to request clarification or add additional context in comments.

2 Comments

how do i call this function ?
Same as you normally would. demo(); Also if I were you consider passing in daily into the function, var demo = function(d){console.log(d)} then when you call it demo(daily);

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.