Wayne Wayne - 3 months ago 7
jQuery Question

Cookie NaN error on first visit

On first visit it to my site, there is no cookies set, so my calculation return a NaN error. How can I solve this (If no cookie, return a 0 instead).

This is what I use to get the cookie.....

$scope.WH1 = parseInt($cookies.get('WH1'));
$scope.WH2 = parseInt($cookies.get('WH2'));
$scope.WH3 = parseInt($cookies.get('WH3'));
$scope.WH4 = parseInt($cookies.get('WH4'));
$scope.WH5 = parseInt($cookies.get('WH5'));


and to set it I use .....

$scope.saveInCookie = function() {
$cookies.put('WH1', $scope.WH1);
$cookies.put('WH2', $scope.WH2);
$cookies.put('WH3', $scope.WH3);
$cookies.put('WH4', $scope.WH4);
$cookies.put('WH5', $scope.WH5);


My fiddle is http://jsfiddle.net/Lvrr0nzc/21/show

I did try || 0 in the code.

Answer

If no cookie, return a 0 instead

With the curiously-powerful || operator:

$scope.WH1 = parseInt($cookies.get('WH1')) || 0;
$scope.WH2 = parseInt($cookies.get('WH2')) || 0;
$scope.WH3 = parseInt($cookies.get('WH3')) || 0;
$scope.WH4 = parseInt($cookies.get('WH4')) || 0;
$scope.WH5 = parseInt($cookies.get('WH5')) || 0;

That works because NaN is falsy and ||, so NaN || 0 is 0 because the result of || is the value of its first operand if that value is truthy, or the value of the second operand otherwise.

Or you could use || earlier in the process:

$scope.WH1 = parseInt($cookies.get('WH1') || "0");
$scope.WH2 = parseInt($cookies.get('WH2') || "0");
$scope.WH3 = parseInt($cookies.get('WH3') || "0");
$scope.WH4 = parseInt($cookies.get('WH4') || "0");
$scope.WH5 = parseInt($cookies.get('WH5') || "0");

That relies on the value from $cookies.get() being falsy (null, undefined, "") if the cookie doesn't exist, which it probably is, and so value || "0" gets either the value from the cookie or the string "0".

But I'd probably use the first one.

Comments