M02: Scripting with Node.js
In Module 2, we created a JavaScript file that writes in the console.
What's cool about it is how we combined functions, variables, conditionals, and imported code from other files to output to the console.
Here is our first line of code:
const $messages = require('./m02_messages');
This line assigns a constant to a value from a different page. Here is the code it's assigning.
const $mess1 = 'These are words. Some more words.';
const $mess2 = 'This is a phrase. A very short sentence. A slightly kind of maybe long sentence.';
module.exports = [$mess1, $mess2];
This is the code we called from the other page. "module.exports" is exporting our code and "require.();" is searching for it.
const $parag = require('./m02_func');
We have another constant assigning a value from a different page. Here is the code it's assigning.
const $parag = ($part) => {
console.log(`This is a paragraph made of different stuff. ${$part}`);
};
module.exports = $parag;
This exports a function that passes a string with a parameter to the console.
var $states = 1;
$parag('This is a test sentence. Short and sweet. Mamma mia!');
This assigns the "states" variable to 1. The next line calls the "$parag" function and passes the phrase inside the parenthesis as a parameter.
let i=0;
while (i <= 1) {
$parag($messages[i]);
$states++;
i++;
};
This is a while loop that parses through an array incrementing the "i" variable along with the "states" variable. The "i" is just a simple counter that will stop the loop and "states" doesn't do anything yet. This is the main loop.
const $rating = ($states < 2) ? 'There are lot of statements here.' : 'This is a farly short statement.';
console.log($rating);
This code uses a conditional statement that fires off two different statements depending on if the conditions are fulfilled. Then console.log writes the value in the console.