Skip to main content
GameDev.net gamedev.net
🔒 Locked

Javascript - Better to instantiate variables, or leave them undefined?

Started by BUnzaga Oct 14, 2012 at 12:55 PM 3 replies 2.5k views
Original Post
BUnzaga
BUnzaga
In Javascript, if I know a variable type, but not necessarily the value, is it better on memory or run-time performance to instantiate it with a 'dummy' value, or is it better to just leave it undefined, and then only instantiate it when it is first needed?

For example...

var array1;
var number1;
var string1;
/* vs */
var array2 = [];
var number2 = 0.0;
var string2 = "";

// later in code...
function onInit(){
array1=[1,2,3];
array2=[1,2,3];
number1 = 3.142;
number2 = 2.718;
string1 = "Hello";
string2 = "World";
}

Is it best to fill the variable with a dummy 'type' or just leave it 'undefined' ?
slicer4ever
slicer4ever
it is better to initialize to a "null" value, so this way you can do error checking against this null value, to make sure you don't incorrectly try to access invalid data.

memory-wise, you are not saving anything, the variable still takes up physical memory, regardless of it's content.

performance-wise, it's doubtful you would see any return whatsoever, any performance gain(and this would be the upmost minimal), would almost never translate to being a bottleneck point for an application, as such, it's pretty much a moot point to discuss.
BUnzaga
BUnzaga
Thanks slicer4ever, that is a good idea about setting them to null for error checking.
Telcontar
Telcontar
Slicer pretty much covered it, but I will reinforce the importance of never intentionally leaving your data in an invalid state. That's just asking for trouble. Set it to something that won't throw an error upon an attempt to access it, even if it is a "dummy" value.
I Create Games to Help Tell Stories
tjlahr
tjlahr
It's perfectly valid to leave your variables 'undefined' at the top of your scope. In fact, it's what the JavaScript interpreter does anyway though a mechanism called variable hoisting. Devs often do this explicitly at the top of their scope in a single, comma-seperated list like this:

[source lang="jscript"]function(){
var array, number, string;

// or
var array = [],
number = 0,
string = '';

// function body...
}[/source]
I prefer the latter method, because it helps the routine document itself.

As for testing against null: I'd be careful. It's one of JavaScript's many quirks that null and undefined are strage cats and can behave unexpectedly (more info here). Everyone's needs are different but I would reccomend using if(typeof array !== 'undefined') if you must check for variable initialization.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.