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:

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

<script type="text/javascript">

if(!yourVariable)
{

        var yourVariable = "Some text here!";

}

alert(yourVariable);

</script>

</body>
</html>

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.

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com