SY110: Intro to the Web: JavaScript



Intro to the Web: JavaScript

Learning Outcomes

After completing these activities you should be able to:



Computer Architecture Components - Applications
Computer Architecture - Applications. The programs and applications that
are accessed and run by users.

JavaScript and the Web

The previous class introduced the World Wide Web (WWW) and Hyper Text Markup Language (HTML). It served as a foundation for introducing web capabilities and this course continues the same theme by introducing JavaScript (JS). As one of the most popular web programming languages used today, the JS framework builds on decades of features and improvements through widely available libraries and expanding the limitations that a markup language like HTML leaves behind. Simply put, much of the fun, interesting, and dynamic content on modern webpages comes from JavaScript. In order to run JS in HTML, the <SCRIPT type="text/javascript">..</SCRIPT> element is used. Within the Computer Architecture, we are still within the applications component, using browsers to navigate and view web pages.


JavaScript Interpreters

While the intent of this lecture is not to make you a programmer, many students learn better by tinkering with some simple JavaScript code as they go along. Running code in an online interpreter will provide a simple way of executing JS code. There is a simple interpreter on this webpage and on the course resources webpage, but for more robust tools, you may want to try one of the websites below. Some sites (such as JS Bin) allow you to simultaneosly experiment with HTML, JavaScript, and CSS (for web formatting), and even allow you to share code with fellow programmers. If you are stuck on a homework problem, you can run the code through an interpreter to better understand it.



JS Syntax

Programming languages in the DoD
1974: DoD is using 450 different programming languages, spending $3 billion/year on software maintenance ($14 billion in 2012 dollars). A major part of "software maintenance" is fixing BUGS! A search begins for an existing language most suited to DoD requirements ...
1977: No existing programming language is suitable. DoD solicits proposals for a language appropriate for embedded computer applications (i.e., command and control, communications, avionics, shipboard, test equipment, software development and maintenance, and support applications). ["Steelman"]
1980: DoD completes specification of the "Ada" language and subsequently mandates its use. Here's Ada code essentially equivalent to prompt( "Hello, World!" );

  with Text_IO; use Text_IO;
  procedure Hello is
  begin
    Put_Line("Hello, World!");
  end Hello;

1996: DoD now uses only 37 different programming languages. New code continues to be written in ADA, which is easier (thus less costly) to maintain: Ada was designed to be less prone to the kind of bugs that make software vulnerable to attack.
Today: Ada code is executing on US Navy systems such as the Aegis Weapon System, SSN-21 AN/BSY-2 Submarine Combat Control System, V-22 Osprey, AGM-114 Hellfire missile, CH46 Cockpit Control System, Tomahawk missiles, MK 41 Vertical Launch System.

Every programming language has a defined syntax, or set of rules with how the language is constructed. Understanding JS syntax will help build on the understanding of problems and challenges with programming and development, especially in more complex situations. Just as HTML has a structure and tags, JS syntax is very simple.

  1. JS is case sensitive
  2. Semicolons end statements in JS
  3. The name of functions and variables should start with lowercase letters
Starting a line with the sequence of characters // allows programmers to provide comments in the code, where the program ignores text that follows. If a programmer needs to comment across multiple lines, the sequence /* .. */ can be used. Commenting allows programmers to document the purpose of code in plain language, which can be very useful when looking at hundreds of programs and thousands of lines of code. (Comments can also be very revealing in both offensive and defensive operations, such as revealing the username (cyber-persona) of a developer, or accidentally revealing a system password.) We will not do a deep dive into all the intricacies (or associated vulnerabilities) of JS, but by understanding its basic syntax and use, we will be able to convey cybersecurity challenges across a wide spectrum of topics.

Below is a basic example of JS code that properly meets syntax requirements and provides comments for someone else reading the code:

// This is an example of commenting a single line within JS code

/* This is an example of commenting multiple lines of JS code.
  Comments are ignored by the program and allow for organization and
  documentation of code. */

  var x = 0;    // x is used as a counter to end the loop
  var sum = 0;  // sum is used to store summation values

  // summate each value from 1-4
  while ( x <= 3 ) {
    x = x + 1;
    sum = sum + x;
  }


Variables and Data Types

Variables in programming, like in math formulas, represent a temporary value. Variables are typically declared in programming languages to allocate memory with the intent to store data. Declarations in JS are written as var x;, where x is now a named variable. Any string of characters can be used as a variable, such as var firstName;. Once a variable has been declared, values can be assigned later in the program using various expressions and operators. An example on this very website is a variable named ygYYYY, which holds the value of the current plebes' graduating class year (e.g., "" right now). By making this a variable, the website's developer can update the value once when the next plebe class arrives, and subsequent references to the variable will change, as opposed to manually finding and replacing every instance of "" next year.

Knowledge Check: When declaring variables in a program, where are the values stored?

JavaScript Interpreter

Input a JavaScript expression or statement and press Enter
js>
  
This course will focus on three data types within JS: (1) number, (2) string, and (3) boolean.
  1. Number. These includes integers and decimal numbers (also known as floating-point numbers). Unlike some other programming langues, JS does not require a user to specify the type of number (integer or floating point) when declaring a variable.

  2. String. These values are represented as a sequence of characters and bounded with single quote ' or double quotes " when assigning or using within an expression. Recall from the Numeral Systems in Computing class that ASCII characters are represented as binary values. Smaller strings can be combined into a larger string, in a process known as concatenation (e.g., "King" and "Hall" would be concatenated into the larger string "KingHall").

    Enter the following lines into the interpreter to observe their outputs:
    • var x = 4; var y = 2; var z = x + y; z
    • var x = '4'; var y = '2'; var z = x + y; z


  3. Boolean. These data types return true or false values and can often be used in expressions. Their values can also be represented in numeric form as booleans, where true = 1 and false = 0.


To check a data type, the typeof() function can be used along with the variable. Enter the following examples into the interpreter to observe how the application identifies data types for variable x:

Type conversions are available to change data types stored in variables by using the Number() or String() functions. Enter the JS code in the sequence listed and determine the data type or value that should be returned before hitting the enter key in the interpreter:
  1. var x = 1; typeof(x);
  2. typeof( String(x) );
  3. x = x + x;
  4. x = String(x); x+x;
  5. typeof(x);
  6. x = Boolean(x);
  7. typeof(x);

1202. What's that?
It started with error code 1201, which was ignored because Eagle was about to land on the moon. Equipped with 2 kilobytes of RAM and 32 kilobytes of storage, no wonder the Apollo Guidance Computer ran out of memory and started to display warnings in the cockpit. "Give us a reading on the 1202 program alarm," stated Neil Armstrong. At the age of 23, Don Eyles wrote part of the computer code for the lunar lander and was at the heart of addressing the issue. Learn more about this infamous software error [YouTube Video].

Statements, Expressions, and Operators

Statements perform actions whereas expressions leverage operators to produce values. This construct in programming can achieve some amazing things, such as sending humans to the moon 🚀

There are several groups of operators that can be used within JS, with two that have already been used and on a short list:

    assignment operator of =, which stores a value in a variable
    type operator of typeof, which returns the type of variable

Combining multiple operators results in an expression. x = x + 1; is a simple line of code that contains a variable, an assignment operator that increments x by 1, and an arithmetic operator. If x held the value of 11, after executing that line of code it would hold the value of 12. (It does not try to solve an equation where x = x + 1;!) If, instead, the line of code read x == x + 1, then the comparison operator == would make the program evaluate whether or not that line of code was true - and if x held the value of 12, the expression evaluates to a boolean value of false. We will see how such evaluation could be used to control a program in the Loops and Conditionals section.

Arithmetic Operators
Operator Description
  +Addition
  ++Increment (adds 1)
  -Subtraction
  --Decrement (subtracts 1)
  *Multiplication
  **Exponentiation
  /Division
  %Modulo division (calculates the remainder)
 
Comparison Operators
Operator Description
  ==equal to
  !=not equal to
  >greater than
  <less than
  >=greater than or equal to
  <=less than or equal to
 
Logical Operators
Operator Description
  &&logical and
  ||logical or
  !logical not

Input and Output Functions

The input, processing, and output concept from the Computer Architecture class also applies to applications through computer programming. For simple webpages, JS uses two functions to be able to handle information with prompt(); used for inputs and alert(); for providing outputs.

Input function. The prompt("Your message here"); function will create a pop-up box containing an optional message to the user, a text box into which the user can type a string, with "OK" and "Cancel" buttons. A message can be provided to the user indicating what input is supposed to be provided, such as a question or phrase. Whatever string the user enters in the text box gets returned as the value of the prompt(); function when "OK" is selected. To save a user's input, we store the value that is returned by prompt(); as a variable like in the third example below.

Create a plain input box: prompt();
Create an input box with a message:   prompt("What is your name?");
Create an input box with a message and save the result:   var s = prompt("What is your name?");
It is important to point out that the prompt(); data type will return a string. If we want to get a number from the user to use in a mathematical calculation, we need to convert the string provided by the user into a number, for example:

var input = prompt("How old are you?");
var age = Number(input);


Output function. Almost every program with which you interact on a daily basis on your computer has some means of providing data back to the user. This output may be in the form of changing the graphics in a window, displaying text, or causing a pop-up box to appear. To provide feedback in our programs to the user, we will take advantage of a function in JavaScript called alert();. The alert("Your message here") function will create a pop-up box containing an optional string message to the user and an "OK" button to close the window. Here is a simple example of using the alert() function:


If we combine both input and output, we can generate programs that take input, perform calculations based on that input, and provide output dependent on the input.


Loops and Conditionals

Loops allow a simple program to execute the same code repetitively until a certain condition is met, enabling a short program to do a lot of work.

Suppose we want to add the numbers from 1 to 10. We could use what we learned above and write (1+2+3+4+5+6+7+8+9+10); ... but that doesn't scale well to a program that adds up the numbers from 1 to 1,000 or 1 to 1,000,000. Instead, we will phrase the problem in a way to allow us to repeatedly run a few lines of code until some condition is met.

Let's reframe our solution to adding the numbers 1 through 10 as so: suppose we had variables var total = 0; and var k = 1;. We could then imagine doing the following steps over and over:
Add k to total and increase k by 1. If we do this up to and including when k is 10, we will have added up the numbers from 1 to 10.

In JavaScript, we execute some section of code (called a block) over and over again using a while statement. Using a while statement looks like this:

 var total = 0;
 var k = 1;
 while(continuation-condition) {
   total = total + k;
   k = k + 1;
 }        

The code inside the block (e.g., between the { }) is called the loop body, and it's repeated over and over until what is inside the ( ), also known as the continuation condition, is no longer true. Just as we saw basic arithmetic operations available to us above, JS can also compare numbers using familiar symbols: > (greater than), < (less than), >= (greater than and equal to), and <= (less than and equal to). Finally, JavaScript can also use two equal signs, ==, to compare if two values are equivalent. In the example above, we want to loop as long as k is less than or equal to 10, which gives us this program:

ProgramMessages

 

Activity: Modify the above program to compute the sum from 1 to 1,000.
The Best Jobs Need Programming
Several of the top jobs in 2023 U.S. News & World Report's "100 Best Jobs" list require programming skills!
  • Software Developer (#1)
  • Information Security Analyst (#5)
  • IT Manager (#8)
  • Web Developer (#9)
In terms of programming languages, JavaScript is the most sought after programming language desired by employers per this UC Berkeley 2021 Study.


With these skills, you can create interactive programs to request, store, and manipulate user input and provide some calculated output back to the user. That's neat, but truly powerful programs go a step further with conditional statements (or conditionals). Conditional statements allow different parts of a program (i.e., different lines of code) to execute depending on whether or not certain conditions are met. Just as the while(); loop continues to run the code in the loop body while the continuation-condition is true, conditional statements use a similar syntax to choose what code is run depending on a condition. To build a conditional statement in a program to control what code is run, we use the conditional words if and else in conjunction with a condition. The if is required, but the else is optional. A generic conditional statement has the following form:

if(condition)
{
Block 1: This code is run if the condition is true
}
else
{
Block 2: This code is run if the condition is false
}

We now have the tools to create powerful programs that can make decisions during execution without programmer involvement:


If we combine a while loop and some conditional statements, we can see the power of just a few lines of code. Below is a guessing game in which the user has to guess the right number between 1 and 10.


The block of code in the while loop is repeated, allowing the user to continue guessing numbers until the conditional statements determine that the user's guess (guess_number) is not larger or smaller than the secret number. While this is obviously a very simple program, the concept of analyzing inputs, outputs, loops, and conditionals is fundamental to understanding a program's purpose, functions, limitations, and vulnerabilities.

Security Vulnerabilities

We will finish this lecture with a simplified discussion of how security vulnerabilities can emerge from common programming mistakes. Consider the simple guessing game from earlier. What happens if a user provides an input that is not a number? In this case, the conditional statements behaves unexpectedly, and the program declares the user a winner, despite an incorrect guess. This occurs because code was not written in a way to handle all possible input types. When programs fail to account for unexpected inputs, they may behave incorrectly, crash, or even expose security flaws.

Many software vulnerabilities arise not from malicious code, but from simple human oversight during development. Without diving into the technical details of JavaScript, let us look at several high-level logic vulnerabilities that can occur in any language — especially when user input is involved.

  1. Not considering all inputs. Unexpected input can lead to all sorts of unintended behavior — from program crashes (affecting availability) to incorrect outputs (affecting integrity). Programmers should account for a wide range of input types, including strings, numbers (positive and negative integers, floating points, and very large numbers), boolean values, special characters, and even empty, null, or undefined values.
  2. Mishandling edge cases. Sometimes a program works perfectly for the vast majority of cases, but not a small handful of unique circumstances. This commonly happens at the edge cases, usually the first or last input in a program, or special values (like zero). In 1997, the USS Yorktown experienced a serious failure when a sailor entered a zero as input. The program attempted to use that value as a divisor, triggering a calculation error that cascaded through the ship’s network and disabled key systems for hours — leaving the ship dead in the water.
  3. Logic errors (ex: off-by-one errors or "fencepost errors"). This one seems simple, but humans are imperfect, and so is the code they create. A famous example comes from OpenSSH, a tool used for managing remote connections (including an implementaiton of SSH, which you used in Lab 2). A version of OpenSSH contained an incorrect conditional statement - it read if (id < 0 || id > channels_alloc) { when it should have read if (id < 0 || id >= channels_alloc) { . This error contributed to a vulnerability where a normal user could gain full administrative priviliegs on a target.
  4. Input type mismatches and type coercion. We discussed data types (numbers, strings, and boolean values) earlier, and we return to them again here. In JavaScript, adding a number and a string results in a string concatenation operation, so 17 + "76" results in "1776" (a string), not the number 93. (This behavior varies with different programming languages.) Another quirk is that 0 is treated as false, but any non-zero number is true. These behaviors aren't inherently unsafe, but if a programmer assumes a value is a number when it's actually a string (or vice versa), it can lead to broken logic or incorrect program behavior.
  5. Precision issues. This final issue is a bit more technical. You’ve learned how to convert positive integers between base 2 and base 10 — but representing floating point numbers (e.g., fractions) in binary is trickier. For example, in JavaScript, 0.1 + 0.2 is 0.30000000000000004, not 0.3. This isn't a bug — it's a limitation of how floating-point numbers are stored. That tiny error might seem harmless, but in certain applications - say, targeting systems for long-range missiles or financial systems processing large transactions - it could have major consequences. You do not need to memorize the process for calculating floating point numbers; instead, recognize that even powerful computers have limits, and attackers may try to exploit those limits.

While these descriptions may seem overly simplified, the issues discussed here aren't just theoretical — they're real mistakes that affect real systems. With modern systems involving thousands, possibly millions of lines of code, you can easily imagine how difficult it would be to identify all mistakes in a program.

Code Examples

To help reinforce this idea, we will look at some shorter code examples that have critical but not obvious flaws. There will be two code examples side-by-side that seem to perform the same function, but one of the two will fail in certain cases.


  • Adding Up Numbers from 0 to N
  • Both programs will properly add up the numbers between 1 and some number provided by the user. However, what happens when the user provides a negative number as an input to the program? The program on the right will not perform any calculation and simply output a total value of zero, which one might argue is not the correct, or anticipated, behavior. The program on the left suffers much more significantly as it enters an infinite loop that will eventually crash your browser window.


  • Withdrawing Money from an ATM
  • Both programs are simplified examples of what might be running on the nearest ATM. Starting with an initial set balance, they allow the user to withdraw a user-defined amount of money from their account. What happens if you try to withdraw a negative amount of money? Think about how the user providing a negative value will affect the arithmetic calculation balance = balance - n;. If n is negative, then the balance will go up! While most ATMs don't have this specific vulnerability, ATM software has been susceptible to multiple hacks.


    Supplemental Media:

    What is JavaScript?



    Want to learn more about programming?

    There are loads of great websites and tools available for beginners to learn more about programming - one of the best is Codecademy, which offers a free introductory course in JavaScript for beginners.


    Review Questions:

    1. Why is JavaScript important in the context of the web?
    2. What are the different JS data types and how are they used? Why is it important to understand the behavior of different data types when writing JavaScript code for web applications?
    3. What is the syntax to assign a variable?
    4. What comparison symbols are used in JS and what do they mean?
    5. What is a programming loop used for and what does a loop control variable do?
    6. What are some simple examples of security vulnerabilities that can result from careless JavaScript coding, even in a small program?