JAVASCRIPT: Variables & Output



Output

In starting any programming language, output is the basic building block. Output allows programs to communicate with and send messages to the user. This page shows several different versions of output that can be performed with JavaScript.

Web Based Output
To output information into a web page using JavaScript, there must first be a target html element in which to push the information. This can be any text element including, but not limited to, div, span, h1-h6, header, nav, footer, main, article, aside, section, etc. It is also necessary that the element have an id attribute with a unique value on the page. Here is an example:
<div id='output'></div>
		    		    
Once the output element is set, output can be written by JavaScript within the script tags. To connect JavaScript with the web code, we use document.getElementById(idvalue). This method will access the html element with the unique id sent into the parenthesis. It is often easier, though not required, to store this reference in a variable.
let outputPath = document.getElementById('output');
		    
Finally, with the connection made between JavaScript and HTML, the desired output can be sent using the innerHTML property. Below are several examples of how to use this property:
document.getElementById('output').innerHTML="Hello";  //this code provides direct access and replaces any code that was previously present
outputPath+=", World";  //this code uses the saved reference and uses += to append output to the information already in the element
		    
A few notes about using innerHTML
  1. We use innerHTML="", with the new content going inside the double quotes.
  2. innerHTML can take a mixture of HTML and text
  3. Any CSS classes identified will be applied with the script executes
Alert Output
The alert() method produces a popup window with informationn inside of it. The alert() method will be called in order as the page is being rendered, often halting rendering until the user dismisses the popup. Alerts are usually used as error or informational messages to users, though they can also be used for debugging purposes. Here are some examples of window.alert() messages:
window.alert("This site is best viewed in Chrome!");
window.alert("This output appears \n on two different lines.");
Note that the window.alert() method takes a string in " ". This is the information to be displayed.
Additionally, note the use of the escape sequence in line 2 to help format the output. An escape sequence is a special code (a backslash combined with a single character) that creates a certain output in programming. Here is a list of common escape sequences that can be used in alert() messages:
  • \n - line break
  • \t - tab
  • \' - single quote
  • \" - double quote
  • \\ - backslash
Console Output
The easiest of the output methods is console.log(). The console.log() method outputs text to a part of the browser called the console. This can be found using the inspector on a regular webpage, or in the console window of your IDE. Console output is text only and will not allow any formatting.
<script>
	console.log("This is my output.");
</script>
		
Note that the console.log() method takes a string in " ". This is the information to be displayed.

Variables

A variable is a programmer created storage item used to hold information from calculations or user input. The use of variables allows our programs to perform the same tasks on different pieces of data each time they run.

JavaScript does not require the type of variable to be declared. In other words, the interpreter doesn't care if the variable holds an integer, string or boolean value.

The process of declaring a variable is giving it a type and name. Since type doesn't matter in JavaScript, we simply begin with the keyword let. This is then followed by the variable name. The name of the variable can be anything that you want, but should follow these rules and guidelines:
  1. It must start with a letter, ideally lowercase.
  2. It can only be comprised of letters, numbers and underscores. No spaces, periods or other keystrokes.
  3. If the name is multiple words, use camelCasing for readability.
  4. The name should be pneumonic, meaning it should describe what is stored in it.
Here are some examples of JavaScript variable declarations:
let firstName;
let gpa;
let isMale;
let age;
let initial;
These declarations simply create the variable. They allocate a location in memory for the information to be stored and label that location with the given name.
Once created, the variables need to be given a value. Giving a variable a value is the process of assignment. The assignment operator in JavaScript is the = sign. The first assignment of a variable is called initializing the variable. Here are some examples:
firstName="Mickey";	//double quotes around string values
gpa=4.0;		//no quotes around decimal numbers
isMale=true;		//no quotes around boolean values of true or false
age=39;			//no quotes around integer numbers
initial='G';		//single quotes around a character value
		
Notice thta the keyword let is not being used here. This is because these variables had already been declared previously in the program. Writing let would declare a new variable with the same name, which is not allowed.
Often times, variable are declared AND initialized in the same statement. Here are two examples:
let lastName="Engel";
let birthMonth=9;


Concatenation

The process of concatenation is linking output items together. In JavaScript, the concatenation operator is the + sign. Concatenation can be used to link multiple strings, literals (actual values), and variables together into one output statement. Here are some examples:
document.getElementById("output").innerHTML="Hello "+"Jim, "+"welcome to the program.");
window.alert("Sorry, but there is no account on file for "+username); 
console.log("My favorite number is "+17);
Take note of the following from the examples:
  • In all examples, there are spaces placed inside of the quotes. Without them, the parts will be linked with no space bwteeen them (e.g. HelloJim).
  • In line (2), the username variable is outside of the quotes. This will allow the program to show the value of the variable, not the variable name.
When creating a long output string with several variables, it is helpful follow this process to make sure concatenation and quotes are placed where needed:
  1. Write the desired output with actual values.
    console.log("Hello, Mickey.  Your username is mickeyengel.");
  2. Replace the actual values with the variables that were declared in the program.
    console.log("Hello, name.  Your username is username.");
    
  3. At each variable place a "+...+" around it (unless the variable is first or last).
    console.log("Hello, "+name+".  Your username is "+username);


One problem to look out for is that the + symbol is overloaded in JavaScript. This means that it is used for addition as well as concatenation. This can present problems as the order of operations will move left to right. See this example:
console.log("The sum of 5 and 7 is "+5+7);
The output of this will be The sum of 5 and 7 is 57. This is because the first + sign encountered from left to right acts as concatenation between the string and the 5 giving us "The sum of 5 and 7 is 5". Then, the next + sign, intended for addition, becomes concatenation because the left is a string and the right is a number.

To fix this, use parenthesis around the addition to override the order of operations:
console.log("The sum of 5 and 7 is "+(5+7));