Assignment in loop then breaking

Viewed 49

I am coming from a C/Python background and the following JavaScript code is puzzling me. Why is the value of c at the end of the program not 6? Because we are assigning and breaking afterwards. (I have run this on JSFiddle)

function funct() {
  var bytes = new Uint8Array(6);
  bytes[0] = 228;
  bytes[1] = 191;
  bytes[2] = 157;
  bytes[3] = 233;
  bytes[4] = 153;
  bytes[5] = 186;
  bytes[6] = 255;
  bytes[7] = 17;
  bytes[8] = 23;
  bytes[9] = 223;
  var c = 0;
  for (var i = 0; i < bytes.length; i++) {
    if (bytes[i] == 255) {
      c = i;
      break;
    }
  }
  console.log(i);
  console.log(c);
}

funct();

Output:

6
0
4 Answers

Your array is of size 6, but index 6 is the 7th entry. You need to allocate more space for your array:

function funct() {
    var bytes = new Uint8Array(10);
    bytes[0] = 228;
    bytes[1] = 191;
    bytes[2] = 157;
    bytes[3] = 233;
    bytes[4] = 153;
    bytes[5] = 186;
    bytes[6] = 255;
    bytes[7] = 17;
    bytes[8] = 23;
    bytes[9] = 223;
    var c = 0;
    for (var i = 0; i < bytes.length; i++) {
        if (bytes[i] == 255) {
            c = i;
            break;
        }
    }
    console.log(i);
    console.log(c);
}
    
funct();

bytes has 6 elements it breaks at 5 never reach the if statement; on bytes = new Uint8Array(6); you should declare it like bytes = new Uint8Array(10)

You have defined var bytes = new Uint8Array(6) which means it can hold only 6 elements and rest are ignored from bytes[6]... bytes[9]. Which means that ifcondition is never true and loop exist naturally without break.

Hope this helps !!

you are asking for trouble by defining the size of your array:

var bytes = new Uint8Array(6);

instead do this;

var bytes = [];
bytes.push(228);
bytes.push(191);
bytes.push(157);

etc...

or:

var bytes = [228, 191, 157];
Related