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

133
Views
recursion in nested javascript object

find the addition of nested object using recursion here my sum is always passed as 10 ??......... I am trying to add sum value in else condition but in if it always pass as 10

let abc = { a: 10, b: { a: 20 }, c: { b: { a: 30 } } };

const Formation = (obj,sum) =>{

  for(let ky in obj) {
    if (typeof obj[ky] == 'object') {
       Formation(obj[ky],sum);
    } else {
      sum += obj[ky] ? obj[ky] : 0;
    }
  // console.log(sum)
  }
  return sum;
}

console.log('res: ', Formation(abc, 0));

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

0

Yes, it's because you don't use returned value from nested Formation. You need make some changes to your code:

let abc = { a: 10, b: { a: 20 }, c: { b: { a: 30 } } };

const Formation = (obj) =>{
  let sum = 0;

  for(let ky in obj){
    if(typeof obj[ky] == 'object'){
      sum += Formation(obj[ky]);
    }
    else{
      sum += obj[ky] ? obj[ky] : 0;
    
    }
  // console.log(sum)
  }
  return sum;
}
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!