Home HTML Hacks Data Types Hacks DOM Hacks JavaScript Hacks JS Debugging Hacks

Code Segments

Practice fixing the following code segments!

Segment 1: Alphabet List

Intended behavior: create a list of characters from the string contained in the variable alphabet

Code:

%%js

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var alphabetList = [];

for (var i = 0; i < 10; i++) {
	alphabetList.push(alphabet[i]);
}

console.log(alphabetList);

<IPython.core.display.Javascript object>

What I Changed

I changed the code from i to alphabet i to iterate the first 10 letters of the alphabet instead of listing out the numbers 1-10. This made it so that when you pushed the string it pushed the letters of the alphabet from for values of i from 1-10 instead of just i being the numbers 1-10.

Segment 2: Numbered Alphabet

Intended behavior: print the number of a given alphabet letter within the alphabet. For example:

"_" is letter number _ in the alphabet

Where the underscores (_) are replaced with the letter and the position of that letter within the alphabet (e.g. a=1, b=2, etc.)

Code:

%%js

var alphabet = "abcdefghijklmnopqrstuvwxyz";
var alphabetList = [];

for (var i = 0; i < 10; i++) {
    alphabetList.push(alphabet[i]);
}

let letterNumber = 4;

for (var i = 0; i < alphabetList.length; i++) {
    if (i === letterNumber) {
        console.log('"' + alphabetList[i] + '" is letter number ' + (i + 1) + ' in the alphabet');
    }
}
<IPython.core.display.Javascript object>

What I Changed

I changed the letterNumber value to 4 since lists are counted starting from 0. This made it so that when you output the letter “e” it is the “fourth” character and when listing its placement in the alphabet it is i + 1 with i being 4 so it is the 5th letter.

Segment 3: Odd Numbers

Intended behavior: print a list of all the odd numbers below 10

Code:

%%js

let odds = [];
let i = 1;

while (i <= 10) {
  odds.push(i);
  i += 2;
}

console.log(odds);
<IPython.core.display.Javascript object>

What I Changed

I changed i to be 1 making the starting number odd thus causing every addition of 2 to display a new odd number.

Hacks

  • Complete the first three activities in this notebook