http://phpcoder.tech/check-if-javascript-variable-is-null-or-undefined/

Here we are learning about some very basic JavaScript functionality. At the time of Website development, we use NULL which is an assignment value. In JavaScript mostly we getting an error statement called “undefined variable”. Before we start with “Check if JavaScript variable is NULL or Undefined”, first we learn about the difference between NULL or Undefined.

Difference between JavaScript NULL or JavaScript Undefined

In JavaScript, you can check the variable is Undefined or Null or empty string or has a value. Below are some points for clarifying the difference.

  1. In JavaScript Undefined means, the variable has declared but no value has assigned to it. Check below example:
  • var phpcoder; console.log( phpcoder ); console.log(typeof phpcoder);
  • Output: Undefined
    Undefined
  • JavaScript Null is an assignment value, which means a variable has no value. And null value has object type. See below example:
  • var phpcoder = null; console.log( phpcoder ); console.log(typeof phpcoder);
  • Output: Null
    Object

Before move forward, I have to clear that JavaScript NULL and JavaScript Undefined both are two distinct types.

  • Undefined is typing itself
  • A null is an Object
null === undefined // false
null == undefined // true
null === null // true

and,

null = 'value' // ReferenceError
undefined = 'value' // 'value'

Javascript typeof

Above we use “JavaScript typeof” in many places. So I want to clear you what is use of the JavaScript typeof operator.

The typeof operator returns a string indicating the type of variable“.

Example:

console.log(typeof 10);
// determined output: "number"
console.log(typeof 'PHP');
// determined output: "string"
console.log(typeof true);
// determined output: "boolean"
console.log(typeof declaredButUndefinedVariable);
// determined output: "undefined";

Let’s talk about JavaScript check undefined or JavaScript empty array using some examples, here we start,

if(any_value){
#code...
}

Using the above code you get the value “true” if the value is not,

  • Null
  • Undefined,
  • empty string
  • NaN
  • 0
  • False

You van also check like this,

if( typeof any_value === 'undefined' || any_variable === null ){
#code...
}

Here are all the explanation above. If you have any question please comment below

--

--

Bikash Panda

I am a web application developer. FB Community: @mrpandatech, Twitter: @phpcodertech My PHP problem-solving site http://phpcoder.tech