48

I am creating a project using angularjs.I have variable like

$scope.test = null
$scope.test = undefined
$scope.test = ""

I want to check all null,undefined and empty value in one condition

0

7 Answers 7

109

just use -

if(!a) // if a is negative,undefined,null,empty value then...
{
    // do whatever
}
else {
    // do whatever
}

this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.

Sign up to request clarification or add additional context in comments.

2 Comments

I would be careful with that when dealing with booleans. Using $scope.$watch() for example, you want to check if the new value is undefined or null, but if that value is a boolean, using your solution will not work.
You also want to be careful with numbers, as you may want to catch undefined and null, but not 0.
9

You can do

if($scope.test == null || $scope.test === ""){
  // null == undefined
}

if false, 0 and NaN can also be considered as false values you can just do

if($scope.test){
 //not any of the above
}

Comments

3
if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){

console.log("test is not defined");
}
else{
console.log("test is defined ",$scope.test); 
}

Comments

1

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

Comments

0

You can do simple check

if(!a) {
   // do something when `a` is not undefined, null, ''.
}

Comments

0

A very simple check that you can do:

Explanation 1:

if (value) {
 // it will come inside
 // If value is either undefined, null or ''(empty string)
}

Explanation 2:

(!value) ? "Case 1" : "Case 2"

If the value is either undefined , null or '' then Case 1 otherwise for any other value of value Case 2.

Comments

-2

You can also do a simple check using function,

$scope.isNullOrEmptyOrUndefined = function (value) {
    return !value;
}

2 Comments

The function name is misleading, since value might be 0.
this function will return the opposite of what you are passing. regardless of data type

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.