JavaScript - Listing Triangle Numbers Flashcards
What is the Code for Triangular Numbers?
<script> for (let n = 1; n <= 20; n++) { let triangularNumber = (n * (n + 1)) / 2; triangularNumbers.push(triangularNumber);} document.write(triangularNumbers); </script>
What is the point of :
?
Starts the Javascript code within a HTML document
What is the point of : for (let n = 1; n <= 20; n++) { ?
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.
What is the point of : let triangularNumber = (n * (n + 1)) / 2; ?
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.
What is the point of : triangularNumbers.push(triangularNumber);} ?
Adds the triangularNumber to the end of the triangularNumbers array. The push method is used to append elements to an array.
What is the point of : document.write(triangularNumbers); ?
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.
What is the point of : </script> ?
Ends the Javascript code within a HTML document