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

88
Views
undefined output in while loop w/array using Nth root equation javascript

I'm trying to write this code for an after effects expression that will move an object a calculated x distance over n number of frames. The movement over each frame is parabolic rather than linear, and so I'm using the nth root code to determine how much the object should move over each frame. I'm putting each of the nth roots into an array to access later when setting the positions for each move.

I'm still learning javascript mainly for AE, so please bear with me if there are things in here I don't fully understand. I think I understand, which is why I'm not sure I'm getting the undefined output for certain n values. Here's the code:

//get Nth root
function nthroot(x, n) {
  ng = n % 2;
  if ((ng == 1) || x < 0)
    x = -x;
  var r = Math.pow(x, 1 / n);
  n = Math.pow(r, n);

  if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
    return ng ? -r : r;
}

distance=1515; //will be determined by another portion of the AE expression
frames=6; //will be set by expression control in AE
const myArray = [];
let i = 1;
while (i <= 6) {
  myArray.push(nthroot(distance,i++));

}

console.log(myArray);
document.getElementById("demo2").innerHTML = myArray

I put it into a fiddle here. What am I doing wrong? Thanks in advance for any help!

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

0

Your "nthroot" function doesn't return values consisistently: if you look at the end of your function you can find this part:

if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
   return ng ? -r : r;

if you notice, you are returning a value only if the condition in the if statement is fullfilled, otherwise you are not returning any value. In JavaScript, a function that doesn't return any value returns "undefined" instead.

In other words, when

Math.abs(x - n) < 1 && (x > 0 === n > 0)

is true, you are returning either "r" or "-r", but when the condition is false you aren't returning any value, so the function returns "undefined".

You have to handle the false case.

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!