JavaScript - Listing Triangle Numbers Flashcards

1
Q

What is the Code for Triangular Numbers?

A
<script>
for (let n = 1; n <= 20; n++) {
    let triangularNumber = (n * (n + 1)) / 2;
triangularNumbers.push(triangularNumber);}
document.write(triangularNumbers);
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the point of :

 ?
A

Starts the Javascript code within a HTML document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the point of : for (let n = 1; n <= 20; n++) { ?

A

This JavaScript code is setting up a for loop. Here’s a breakdown of what it does:
1. Initialisation : let n=1; - This initializes a variable n to 1. The let keyword declares the variable, and you can think of n as a counter.
2. Condition : n<=20; - This is the condition that the loop checks before each iteration. The loop will continue to run as long as n is less than or equal to 20.
3. Increment: n++ - This is the increment expression, which runs after each iteration of the loop. It increases the value of n by 1 each time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the point of : let triangularNumber = (n * (n + 1)) / 2; ?

A

Calculates the nth triangular number and assigns it to the variable triangularNumber. A triangular number is a number that can form an equilateral triangle. The formula for the nth triangular number is n(n+1) over 2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the point of : triangularNumbers.push(triangularNumber);} ?

A

Adds the triangularNumber to the end of the triangularNumbers array. The push method is used to append elements to an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the point of : document.write(triangularNumbers); ?

A

Printing out the variable triangleNumbers based on the code above, it wont print ‘triangleNumbers’ as a string as there are no quotation marks around the triangleNumbers - not making it a string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the point of : </script> ?

A

Ends the Javascript code within a HTML document

How well did you know this?
1
Not at all
2
3
4
5
Perfectly