Like Progressive Metal? Check out my band on Spotify, please follow us!
Variables are an important part of any program or script. A variable is a simple way to refer to a chunk of data in memory
to create a variable, we simply put in our script:
var variableName = value
The text "variableName" can be anything you want, as long as it only contains numbers, letters and/or an underscore "_". A variable name also
cannot start with a number. After the equal sign you put the value.
Let's revise our original script to use a couple of variables as such:
To access the values in an array, you use the  operator. For instance, to access the first item in an array named args, you would access args. Which would return the first variable passed into the script. The arguments passed to the script are stored in the array starting with index 0. Let's make our script take the 2 arguments name and age which will be indexes 0 and 1 respectively. We can assign these values to a named variable and then print them. We will create a 3rd variable called "diff", which will hold the number of years until you will be 100 years old.
#!/usr/bin/env node //Years till 100 script var args = process.argv.slice(2); var name = args; var age = args; var diff = 100 - age; console.log('Hello ' + name + ', you will be 100 in ' + diff + ' years!');
Give this program a name of years.js, be sure to give it execute permission and then run it with the following command:
./years.js Joe 25
This will print the text "Hello Joe, you will be 100 in 75 years!"
This script works well, but it does have some problems. For instance, what if you are 102 years old? What if you don't enter a name or an age on the command line? The script will either crash or print nonsense data. In order to fix this script, we will need to make use of the if and else keywords, which are covered in the next section.
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6