Home > database >  Else-if Block not executing
Else-if Block not executing

Time:10-23

The last else if block is not getting executed when the condition is satisfied please help. Thank you.

let rotatingArr = (n, arr, k) => {
  if (n == arr.length && k !== 0 && k <= arr.length) {
    let arr2 = []
    arr
    let delItems = Math.abs(arr.length - k)
    console.log(delItems)
    let modArr = arr.slice().splice(delItems)
    modArr
    arr.splice(-k)
    console.log(arr)
    let result = [...modArr, ...arr];
    return result
  } else if (k == 0) {
    return arr;
  } else if (11 > k > arr.length) {
    k = k - 5
    arr
    let delItems = Math.abs(arr.length - k)
    console.log(delItems)
    let modArr = arr.slice().splice(delItems)
    modArr
    arr.splice(-k)
    console.log(arr)
    let result = [...modArr, ...arr];
    return result
  }
}

console.log(rotatingArr(5, [1, 2, 3, 4, 5], 10))

CodePudding user response:

JavaScript does not support that kind of infix operators. Your code is executing (11 > k) > array.length.

CodePudding user response:

The relational operators (e.g. >) evaluate two values to a boolean.

Therefore, your condition 11 > k > arr.length will be evaluated in two steps:

  1. 11 > k: This will evaluate to either true or false.
  2. (11 > k) > arr.length: This will compare the boolean of the previous expression with arr.length. Because true == 1 and false == 0, this expression will always evaluate to false for arr.length > 1.

You should do these comparisons (11 > k and k > arr.length) in two distinct comparisons, and combine them with a logical operator.

  • Related