-2

I'm having problems getting the result for 'newestLine' out of the array map function. The first console.log gives the correct result the second two gives undefined.

         var currentArr = [+1+SN5M+K114987A+ZO1075892+ICRR+191009+000000+GU345HB+EC2419+1 ITEMS, +1+SN5M+K114987A+ZO1075892+I139+191009+151600+COVENTRY DEPOT+EC2419+1 ITEMS, +1+SN5M+K114987A+ZO1075892+ISCN+191009+151600+GU345HB+EC2419+1 ITEMS]

            currentArr.map(function(obj) {     
            if (obj.split('+')[7] > maxid) {
                maxid = obj.split('+')[7]; 
                var newestLine = obj;
                console.log(newestLine);
                return newestLine;
            }
            console.log(newestLine);
            return newestLine;
        });
        console.log(newestLine);
twl2009
  • 79
  • 1
  • 11
  • Can you please supply some test data? – LearningEveryday Oct 10 '19 at 15:37
  • Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Heretic Monkey Oct 10 '19 at 15:38
  • 1
    I would suggest reading another js tutorial. You appear to be throwing completely unrelated things at problems (async/await), in a trial-and-error way. That's not a time efficient way to code, or learn how to. – ASDFGerte Oct 10 '19 at 15:39
  • Basically, you've declared `newestLine` inside an `if` block inside a function and are trying to get its value outside of both. That's not how JavaScript works. – Heretic Monkey Oct 10 '19 at 15:40

2 Answers2

1

This is because you use the variable newestLine in the local scope within the function you pass to the map function.Change the scope of the variable by declaring it before the function and use it with in the function to get the expected result

var currentArr = [+1+SN5M+K114987A+ZO1075892+ICRR+191009+000000+GU345HB+EC2419+1 ITEMS, +1+SN5M+K114987A+ZO1075892+I139+191009+151600+COVENTRY DEPOT+EC2419+1 ITEMS, +1+SN5M+K114987A+ZO1075892+ISCN+191009+151600+GU345HB+EC2419+1 ITEMS]
 var newestLine;
            currentArr.map(function(obj) {     
            if (obj.split('+')[7] > maxid) {
                maxid = obj.split('+')[7]; 
                 newestLine = obj;
                console.log(newestLine);
                return newestLine;
            }
            console.log(newestLine);
            return newestLine;
        });
        console.log(newestLine);
Sathiraumesh
  • 5,949
  • 1
  • 12
  • 11
1

Second two newestLine gives undefined because of the variable newestLine out of their scope.

Do like this

var newestLine;
currentArr.map(function(obj) {     
            if (obj.split('+')[7] > maxid) {
                maxid = obj.split('+')[7]; 
                newestLine = obj;
                console.log(newestLine);
                return newestLine;
            }
            console.log(newestLine);
            return newestLine;
        });
        console.log(newestLine);
siddesh
  • 41
  • 3