Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

68
Views
Get a default value instead of `undefined` for non-existing array element

I'm trying to get the value "0" back when there's nothing written in the spreadsheet cell whose data I get returned as JSON in an API call. But the output is always undefined. I tried using if else, but it didn't work.

IMG SHEET

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + field[0] + '</span><br><span class="field2">' + field[1] + '</span><br><span class="field3">' + field[2] + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color:green;
}
.field2 {
  font-size: 14px;
  color:blue;
}
.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use the ?? operator (Nullish coalescing operator) to replace null and undefined with something else, in this case, 0.

For example: (field[1] ?? 0)

$(function() {
  $.getJSON("https://sheets.googleapis.com/v4/spreadsheets/10Ct44JBW-CyoApJXIV87jeVU3Rr-fiLTdoTIJdbSwG8/values/page!A1:C3?key=AIzaSyArRlzwEZHF50y3SV-MO_vU_1KrOIfnMeI", function(result) {
    $.each(result.values, function(i, field) {
      $(".guide").append('<span class="field1">' + (field[0] ?? 0) + '</span><br><span class="field2">' + (field[1] ?? 0) + '</span><br><span class="field3">' + (field[2] ?? 0) + '</span><br>');
    });
  });
});
.field1 {
  font-size: 12px;
  color: green;
}

.field2 {
  font-size: 14px;
  color: blue;
}

.field3 {
  font-size: 18px;
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div class="guide"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!