1

I am new to programming and am trying to learn angularJS to build a web app. I came across an example contacts manager app and am having difficulty understanding part of it, namely the part that checks if a contact exists or not:

 if($scope.newcontact.id == null)

Ok, I get that this checks if this is a new contact, but I don't understand what is happening in logical terms. I read up on null and understand it to mean that the thing being evaluated is known to exist, but does not have value.

So does this mean 'newcontact.id exists but does not have a value'?

Below is the javascript part of the app:

var uid = 1;

function ContactController($scope) {

$scope.contacts = [
    { id:0, 'name': 'Viral', 
      'email':'hello@gmail.com', 
      'phone': '123-2343-44'
    }
];

$scope.saveContact = function() {

    if($scope.newcontact.id == null) {
    //if this is new contact, add it in contacts array
    $scope.newcontact.id = uid++;
    $scope.contacts.push($scope.newcontact);
    } else {
    //for existing contact, find this contact using id
    //and update it.
    for(i in $scope.contacts) {
        if($scope.contacts[i].id == $scope.newcontact.id) {
        $scope.contacts[i] = $scope.newcontact;
        }
    }                
    }

    //clear the add contact form
    $scope.newcontact = {};
}


$scope.delete = function(id) {

    //search contact with given id and delete it
    for(i in $scope.contacts) {
        if($scope.contacts[i].id == id) {
            $scope.contacts.splice(i,1);
            $scope.newcontact = {};
        }
    }

}


$scope.edit = function(id) {
//search contact with given id and update it
    for(i in $scope.contacts) {
        if($scope.contacts[i].id == id) {
            //we use angular.copy() method to create 
            //copy of original object
            $scope.newcontact = angular.copy($scope.contacts[i]);
        }
    }
}
}
skwny
  • 2,930
  • 4
  • 25
  • 45
  • Related: http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined?rq=1 – Pete TNT May 29 '14 at 14:22

1 Answers1

2
if ($scope.newcontact.id == null)

if $scope exists AND $scope has a property called newcontact which also exists AND newcontact has a property called id AND id has not been assigned a value.

By that statement the author assumes (or has previously checked) that $scope exists and is not null and that $scope.newcontact exists and is not null. The explicit check is that id is a property on newcontact that has not been assigned a value.

Darko
  • 38,310
  • 15
  • 80
  • 107