JavaScript Check if Variable is Object
JavaScript Check if Variable is Object – While dealing with the object types variable we need sometimes to check that the variable is object so that we can avoid any other type of variables. You can use typeof method to check the variable type object. Here in this tutorial we are going to explain how you can check the object type variables in JavaScript. You use try it functionality to check the functionality online.
JavaScript Check if Variable is Object Example
You can use typeof() (variable instanceof Object) method to check the variable type whether it is object or not.
Using typeof()
Using typeof() method you can check variable if it is object as below –
JavaScript Check if Variable is Object:
<html> <head> <title>Javascript Demo</title> <script type='text/javascript'> function checkobject(){ var myCar = {type:"Hundai", model:"1000", color:"white"}; if(typeof(myCar) == "object"){ alert("Object"); }else{ alert("Not Object"); } } </script> </head> <body> myCar = {type:"Hundai", model:"1000", color:"white"}; <a href="javascript:void(0)" onclick=" checkobject()">Check Object-</a> <p id='result'></p> </body> </html> |
Using instanceof Object
Using instanceof Object method you can check variable if it is object as below –
JavaScript Check if Variable is Object:
<html> <head> <title>Javascript Demo</title> <script type='text/javascript'> function checkobject(){ var myCar = {type:"Hundai", model:"1000", color:"white"}; if(myCar instanceof Object == true){ alert("Object"); }else{ alert("Not Object"); } } </script> </head> <body> myCar = {type:"Hundai", model:"1000", color:"white"}; <a href="javascript:void(0)" onclick=" checkobject()">Check Object-</a> <p id='result'></p> </body> </html> |
Advertisements