100k views
4 votes
What is the value of the totalsString variable after the following code is executed? var totals = [141.95, 212.95, 411, 10.95]; totals[2] = 312.95; var totalsString = ""; for (var i = 0; i < totals.length; i++) totalsString += totals[i] + "

User Alscu
by
7.0k points

1 Answer

5 votes

Answer:

141.95|212.95|312.95|10.95|

Step-by-step explanation:

Reformatting the code snippet and giving it line numbers;

1. var totals = [141.95, 212.95, 411, 10.95];

2. totals[2] = 312.95;

3. var totalsString = "";

4. for (var i = 0; i < totals.length; i++) ";

6.

Line 1 creates an array called totals with four elements.

First element = totals[0] =141.95

Second element = totals[1] = 212.95

Third element = totals[2] = 411

Fourth element = totals[3] = 10.95

Line 2 replaces the value of the third element totals[2] = 411 with 312.95.

Therefore the array totals = [141.95, 212.95, 312.95, 10.95]

Line 3 creates an empty string called totalsString

Lines 4 - 6 create a for loop that cycles from i=0 to i<totals.length

totals.length = 4 (which is the number of items in the array totals)

This means that the loop cycles from i=0 to i<4

During cycle 1 when i = 0, the expression inside the for loop executes as follows;

totalsString = totalsString + totals[0] + "|" //substitute the values

totalsString = "" + 141.95 + "|"

totalsString = 141.95|

During cycle 2 when i = 1, the expression inside the for loop executes as follows;

totalsString = totalsString + totals[1] + "|" //substitute the values

totalsString = "141.95|" + 212.95 + "|"

totalsString = 141.95|212.95|

During cycle 3 when i = 2, the expression inside the for loop executes as follows;

totalsString = totalsString + totals[2] + "|" //substitute the values

totalsString = "141.95|212.95|" + 312.95 + "|"

totalsString = 141.95|212.95|312.95|

During cycle 4 when i = 3, the expression inside the for loop executes as follows;

totalsString = totalsString + totals[3] + "|" //substitute the values

totalsString = "141.95|212.95|312.95|" + 10.95 + "|"

totalsString = 141.95|212.95|312.95|10.95|

At the end of the execution, totalsString = 141.95|212.95|312.95|10.95|

User Dzavala
by
7.1k points