After completing these activities you should be able to:
<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.
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.
prompt( "Hello, World!" );
with Text_IO; use Text_IO;
procedure Hello is
begin
Put_Line("Hello, World!");
end Hello;
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.
// 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 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?
' 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").
var x = 4; var y = 2; var z = x + y; zvar x = '4'; var y = '2'; var z = x + y; ztrue 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.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:
var x = 4; typeof(x);x = '4'; typeof(x);x = true; typeof(x);x = false; Number(x);typeof(x);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:
var x = 1; typeof(x);typeof( String(x) );x = x + x;x = String(x); x+x;typeof(x);x = Boolean(x);typeof(x);
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
|
Comparison Operators
|
Logical Operators
|
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?"); |
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);
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:
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;
} { }) 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:
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 awhile 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.
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.
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.
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. 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.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.
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.
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.