views:

504

answers:

4

In other words, what options do I have to allocate memory in JavaScript?

I know you can allocate memory either globally, or inside function scope. Can I allocate memory dynamically? What does the new operator really mean?

Edit: here's a specific example. How would you implement reading an integer value from the user - n, and then read n integers into an array?

+1  A: 

No, you don’t need to and can’t allocate memory. The JavaScript interpreter does that automatically.

Gumbo
I can't agree with that statement. var i = 0 is memory allocation for all I'm concerned. If I'm not allocating memory, I'm not programming.
Yuval A
So you rather want to know what the `var` is for and why it should be used?
Gumbo
+7  A: 

you can't allocate memory. you can create objects. that's what new does.

now, javascript is a queer creature: functions are also objects in javascript. So this mean that you can instantiate prettymuch everything using new.

So, the new operator means that a new object is being created.

Javascript also garbage-collects these variables, just like it happens in java. So if you know java, it should be easy for you to draw parallels.

cheers,

jrh

PS: when you allocate objects, you really are allocating memory. Only, you are not doing that explicitly. You can allocate an array, and make it behave like a memory buffer, but that will degrade javascript performance drastically: javascript arrays are not in-memory buffers, they are also objects (like everything else).

Here Be Wolves
+1  A: 

Hmmm sounds to me like you are coming from the memory focused language and trying to shoe horn that logic into JS. Yes JS uses memory (of course), but we have garbage collection to take care of cleaning it all up.

If you are after specifics about the guts of memory allocation then you will have to hunt around for that. But as a rule thumb, when you use var, new or declaring a new function (or closure) you are gobbling up memory. You can get vars to null to flag them for garbage collection and you can use the delete keyword too although few do either of these unless they work Server-side (like myself with ASP JScript) where its important.

Pete Duncanson
+1  A: 

JavaScript has garbage collection and handles this for you.

However, you can help it by using the delete operator where appropriate.

From the Apple JavaScript Coding Guidelines:

Just as you used the new operator to create an object, you should delete objects when you are finished with them, like this:

delete myObjectVariable;

The JavaScript runtime automatically garbage collects objects when their value is set to null. However, setting an object to null doesn’t remove the variable that references the object from memory. Using delete ensures that this memory is reclaimed in addition to the memory used by the object itself. (It is also easier to see places where your allocations and deallocations are unbalanced if you explicitly call delete.)

Steve

Steve Harrison