Ad

What Is The Significance Of The If Statement In This Code?

- 1 answer

I am currently learning JavaScript through some tutorials and this example came out in the tutorial. I'm just confused why must the if statement be there. I tried erasing the if statement and it still worked. Can someone help me please.

var timesVisited=0;
var dateVisited = 'Never';

if(localStorage.myLastVisit){
    var visit = JSON.parse(localStorage.myLastVisit);
    timesVisited = visit.numVisits;
    dateVisited = visit.dateVisits;
}

$("#dateVisit").html(dateVisited);

timesVisited++;
$("#numVisit").html(timesVisited);


var myVisits = {};
myVisits.numVisits = timesVisited;
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
myVisits.dateVisits = hours + ':' + minutes;
localStorage.myLastVisit = JSON.stringify(myVisits)
Ad

Answer

I tried erasing the if statement and it still worked.

Only if myLastVisit is already in localStorage. If it isn't there (which is what the if is testing for), without the if you'll get an error from JSON.parse because you'll pass undefined into it, which will get converted to a string with the charactersundefined in it because JSON.parse requires a string, which will then fail because that's not valid JSON. The if is there so that if the setting isn't present, the default values assigned to timesVisited and dateVisited are used.

Works if the setting is there:

var timesVisited=0;
var dateVisited = 'Never';

var visit = JSON.parse(`{"numVisits": 2, "dateVisits": "2020-03-27"}`);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited); // 2
console.log(dateVisited);  // "2020-03-27"

Fails if it isn't:

var timesVisited=0;
var dateVisited = 'Never';

var visit = JSON.parse(undefined); // ERROR
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited);
console.log(dateVisited);

Ad
source: stackoverflow.com
Ad