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
  • 11
  • 26
pmn
  • 2,176
  • 6
  • 29
  • 56
  • 4
    `{}` is an object. Of course it's not null. – melpomene Jul 24 '16 at 10:21
  • `var p = {}` is not an unassigned variable. You assigned an empty object to it. – t.niese Jul 24 '16 at 10:22
  • Try `var p = {}; console.log(typeof p);` – Gerardo Furtado Jul 24 '16 at 10:22
  • @t.niese if i want using it in a `if` condition, how can use it? – pmn Jul 24 '16 at 10:23
  • 2
    [How do I test for an empty JavaScript object?](http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object) – pishpish Jul 24 '16 at 10:23
  • 2
    And beside that `p` is not `null` if your write`var p;`. It is of type `undefined`. So `p !== null` but `p === undefined`. – t.niese Jul 24 '16 at 10:24
  • 1
    Depends what you want to test for. If you want to know that it is an `object` then you test for `typeof p === 'object'`. If you wand to know if two variables point to the same object: `var p = {}; var q = p;` then you test `p === q`. – t.niese Jul 24 '16 at 10:26
  • @t.niese thank you. the link that you sent me was very helpful – pmn Jul 24 '16 at 10:33

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
  • 48,835
  • 10
  • 56
  • 78
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,715
  • 1
  • 21
  • 21