JavaScript - Listing Square Numbers Flashcards
What is the code for Listing Square Numbers?
<script> for (let n = 1; n <= 10; n++) { let sq = n*n; document.write(sq + ","); } </script>
What is the point of :
?
Starts the Javascript code within a HTML document.
What is the point of : for (let n = 1; n <= 10; 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<=10; - 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 10.
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 sq = n*n; ?
This line of code means that a new variable sq is declared using the let keyword. The value assigned to sq is the result of multiplying n by itself, effectively squaring n.
What is the point of : document.write(sq + “,”); } ?
Printing out the variable sq based on the code above, it wont print ‘sq’ as a string as there are no quotation marks around sq.
What is the point of : </script> ?
Ends the Javascript code within a HTML document.
Difference Between Square and Cube Numbers when Programming in JavaScript?
The only difference between writing square numbers to cube numbers in Javascript is the 3rd line of code where for squares it would be nn but for cubes it would be nn*n.