10print

variations

In class we learned that we could write our 10print algorithm using a while loop like the example above, but we could also use a for loop like the example below. Both produce the same output, but the for loop allows us to write our instructions with less code. Let's explore other variations on this same sketch to learn a bit about how JavaScript can be written a number of different ways to express the same idea.

Let's create a p() function in order to set ourselves up for some other code variations down the line. This function will take care of "printing" (ie. outputing) our text to our document's body.

In the example above, we defined our p() function using the declarative approach, this is the most conventional way, but we can also define it as a function expression, which looks more like we're defining a variable (like all variables creating a function is really about storing data in memory and assigning it a name, in this case the datatype we're storing is a "function", rather than a "number", "string", etc). There is nothing functionally different about these two approaches, it's just different syntax which allow us to use functions in different ways/contexts.

Here is yet another way to create that same function, this variation is known as an arrow function, notice the absence of the function keyword and the presence of the => between the function's parenthesis () and its brackets { ... }

Arrow functions do behave a little different from the traditional declarations (refer to this MDN page for more on that), but for our purpose of exploring variations on this code, what's most interesting is that they can be written evern more compactly. When an arrow function only has one line of code in it's code block (ie. between its brackets) it can be written like this

Similarly, when an arrow function only contains a single parameter between its parenthesis () then we don't actually need to write the parenthesis

Now that we've tightend up our function, let's do the same with the rest of our code

When conditional statements only have 1 line in their code block, their brackets can also be omitted and the statement can be written on the same line

When we have an if / else like this which is a simple "either / or", we can write both on the same line using a ternary expression like this

Just like functions and conditoinals, when a for loop only has a single statement in its code block (as it does now) we can also omit the brackets and write that on the same line.

This code produces the same exact output as the first example, except now we've written our insructions in just two lines of code. This version is real compact, but it's also not the most readale code. The sweet spot is probably somewhere inbetween. The purpose of these variations is not necessarily to end up at this last version, but rather to learn how the same instructions can be written in a number of different ways