Caesars Cipher 'for loop and if statements'

Caesars Cipher 'for loop and if statements'
0

#1

Tell us what’s happening:

Your code so far

function rot13(str) { // LBH QVQ VG!
  charArr=[];  
  rot13CharArr=[];
  for (i=0; i<str.length; i++){
    charArr[i]=str.charCodeAt(i);  
  }
  charStr=charArr.join(); 
  
  for (i=0; i<charArr.length; i++) {
    if (64<charArr[i]<78){
        rot13CharArr[i]=String.fromCharCode(charArr[i]+13);
    }
    else if (77<charArr[i]<91) {
      rot13CharArr[i]=String.fromCharCode(charArr[i]-13);
    }
      else if (charArr<65 || charArr>90) {          
        rot13CharArr[i]=String.fromCharCode(charArr[i]);
      }
  }
     

  
  return rot13CharArr;
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:


#2

The following is not comparing what you think it is comparing:

if (64<charArr[i]<78){

You will need to rewrite the above and the other 2nd else if like:

if (64 < charArr[i] && charArr[i]  < 78){

#3

Thank you for letting me know.

What should I search in MDN to find out more about these rules for comparatives in javascript?


#4

#5

Thank you for this. Finally able to complete this section with the below code.
I’m having trouble understanding why i cant use a range (i.e. a<var<b). Is it because it’s nested within an if statement? are there other cases when I have to use && and ||?

I know. I should really be searching this instead of asking :sweat:


#6

Let’s say we have the code:

var min = 3;
var max = 10;
var val = 2;

Let’s say I want to check if val is greater than min AND less than max. You are thinking you should write:

if ( min < val < max ) {

JavaScript uses operator precedence determines which expression gets evaluated first. Both operators are <, so the left comparison is made first. JavaScript will end up grouping the expression as:
(min < val) < max

So, in our example, the left most part ( min < val ) evaluates 3 < 2, which evaluates to false.

Next, we are left with false < max. Because of the comparison operator <, false gets coerced into the number 0 (true would be the value 1). So, since 0 < 10, the overall expression evaluates to true.

The main point to learn here is when you have two comparisons of the same value (min < val < max), you have two break it down into two comparisons for JavaScript to evaluate it correctly. So since you really want to make sure both conditions (min < val AND val < max,) are true, you must write it as:

if (min < val && val < max) {

#7

Fantastic.
I understand it so much better now.
Couldn’t ask for a better explanation.