0

Below I have two examples of code. They are the same except I change the value of w at the beginning. In either example, m has a value. All I'm trying to do is set x = m. Why can I do this in the first but not the second? I'm testing this in the console in Chrome (68.0.3440.84)

This works (m = 100| x = 100)

    var c = [],
     w="word",
     x = 0;
        for (l=0; l<w.length; l++){
         c.push(w.charCodeAt(l));
        }
    
    for (i in c) {
     if (c.length > 0) {
            var m = c[1];
            if (m > Math.min(m, c[i])) {
                m = Math.min(m, c[i]);
       x = m; 
       console.log(x);
            } 
        }
    }

This does not work (m = 97| x = 0):

    var c = [],
     w="cancel",
     x = 0;
        for (l=0; l<w.length; l++){
         c.push(w.charCodeAt(l));
        }
    
    for (i in c) {
     if (c.length > 0) {
            var m = c[1];
            if (m > Math.min(m, c[i])) {
                m = Math.min(m, c[i]);
       x = m; //why cant I set this?
       console.log(x);
            } 
        }
    }

There is more I want to do but in my process of figuring out this learning problem I have I have been unable to set this variable x reliably and I'm trying to figure out why.

Filburt
  • 17,626
  • 12
  • 64
  • 115
AGx-07_162
  • 301
  • 1
  • 3
  • 14
  • 1
    `for..in` is for iterating over object properties, not for arrays. For those, use `for..of`. – connexo Aug 17 '18 at 20:47
  • 1
    FYI: `for/in` loops should be used on Objects only, not Arrays as they iterate all the properties of the array. For Arrays, use `.forEach()`. – Scott Marcus Aug 17 '18 at 20:47
  • 1
    For starters, you should be using `for...of` with arrays, not `for...in` [see this post](https://stackoverflow.com/questions/29285897/what-is-the-difference-between-for-in-and-for-of-in-javascript). I'm not sure if that is the cause of your issue, but it certainly doesn't help – mhodges Aug 17 '18 at 20:48
  • I will take that advice and re-write what I'm doing. Thanks for the feedback! – AGx-07_162 Aug 17 '18 at 20:49

1 Answers1

0

It is because if (m > Math.min(m, c[i])) condition is never met. In your example both m and Math.min(m, c[i]) have the same value. Replacing > with >= seems to be fixing your issue. Or moving console.log outside if statement - depending on what you're actually trying to achieve.

var c = [],
  w = "cancel",
  x = 0;
for (l = 0; l < w.length; l++) {
  c.push(w.charCodeAt(l));
}

for (i in c) {
  if (c.length > 0) {
    var m = c[1];
    if (m >= Math.min(m, c[i])) { // because m > Math.min(m, c[i]) would return false
      m = Math.min(m, c[i]);
      x = m
      console.log(x);
    }
  }
}
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18