How to unset a JavaScript variable?

By Saruque Ahamed Mollick

In this JavaScript tutorial, I will explain if you can delete a variable or not in JavaScript. If yes, then how you can delete a variable or unset a JavaScript variable easily.

Someone says it delete someone says unset.



Delete is an operator by Which you can remove a property of an object. But it can’t be used to delete a variable.

So it is clear, you can’t delete a property which is created with var by using delete operator. But you can delete a property ( or a variable whatever you say ) which is created without var.

Guess The Number Game Using JavaScript

Unset a JavaScript Variable or Delete a JavaScript Variable

Just look at these two examples I am gonna provide below.

<!DOCTYPE html>
<html>
<head>
  <title>Title goes here</title>
</head>
<body>
  <script type="text/javascript">
    var some_variable= 23;
    delete some_variable;
    document.write(some_variable);
  </script>
</body>
</html>

Output:

23

3D Photo/Image Gallery (on space) Using HTML5 CSS JS

What happened?

<script type="text/javascript">
	var some_variable= 23; // used var here
	delete some_variable;  // it will return false
	document.write(some_variable);  // value of some_variable will be still here
</script>

Now see the second example. This time we gonna create a variable without var

<!DOCTYPE html>
<html>
<head>
  <title>Title goes here</title>
</head>
<body>
  <script type="text/javascript">
    some_variable= 23;
    delete some_variable;
    document.write(some_variable);
  </script>
</body>
</html>

Output:


So, you will get a blank output. BecauseĀ  now the property some_variable is gone.

( In the earlier versions of browsers It can be show you as some_variable is not defined, but now it will not show you any error. Instead of any kind of error it will show nothing )

Why?

<script type="text/javascript">
	some_variable= 23; //  now this is a property not a variable
	delete some_variable; // this will return true
	document.write(some_variable); // will show you the value of some_variable
</script>

Special Note:

Finally, You can also use

some_variable= undefined;; // unset variable

It will unset the variable.

Moreover, You may also be interested in,

How to compare two dates in JavaScript

How to convert binary to decimal in JavaScript easily

Get user’s Latitude and Longitude in JavaScript HTML5 Geolocation

 

Leave a Reply

Your email address will not be published. Required fields are marked *