So far we have been concerned with PHP, a server-side language. The code runs on a server, computes some result or writes to a file or a database, and returns the output to the client (usually your browser). We now focus on a client-side scripting language called "JavaScript". JavaScript code can be written in an HTML document, or external script, or it can be produced by a PHP script, but it does not actually runs until it is executed by the web browser that requested that file.
JavaScript is useful when we want webpages to respond to some sort of user action — like clicking on a certain part of the page, moving the mouse over an image, or pressing a particular key. In fact, these "event-driven" actions are so useful and frequently-desired that JavaScript has built-in functions that are triggered when these events occur. JavaScript, like most modern programming languages, can do arbitrarily complex calculations using the same logical programming structures we met in PHP — conditional statements and loops — with a very similar syntax. Throughout, it's important to remember where the language is being interpreted and executed — for PHP, on the webserver; for HTML, CSS, and JavaScript, on the client device (web browser) itself.
JavaScript code can be writen in an HTML document as the content for a special element: script. This element indicates to the web browser that the content is not HTML, but rather JavaScript, and so the browser's JavaScript interpreter should handle the execution of that code. Here's an example of a block of JavaScript:
<script>
...JavaScript code goes here...
</script>
There are two basic ways to give the user output in JavaScript — the
alert() function, and the document.write() function. The main difference
between the two is that the alert() function will cause a pop-up window to occur with
the information contained inside of it for the user to then close, while the document.write() function will write the data to the HTML document (including any HTML tags). In this way, document.write() is very similar to the PHP
echo keyword. Let's try out both methods for giving the user output now. Create a new
HTML file, and place each of the following JavaScript blocks into the document <body> in turn:
<script>
alert("Hello world!");
</script>
<script>
document.write("Hello world!");
</script>
As we noted above, the document.write() function writes to the HTML document itself, so
HTML tags are perfectly valid inside of the parentheses. Try your favorite tags out around your string,
like so:
<script>
document.write("<b>Hello world!</b>");
</script>
Speaking of strings, it's high time we talk about variables and basic data types in JavaScript. Most of the data types in JavaScript should be familiar.
Variables in JavaScript are declared using the keyword "var" ... but JavaScript doesn't mind if you leave it out. I encoure you however to alwasy use the keyword "var" to define new variables, as this affects the scope of the variables (as we we'll see later), but ultimately, as long as your script does what you want it to do, that's what matters. The first JavaScript data type (that we've already encountered) is the string. Just like in PHP, strings are enclosed in single or double quotes; unlike, PHP, however, there is no difference between the two. In the below code snippet, I'm declaring a variable called "name", and giving it the string value "m123456".
<script>
var name = "m123456";
document.write(name);
</script>
This code will do exactly the same thing as the following two snippets:
<script>
var name = 'm123456';
document.write(name);
</script>
<script>
document.write('m123456');
</script>
The next data type we'll meet is the "number" data type. Unlike PHP (and most other languages), JavaScript
does not differentiate between integers and floating point numbers — they're all just "numbers".
Let's play around with some numbers, and check out the built-in JavaScript function
typeof(), which will tell you what data type a variable is.
<script>
var name = 'm123456';
var age = 42;
var name_type = typeof(name);
var age_type = typeof(age);
document.write(name_type);
document.write(age_type);
</script>
Similarly, the type of a floating point number is still "number", as in the example below:
<script>
var width = 8.5;
var height = 11;
alert(typeof(width));
alert(typeof(height));
</script>
Just as in PHP, numbers that are really big or really small can be written using the "e" character to indicate an exponent. For e.g.,
<script>
var avagadro = 6.022e23;
var real_small = 2.12345e-13;
</script>
JavaScript has Boolean values as well, and their utility is usually most easily demonstrated in conditional statements. There are two Boolean values, true, and false.
<script>
var t = true;
var f = false;
</script>
JavaScript also has an array datatype. While the keyword "array" can be used in creating one, it's actually much simpler to use the following literal notation shown below. Square brackets indicate an array; arrays in JavaScript may be homogeneous or heterogeneous — that is, composed of just one data type, or a mix of data types. In fact, arrays can even have other arrays as their elements.
<script>
var friends = ["Bill", "Doug", "Jim", "Sarah", "Jill"];
</script>
Whitespace is not important; each new array item can be declared on a new line, if helpful for readability:
<script>
var primes = [2,
3,
5,
7,
11];
</script>
As in PHP (and most programming languages), JavaScript affords the programmer with the ability to choose to execute different blocks of code based on some condition. In the code below, we write the variable "name" if the variable is equal to the string "Steve".
<script>
var name = "steve";
if (name == "steve") {
document.write("Hello, " + name);
}
</script>
In the next example, we provide the greeting of the day based on a variable called "time".
<script>
var time = 1600;
if (time < 1200) {
document.write("Good morning, sir/ma'am.");
} else if (time < 1800) {
document.write("Good afternoon, sir/ma'am.");
} else {
document.write("Good evening, sir/ma'am.");
}
</script>
You should notice that the syntax of loops is the same as it is in PHP:
<script>
counter = 0;
while (counter < 5) {
counter++;
}
do {
counter++;
} while (counter < 7)
for (i = 0; i < 10; i++) {
}
</script>
So far, we've mainly concerned ourselves with outputting information to the user with JavaScript, rather than taking information from the user. In real life, the user often needs to give the program some data, however — whether it's their name, address, credit card number, or a variety of other details. In JavaScript, a simple way to do this is by using the built-in "window.prompt" (or just "prompt") function. prompt() displays a pop-up box, with an input field for the user to type something and two buttons, "Cancel" and "OK". Prompt returns the value that a user provided as a string if the user clicks "OK". If the user clicks "Cancel", prompt returns the null value. Let's write a simple "Hello World" program that asks for some input.
<script>
var name = prompt("Tell me your name");
document.write("Hello " + name + ", nice to meet you");
</script>
Notice that we defined a variable called "name", and assigned to it the return value of the prompt — that's the text that the user entered into the text box. JavaScript will convert the string into a number when we compare with a number. For example, it implicitly converts a string that the user enters in the following example to a number:
<script>
var num = prompt("What's your favorite number?");
if (num < 0) {
document.write("Your favorite number is less than 0");
} else if (num == 0) {
document.write("Your favorite number is 0");
} else {
document.write("Your favorite number is greater than 0");
}
</script>
However, JavaScript doesn't always convert the strings that a user enters into a prompt into a number automatically. In the following example, JavaScript keeps the string as a string, and concatenates it to the other string, rather than implicitly converting it to a number:
<script>
var num = prompt("What's your favorite number?");
document.write(num + 10);
</script>
In order to add 10 to the string-number the user entered, we would have to explicitly convert the string into a number type. Luckily, JavaScrip has a built-in function that does just that, called "Number()". You can also use "parseInt()" or "parseFloat()".
<script>
var num = Number(prompt("What's your favorite number?"));
document.write(num + 10);
</script>
JavaScript uses C-style comments, ex:
// this is a comment
/* this is a
multi-line comment */
Similar with CSS, you can write the JavaScript code in a separate file, and then reference it in HTML. Separating files for different functions and purposes supports easy reuse of code and can make debugging easier.
To load a JavaScript file into the browser, vice defining it between the tags, use:
<script src="script.js"></script>
var x, y, z;
x = 7;
y = 9;
z = "abc";
window.alert(x+y+z);
window.alert(z+y+x);
if( x )
window.alert("x true");
x = "seven";
window.alert(x+y+z);
var a, b, c;
a = 1;
b = 2;
c = 3;
d = a + b * c;
window.alert("<h1>Begin</h1>");
if (d < 20)
window.alert("d is okay: "+d);
else
window.alert("d is too high!:"+ d);
d = d - 3;
document.writeln("<h1>Done. Final d = "+d+"</h1>");
/* Return an integer no larger than ‘max’ */
var max = 25;
var value;
do {
value = window.prompt(
"Please enter an integer no larger than "+max);
} while (value > max);
When does this work and why?
Math.abs(x) that returns the absolute value of some number x. Research the
JavaScript function
Math.random() here, looking
only at what the function returns (not the "TryIt!" example), and write a JavaScript program that
"flips" a fair coin; that is, a coin that has a 50% chance of being heads or tails. Instead of printing
out whether it's heads or tails, display an image of a coin's head or tail. Run it several times
to see how many heads and tails you roll!
var now = new Date().getTime(); And, we can get the time (in milliseconds)
at any arbitrary point in time, example:
var now = new Date("May 28, 2021 12:00:00").getTime(); Write a
quick script that will print out the time in days, hours, minutes, and seconds until your Graduation.