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

111
Views
initialize var with integer : zero == false

How can I initialize correctly my Int variable in JS ?

var h = {
  baz: 0
} // or {} has same result => 42

function foo(opt) {
  opt.baz ||= 42;

  return opt.baz;
}

foo(h);

it's because 0 == false is true...

So how can I properly define my variable default value?

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

0

You can use Logical nullish assignment:

var h = {baz: 0}

function foo(opt){
  opt.baz ??= 42;

  return opt.baz;
}

console.log(foo(h));

UPD: in case if you need to handle NaN:

var h = {baz: NaN}

function foo(opt){
  var defaultOpt = { baz: 42 }
  opt.baz = Number.isNaN(opt.baz)
    ? defaultOpt.baz
    : opt.baz ?? defaultOpt.baz;

  return opt.baz;
}

console.log(foo(h));

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!