2

I know when we want to define unassign variable in Javascript we can do:

var p;

and the other:

var p ={};

i want to know differences between these two ways, and if i define a variable in second way it is not null! what is the value in the variable, if we want using it in a if condition, for example :

var p ={};
if(p=='what i shout put there')
  {}
Rohit Goyani
  • 1,246
  • 10
  • 26
pejman
  • 2,053
  • 5
  • 27
  • 55

2 Answers2

2

var p is creating an unassigned variable. So console.log(p) will log undefined

var p ={}; is a way of creating object using literal notation.

Object p have methods like constructor,hasOwnProperty,toLocaleString etc

if(p=='what i shout put there'){}

If it is required to check if p is an object then below snippet is useful

if(Object.prototype.toString.call( a ) === '[object Object]'){
 // Do rest of code
}

An object can have properties. like

var p={};
p.a ="someValue";

In this case you can check by

if(p.a  === 'someValue'){
     // Do rest of code
    }
brk
  • 46,805
  • 5
  • 49
  • 71
0
var p = {};

It is not unassigned ,it is infact assigned to the empty object

If you do below , it will be trut

if(p) {} // truthy
Piyush.kapoor
  • 6,385
  • 1
  • 19
  • 20