Layers of a webpage
Unlike HTML and CSS, Javascript is a programming language and can perform all sorts of actions. JavaScript is list of instructions to be interpreted and executed by your computer, either by a browser or other JavaScript interpreter (in the command line.)
Layer | Language / File Type |
---|---|
content | HyperText Markup Language (HTML) |
form | Cascading StyleSheets (CSS) |
behavior | JavaScript (JS) |
Javascript can add interactivity to a page by manipulating the DOM (Document Object Model).
- Access the content of the page
- Modify the content of the page
- Program rules or instructions the browser can follow
- React to events triggered by the user or browser
- Use an API via HTTP(S)
Some common interactions JavaScript might detect on a page are:
- Mouseover / Mouseout*
- Click
- Drag & drop
- Scroll
- Input (field entry, slider range)
- Keydown / keyup
- Window resize*
*These interactions can be detected purely with CSS, but for more complex outcomes, JavaScript may be necessary.
Setup
Like CSS, JavaScript can be included within the <head></head>
your html
file as well as linked as an external file. It can also be included at the bottom of your document, right before the closing </body>
tag.
head
of your HTML page:
<!-- Internal JavaScript -->
<script language="javascript" type="text/javascript">
JavaScript code
</script>
<!-- External JavaScript -->
<script language="javascript" src="js/filename.js"></script>
Output
When you instruct Javascript to perform a task, it will usually give you some output, but it won’t automatically display it anywhere. You can verify your result by using the Console of your browser.
<script language="javascript" type="text/javascript">
console.log("Hello World!");
</script>
Comments
As with HTML and CSS, comments are important to keep your code legible — they help you keep notes in regular English on your intentions for each piece of code you write. They’re a great tool to keep track of what’s happening in your script. They also help future you (and others) read and understand your code.
<script language="javascript" type="text/javascript">
// ”//” starts a single line comment.
/* “/*” opens a multiline comment,
and “*/” closes it. */
</script>
Syntax
A script is a series of instructions that a computer can follow one-by-one. Each individual instruction or step is known as a statement. Statements should end with a semicolon (;
) Statements are composed of values, operators, expression, keywords, and comments. Semicolons are not needed after curly brackets }
(except when it is an expression.)
term | description | example |
---|---|---|
values | Fixed values are called literals, such as numbers or texts (strings). Variable values are called variables. | "Hello!" 23 |
operators | Operators determine the relationship between the left and right side of the operand. There are many kinds of operators, such as an assignment operator = , or the addition operator + . |
let x = 5; (5 + 6) * 9; |
expression | An expression is a combination of values, variables, and operators, which computes to a value. The computation is called an evaluation. | (5 + 6) * 9; "Web" + " " + "Design"; x * 10; |
keywords | Keywords are used to identify actions to be performed. For example, the let or var keyword signifies that you are setting up a new variable. |
let x = 5; |
Common Data Types
type | description | example |
---|---|---|
Strings | In programming languages, any textual content that is not part of the programming instructions must be surrounded in single or double quotes (just make sure they match, and that they’re not curly quotes.) |
|
Numbers | Numbers — whether an integer or decimal number — do not need to be surrounded in quotes "" . |
|
Boolean | A binary value of either true or false . |
|
Variables | A variable is a named location for storing a value. That way a changing value can be accessed through a predetermined name. A variable can serve as a container for anything (numbers, strings, booleans, arrays, other variables.) |
|
Variable Naming Conventions
You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.
- Avoid underscores at the start of variable names — this is used in certain JavaScript constructs to mean specific things, so may get confusing.
- Avoid numbers at the start of variables.
- A safe convention to stick to is so-called “lower camel case”, where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words.
camelCase
- Make variable names intuitive, so they describe the data they contain. Avoid single letters/numbers, or big long phrases.
- Variables are case sensitive — so myage is a different variable from myAge.
- Avoid using JavaScript reserved words as your variable names — like
var
,function
,let
, andfor
— since browsers recognize them as code.
Arrays
An array is a data type that contains a group of values. This can be a list of anything—strings, integers, variables. An array is defined by a comma-separated list of items in square brackets []
.
let colors = ["red","green","blue"];
You can access array items by their index, or numerical label, inserted between square brackets[]
. The starting position is 0
, not 1.
The length
property will give you the number of items in an array.
colors[0] // red
colors[1] // green
colors.length // 3
Objects
An object is a collection of data, where each data in the collection has a unique name that identifies it. An object is defined by a comma-separated list of key: value pairs in curly brackets {}
.
let numbers = {e: 2.7183, pi: 3.1416};
Each item in the object has a key and a value. You use the key to get at the value! You can access the value either by a .
before the key or by inserting the key within square brackets []
. If using square brackets, make sure to surround the key in quotes ''
if you’re using a string key. If you are using a variable as a key, you must use the bracket notation.
numbers.e // 2.7183
numbers['pi'] // 3.1416
let myKey = 'e';
numbers[myKey] // 2.7183
Assignment operators
The assignment operator =
assigns the right-hand value to the left-hand operand.
let name = "Beatrice"; // assigns Beatrice to the name variable
name = "Betty"; // updates the value of name to Betty
let count = 5; //assigns 5 to the variable count
count = count + 3; // updates the count variable by adding 3 to itself. count is now 8.
There is a commonly-used shorthand for variables to cumulatively add new values to itself.
count += 3; // same as count = count + 3
count ++; // same as count += 1, or count = count + 1
String operators
The concatenation operator (+
) concatenates two string values together, returning another string that is the union of the two operand strings.
let mystring = "alpha";
mystring += "bet";
// evaluates to "alphabet" and assigns this value to mystring.
let anotherStringVar = 'word';
let concatenated = mystring + " " + anotherStringVar;
//evaluates to "alphabet word"
Comparison operators
Comparison evaluates an expression, returning a boolean, true
or false
. Below are some examples — these are strict comparison formats, meaning they will check both the data type and the value.
operator | description |
---|---|
=== |
checks whether they are equal |
!== |
checks whether they are NOT equal |
< or > |
checks that the number on the left is less than or greater than the right |
Logical operators
Logical operators combine multiple conditions
operator | description |
---|---|
&& |
logical AND 3 < 5 && 2 > 9 // evaluates to false |
|| |
logical OR 3 < 5 || 2 > 9 // evaluates to true, because 3 < 5 evaluates to true |
Conditionals
Conditionals allow you to declare different actions based on different conditions. You can use If if
/ Then else if
/ Else else
logic to define your scenarios.
let x = 2
if (x === 2) {
console.log("x is 2");
}
else if (x === 3){
console.log("x is 3");
}
else {
console.log("x is neither 2 nor 3");
}
Functions
A function is a set of actions to be performed. These can include built-in functions, like console.log
or alert
, or you can define your own function. Most functions are groups of other functions. After declaring a function, you can execute its statements by calling the function. While it’s possible to call a function before it’s declared, it’s best practice to declare your functions before you call them.
// define custom function we called sayHi. This only defines the function and does not execute it.
function sayHi() {
console.log("Hi!"); // native function console.log
alert("Hi"); // native function alert
}
//call (execute) the sayHi function
sayHi();
Parameters and arguments
A function may need inputs to process its statements. These inputs are known as parameters and are used as variables in the function’s statements — you can give them whatever name is appropriate. Arguments are inputs passed into the function when it is called. When you expect a function to provide an answer or output, it’s know as the return value
//sets up "something" as a parameter.
function saySomething(something) {
console.log(something);
alert(something);
}
//call saySomething function via the function name and parentheses ().
saySomething("Hi"); // executes the same statements as before
saySomething("Bye"); // but you can reuse the function
You can also set up multiple arguments
//define function with parameters width and height
function getArea(width, height) {
return width*height;
}
//call getArea function with arguments 3 and 5
getArea(3, 5); //returns 15
Loops
Loops allow you to run a function by specifying the number of iterations you want it to repeat; it uses a counter as its condition to run. There are a number of different kinds of loops. Common loops are the for
and forEach
loop.
For loops use an index counter to keep track of the repeated function. i
is the index, or the count value of the loop. It start at 0
and will increment (i++
) every iteration, until it’s no longer < 3
.
// logs "Hello" in the console 5 times
for(var i = 0; i < 3; i++){
console.log(i, "Hello");
}
// Expected output:
// 0 Hello
// 1 Hello
// 2 Hello
Another is a forEach
loop on array
data types.
const myArray = ['a', 'b', 'c'];
myArray.forEach( (element) => console.log(element) );
// Expected output:
// a
// b
// c
Objects, properties, and methods
Objects are containers for named values, which could properties or methods. Properties are data (see data types above) associated to the particular object, and Methods are specific functions for ane object. Both properties and methods are accessible as keys of the object.
The Document Object
The most important object in JavaScript is the Document Object: it represents an HTML web page.
- Properties describe characteristics of the current web page (such as the title of the page).
- Methods perform tasks associated with the document currently loaded in the browser (such as getting information from a specified element or adding new content).
- Events, such as a user clicking or tapping on an element, can be used as triggers for methods
The Math Object
There is a Math
object in JavaScript can be used to work with numbers, and it comes with several methods. The outputs of these can be scaled to your desired range.
method | description |
---|---|
Math.random() |
generates a number [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive). |
Math.floor() |
returns the largest integer less than or equal to a given number |
parseInt() and parseFloat() |
converts its first argument to a string, parses it, and returns an integer / float / NaN (not a number.) This is useful when grabbing number values from HTML, which is by default processed as a string. To perform Math functions on these values, they need to be converted into a number data type. |
// get a random integer between 2 numbers, including the min and max.
function getRandomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
getRandomNumber(0, 5); // returns a random number: 0, 1, 2, 3, 4, or 5.
Why all this math?
All of these programming concepts may initially seem unrelated to how we think about interaction on the web. One thing we will learn in JavaScript programming, however, is how our interactions are interpreted through numbers—for example, a mouse event is captured through X Y coordinate values on the screen. A scroll event is captured with the scroll distance in pixels. A window resize event changes the pixel width property of the window. Using JavaScript entails capturing the relevant numbers for our interaction effectively, then setting up certain consequences for certain numbers.