CancelImage Upload

How to find out if a variable already exists in JavaScript

Unlike PHP, where a variable can be called upon at any time without being previously initiated, JavaScript requires that a variable has been defined properly before it can be used. Of course this calls for a bit of careful planning on behalf of the coder. After all, on the one hand you do not want to call upon a variable that does not exist, and cause a bug, on the other hand, if the variable does already exist, you do not want to overwrite it, and store a new value that might not be relevant.

The solution to this problem of course is to check whether or not the variable has already been initiated. And this can easily be accomplished with the help of an if statement. Here is how it's done:

<title>How to find out if a variable already exists in JavaScript</title>

<script type="text/javascript">


        var yourVariable = "Some text here!";





As you can see from the code above, with if(!yourVariable) we check as to whether or not the variable yourVariable already exists. Since it does not we initiate it, and upon this call upon alrert() to display it in an alert box. This way you are guaranteed not to overwrite, or redefine, previously defined variables.

Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •