Open CheatSheet Back To List Next Tutorial

The JavaScript programming language

Intro

This is the first in a series of tutorials on JavaScript. The series is broken into Beginning JavaScript and Intermediate JavaScript.

Beginning JavaScript: The first two tutorials cover Beginning JavaScript.
  • We are currently in the first Beginning JavaScript tutorial. It covers the basics of the JavaScript programming language.
  • The second tutorial is a project where you incorporate the Beginning JavaScript concepts into a simple To-Do list application.
  • It is important to have an overall understanding of all the basic concepts before moving on to the Intermediate JavaScript tutorial. Go through the Beginning JavaScript CheatSheet, the flashcards, and the To-Do list project. Using the forest and the trees analogy, having a solid understanding of all the basic concepts covered in the beginning tutorial will give you a view of the forest. In the intermediate JavaScript series we will focus on the individual trees.

Intermediate JavaScript: There is a whole series of tutorials each focused on a major topic.
  • This series is intended to get you to a highly proficient intermediate skill level by focusing on topics that you will need to be familiar with and excluding advanced topics that you are less likely to use.
  • This series also ends with the same To-Do list project from the Beginning JavaScript series but modified to include more advanced topics.  
  • After each tutorial, go through the matching CheatSheet category. Make sure you understand each topic. While you should memorize the Beginning topics, for many or most of the Intermediate topics you only need to be be able to reference them in the CheatSheet when needed for your own projects.



Work environment Setup

  • The only things you need to start coding JavaScript are a web browser, a text editor, a Terminal application, and Node.js. 

A Web Browser with Developer Tools
  • All browser have Developer Tools that include a console tab where you can view console logs, or directly execute JavaScript code.
  • To open The Developer Tools console from any web page:
    • Mac: Press Command+Option+J
    • Windows and Linux: Press Control+Shift+J  
    • Any OS: Right click anywhere on the page > select Inspect > click the Console tab.
  • Test it out by entering:
    • let x = 7;
      console.log(x + 3); // logs 10

Visual Studio Code text editor
  • Both Macs and PCs ship with some very basic text editors. But these are not sufficient. There are a number of free and paid text editors. We recommend using the free and very popular Visual Studio Code. Download from code.visualstudio.com/download
  • It has three features we will be using:
    • A built-in Terminal panel you can open to enter commands in the command line without having to open a separate Terminal application. 
    • A built-in Debugger sidebar that allows you to set breakpoints in your code, pause the program, and inspect variable values.
    • A plugin called Live Server that will launch a local web server to use in development.
  • VS Code is not required however, so if you are already a programmer happy with your text editor, you can follow along using that, plus your Terminal application and the DevTools source tab for Debugging. Or use console logs. 
  • There is a separate CheatSheet and tutorials for VS Code and VS Code's debugger feature. 

The Terminal
  • In some cases we will be using the Terminal to enter commands and launch files from the command line. If you are not familiar with the Terminal there is a separate CheatSheet and tutorial on Unix that covers the Terminal in depth. But for now all you need to know is:
    • Mac ships with an app to access the command line called Terminal. 
    • Windows ships with an app called Powershell, although you can install others such as the Bash shell for Unix. 
    • VS Code has a built-in Terminal window. To open it click the Terminal menu and select New Terminal.
    • Once the Terminal is open, you can see what directory you are in by entering: pwd
    • You change directories with the cd command followed by the path to the file or directory you want. Your home directory is represented by "~/". To go from your home directory to the Documents/javascript-tutorial/general directory for example enter: 
      • cd ~/Documents/javascript-tutorial/general 
    • Generally this tutorial series will refer to the command line interface as the Terminal, but it can also be called the Console, the CLI (command line interface) or the Shell.

Node.js
  • There are two main environments for running JavaScript code, the browser and Node.js. The browser environment is mainly for using JavaScript to access and manipulate web pages. The Node.js environment is often used for running web servers. There is a separate CheatSheet and tutorial series for Node.js.
  • To see if Node.js (or just Node) is installed on your computer, open the Terminal and enter: node
    • If you get a prompt you can start entering JavaScript code directly in the Terminal. 
    • Or run a file by entering "node" followed by the file name node filename, or the path to the file if it is in a different directory: node path/to/file

  • If it returns "Command not found" then you need to install Node.js. Go to nodejs.org and download and install the LTS version.


Project setup

  • For this tutorial series create a project directory called javascript-tutorial.
  • Open the javascript-tutorial directory with the VS Code text editor.
  • Create a JavaScript file to test code with. You can call it anything such as try.js.
  • Then type or paste in the code from this tutorial.
  • Open a Terminal window by clicking the Terminal menu and selecting New Terminal.
  • Run the file with the node command: node try or whatever file name you choose. The .js extension is implied.
  • To see variable or expression values put console logs in the code. It will log the value in the Terminal: 
    • const x = 7;
      const res = x + 3;
      console.log(res); // logs 10


Beginning JavaScript 

  • The rest of this tutorial will cover key concepts in the JavaScript programming language. This is the bare minimum that you need to know to program with JavaScript. It is important to learn all of these concepts before moving on the the Intermediate JavaScript tutorial series. You will need to go through this a minimum of two times since the concepts are interrelated. If you take the intermediate JavaScript course you should memorize all the Beginning JavaScript concepts including the syntax, although for now make sure you just understand what they do. 
  • The next tutorial is a project where we put most of these concepts to use. 
  • Type or paste the example code in the javascript-tutorial to see it in action. Add your own console.log()s to see the values. 

  • The concepts you need to learn include:
    1. Data Types
    2. Variables
    3. Expressions and Operators
    4. Booleans and If Statements
    5. Functions
    6. Strings
    7. Objects
    8. Classes
    9. Arrays
    10. The DOM: Using JavaScript to manipulate web pages.

What is JavaScript?

JavaScript is a programming language run in web browsers and on servers.

JavaScript (often shortened to JS) was first released in 1995 as a simple programming language to run in the Netscape Navigator web browser to manipulate HTML elements without having to reload the page. Shortly afterwards official standards were released to enable JavaScript to be run in any web browser. 

Besides the unique feature of being run in the web browser and interacting with web page, JavaScript also has all the features of a standard programming language. It has variables, functions, if statements, data types, objects, arrays, etc. We will cover the basics of all these in this tutorial.

In 2009 Ryan Dahl created the Node.js runtime environment that lets you run JavaScript programs outside the browser and interact with the host computer's operating system. Since then JavaScript has become a prominent language for running web sites on the server side. There are other languages used to run website on the server side such as Python, PhP, Ruby, and Java. But only JavaScript can be run both client-side (in the browser) and server side. 

JavaScript Syntax

Example code:
// Reference the below code snippet for the syntax explanations.
const name = 'Joey';
if (name === 'Joey') {
  console.log('My name is Joey');
}

  • Statement: A line of code that instructs the computer to execute some action. Programs are formed by a sequence of one or more statements. Statements are often grouped into blocks such as functions or if blocks.
  • Code Blocks: Blocks are a sequence of statements that execute together. Blocks include functions and if statements. They are enclosed in curly braces { }.
  • Indentation: Indent your code two spaces to make it easier for you or others to read. Set up VS Code to use soft tabs so you can press the tab key and it will indent two spaces.
    • In the above example there is an if block that contains one statement. Indent the statement with two spaces to show that it is inside the block.
  • Comments: // single line /* multiple lines */ You can use comments to give short explanations about the next line or block of code. You can also use comments in development to temporarily "comment out" code you are working on.
  • Semicolons: Put semicolons at the end of each statement. Do not put semicolons at the end of code blocks (i.e., do not put a semicolon after the closing curly brace.
  • Double vs single quotes: Text strings must be put in double or single quotes. You can use either but style guides recommend single quotes. Use double quotes if your string includes one or more single quotes.

1. Data Types

Programming languages handle data differently depending on what type of data it is. 
JavaScript has 8 data types including 7 primitive data types and an object data type.

The most commonly used data types are:
  • String: text surrounded by quotes. Example: "Hello"
  • Number: numeric values. Example: 7
  • Boolean: true or false
  • Undefined: variables that have not been initialized with a value are undefined.
    • Example: typeof x; // returns undefined since x has not been initialized.
  • Null: Null is the intentional assignment of no value to a variable. let x = null;
  • Object: An object is an unordered collection of properties written as name:value pairs. 
    • Example: { name: 'Joey', age: 22 };
    • Arrays and functions are a type of object.

The typeof operator will return the datatype of a value: 
typeof "Hello"; // returns 'string'
typeof 7; // returns 'number'
typeof true; // returns 'boolean'
typeof false; // returns 'boolean'
typeof x; // returns 'undefined', x is a variable name that has not been declared.
typeof { name: 'Joey', age: 22 }; // returns 'object'
typeof [1, 2, 3, 4]; // returns 'object'. Arrays are a type of object.


2. Variables

Variables are containers that store values in memory.

Declare a variable: You declare a variable with the keyword let or const followed by an identifier (i.e., the variable name): let x
Initialize the variable: You initialize the variable with a value with an = sign followed by the value: let x = 7;

To get the variable's value, just enter the variable name:
x; // returns its value, 7

const vs let:
  • The difference between variables declared with const vs let is const variables can't change their value, but let variables can. 
  • Use const unless you intend to change the variable's value.
  • For let variables, only use the let keyword when you declare the variable. After that just use the identifier.

Example using let:

let result = 0;
result = 8 * 2; result; // returns 16 result = 4 + 9; result; // returns 13

Scope
Scope relates to where variable values can be accessed.
  • Script scope / Local scope: Variables declared in your JavaScript file that are not inside of a block (e.g., not inside a function or if statement) are scoped to the whole script. The variable is available anywhere in your script's code after it is declared. This is called script scope if you are running JavaScript in the browser and local scope if you are running the file with Node.js.
  • Block scope: Variables declared inside a block (e.g., inside a function or if statement) are locally scoped to that block. That means they can only be accessed within that block.

Example:
In the below example, x is script scoped. It is available anywhere in your script after this point. Y is block scoped. It is only available within this if block.
const x = 1;
if (x > 0) {
  const y = 2; y; // returns 2
}
x; // returns 1
y; // throws ReferenceError: y is not defined

  • To set the value of a variable in an if statement, declare it outside the if statement.
Example:
let result
const score = 80;
if (score > 60) {
  result = 'Pass';
else {
  result = 'Fail';
}
result; // returns 'Pass'

Primitives are stored by value
Variables assigned to primitive values such as numbers, strings, and booleans are stored by their value.
In the below example x and y are assigned to numbers which both resolve to the value 1.

Examples:
  • In the below examples variables x and y are assigned to values the resolve to the value 1. When you compare the variables you are comparing their values. They both hold the number 1 so x and y are equal.
const x = 1;
const y = 3 - 2;
const res = (x === y); // returns true. They both store the value 1. The values are equal.

  • Below is another example where the values are assigned to the string "hello".
const str1 = 'hello';
const str2 = 'hello';
const res = (str1 === str2); // returns true. They both store the value "hello".

Objects are stored by reference
  • Objects are stored in heap memory. Variables assigned to object values don't store the object value itself, they store a reference to the memory address. This applies to arrays and functions as well since they are a type of object.

Examples:
  • The below variables are assigned to objects which get stored in heap memory. The variable holds the reference to the object in memory, not the object itself. As such obj1 is not equal to obj2 even though the object properties are identical. 
const obj1 = { name: 'Joey', age: 22 };
const obj2 = { name: 'Joey', age: 22 };
let res = (obj1 === obj2); // returns false

  • The below example assigns variable objCopy to the value of obj1. Since the value is their location reference value, they are equal. They both contain the same reference value.
const objCopy = obj1;
let res = (objCopy === obj1); // returns true


3. Expressions and Operators

Expression: An expression is any valid unit of code that resolves to a value. For example: 4 + 3 is an expression that resolves to 7.
Primary expressions: Literal values are expressions that cannot be evaluated further. For example the number 7 is a literal number value. It is still considered an expression, but since it is already at the lowest level, it is a primary expression.

Operators
Operator: A JavaScript operator is a special symbol or keyword used to perform operations on data. Operators are used in expressions. In the expression 4 + 3, the + sign is the operator. 

Operands: are the data that is used in the expression. So in the expression 4 + 3, 4 and 3 are the operands.

Assignment operator =
The = sign is the assignment operator used to assign a value to a variable.
const num = 5;

Compound assignment operator +=
You can keep adding on to a variable value, changing the value each time.
let res = 5;
res = res + 1; // returns 6
res = res + 1; // returns 7

The compound assignment operator is a shorthand operator for adding on to an existing variable.
  • Instead of adding 1 to the result variable like this: res = res + 1;
  • You can use the += compound assignment operator: res += 1;

Example:
res = 5;
res += 1; // returns 6
res += 1; // returns 7

Comparison operators === !== == != > < >= <= 
  • Comparison operators compare two operands and return true or false. They can check for equality ===, inequality !==, greater than >,  greater than or equal to >=, less than <, less than or equal to <=.
  • Strict equality and inequality: Strict equality checks for equality of the value and data type. The strict equality operator is 3 equal signs ===, and the strict inequality operator is !==. Expressions are evaluated before doing the comparison. Examples:
    • 7 === (5 + 2); // returns true
    • 7 === '7'; // returns false. One value is a number while the other is a string.
    • true === 1; // returns false.
    • undefined === null; // returns false. 
  • Loose equality and inequality: Loose equality uses == as the operator, and != for loose inequality. Loose equality does some type conversions before doing the equality check.
    • 7 == '7'; // returns true. When a number is compared to a digit string, the string converts to a number before doing the comparison.
    • true == 1; // returns true. When a boolean is compared to the numbers 0 or 1, 0 converts to false and 1 converts to true.
      • undefined == null; // returns true. This resolves to true when using loose equality.


4a. Booleans

Booleans
  • Boolean is a primitive data type with two possible values: true or false.
  • Comparison expressions resolve to boolean values. Examples:
let name = 'Joey';
let age = 22;
name === 'Joey'; // returns true
age < 21; // returns false.

4b. If Statements

If statements
  • An if statement is a block of code that executes if its condition resolves to true. If the condition resolves to false it is skipped.
Format:
if (condition) { 
statements;
}

Example:
const score = 77;
let pass = false;
if (score >= 60) {
  pass = true;
}
pass; // returns true

If... else:
It can have an else clause that executes if the condition is false.

Format:
if (condition) { 
statements;
} else {
statements;
}

Example:
const score = 77;
let pass;
if (score >= 60) {
  pass = true;
} else { pass = false; }
pass; // returns true


5. Functions

  • Functions are self contained blocks of code that accomplish a specific task. 
  • Functions are not executed until they are called. 

Function declarations
Format:
function name(parameters) { 
  statements;
  return statement;


name(arguments);
  • Function declarations start with the keyword function followed by the function name.
  • Parameters: Parameters are put in parentheses. They act like local variables that hold values passed in when the function is called. 
  • Function Body: Inside the curly braces are the statements of code that get executed as a block of code. 
  • Return statements: 
    • Functions always return a result. 
    • The last statement in a function starts with the keyword return followed by the value you want the function to return.
    • If there is no return statement, the function returns undefined.

Functions are callable:
  • You call the function by entering the function name followed by parentheses.
  • Arguments: In the parentheses you can pass in values for the function's parameters. These values are called arguments. 

Example: function that adds two numbers together
function add(x, y) {
  const res = x + y;
  return res;
}
let res = add(5, 3); // returns 8

  • The above example function has two parameters, x and y. 
  • The function body adds the two parameter values together then returns the result.
  • We call the function passing in two arguments: 5 and 3. 
  • We assign the function's return value of 8 to the variable res

  • Function declarations are hoisted to the top of their scope. That means you can call them before they are declared. 

let res = add(5, 3); // returns 8
function add(x, y) {
  const res = x + y;
  return res;
}

Arrow functions
Arrow functions have a different format from function declarations.

Format:
const funcName = (params) => {
  statements;
  return statement;
}

  • The function keyword is removed and replaced with a fat arrow.
  • Arrow functions do not have a name. Rather a const variable declared and assigned to the arrow function. 
  • With a const there is no hoisting. So arrow functions can't be called before they are declared. 
  • Const variables are block scoped, not function scoped. So arrow functions inside an if statement are not accessible outside the if statement.
  • Const variables are not attached to the global object.

Example:
const add4 = (x) => {
  const result = x + 4;
  return result;
}
add4(10); // returns 14


Single statement arrow functions
Arrow functions allow a shortened syntax for single statement functions.
They go on a single line and you can omit the curly braces and the return keyword.
Format:
const functionName = (parameters) => statement;
functionName(args);

Example:
const add5 = (x) => x + 5;
add5(10); // returns 15

  • The add5 function is an example of a single statement arrow function.
  • You call it the same way as any other function. Calling add5(10) returns 15.


6. Strings

  • Strings are a sequence of characters surrounded by single or double quotes. Style guides recommend single quotes.
  • String is a primitive data type: typeof "Some text"; // returns 'string' 
  • Template literals use backticks instead of quotes, and allow you to insert JavaScript expressions inside ${expression}. And can span multiple lines:
const name = 'Joey';
const age = 22;
`My name is ${name}.
I am ${age} years old.`

There are a number of instance methods that can be applied by chaining them to the string.
toUpperCase() and toLowerCase() changes the case of the string.
const name = 'Joey';
let username = name.toLowerCase(); // returns "joey"

The + operator and the concat method concatenates stings together.
let str = 'Hello ' + 'world'; // Returns "Hello world"

str = 'Hello ';
str.concat('world'); // Returns "Hello world" 


7. Objects

  • An object is an unordered collection of properties written as name:value pairs.
  • Object is one of JavaScript's eight data types and the only one that is not a primitive type.

  • The preferred way to create an object outside of a class is by declaring an object literal. 

Format:
const objName = {
  prop1: value,
  prop2: value,
};

  • Object literals are surrounded by curly braces. 
  • Assign it to a const variable unless you plan on assigning the variable to another object or value.
  • Properties are listed as name value pairs separated by commas. They are like variables.
  • Properties can be of any data type including other objects.
  • Trailing commas on the last item are optional but recommended by style guides. 

Example:
const author = { 
  name: 'Joey R', 
  age: 34,
  active: true,
  books: ['Learn JavaScript', 'Learn Node.js', 'Learn Express'],
};
  • Above is an example of an object literal named author. It has four properties of different data types: name, age, active, and books.

Property value shorthand:
  • When creating an object, if the property value is assigned to a variable of the same name, you can use the property name by itself:
  • For example if you have variables for name and age:
const name = 'Joey R';
const age = 34;
  • You can create the author object literal with just the property names:
const author = { name, age }


8. Classes

  • If you want to create multiple objects that have the same properties and methods, use a class. 
  • Like most popular programming languages, JavaScript is object oriented. But unlike the others, JavaScript uses prototypes to create objects, instead of classes. 
  • However, in the 2015 ES6 release a class syntax was added to JavaScript. This gives it a similar look and feel to to class-based programming languages.
  • Behind the scenes JavaScript still uses prototypes, but class syntax enforces class-like behavior. 
  • A JavaScript class is a special type of function, called a constructor function, that generates new objects. 
    • It is a template that defines the properties and methods that all instances of this class will have.

Format:
class ClassName {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
  }
}
const instance1 = new ClassName(val1, val2);

  • To create a class, declare it with the class keyword followed by the class name. By convention, the class name is capitalized and singular. Put multiple word names in UpperCamelCase.
  • Then add a function named constructor, with parameters for the object property values.
  • The this keyword refers to the instance object you are creating. The constructor chains each property name to the object being created and assigns it to the parameter value passed in. 
  • To instantiate an object: 
    • Call the class with the new operator. 
    • Pass in the property values as arguments. 
    • The class will return a new object. 
    • Assign the returned object to a variable.

Author example:
class Author {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
const author1 = new Author('Joey', 32);

  • The above example creates an Author class.
  • The constructor function has parameters for name and age.
  • In the last line we instantiate a new object by calling the Author class with the new operator, passing in arguments 'Joey' and 32 for the name and age property values. We assign the new object to variable author1.

Get and set instance properties
  • Access property values by chaining the property name to the object.
author1.name; // returns "Joey"

  • Set property values with the equals assignment operator.
author1.age = 33;

Instance methods
  • Instance methods are functions that are applied to a specific instance of a class.

Format:
class ClassName {
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
  }
  method1() { statements; };
  method2() { statements; };
} const instance1 = new ClassName(val1, val2); instance1.method1();

  • Put instance methods after the constructor.
  • The syntax is the method name, parentheses, then the method body: methodName() { statements; }
  • Use the keyword this to reference the current object. For example, this method adds 1 to the object's age value: addYear() { this.age += 1; }
  • Call the method by chaining it to an instance object: obj.methodName()

Author example:
class Author {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  addYear() { this.age += 1; };
  log() { return `${this.name} is ${this.age} years old.` };

}
const author1 = new Author('Joey R', 32);
author1.addYear();
let view = author1.log(); // returns Joey R is 32 years old.

  • The above class has two instance methods.
  • AddYear adds 1 to the age property.
  • Log returns a string with information about the author.
  • We instantiate an Author object and assign it to variable author1.
  • Then call author1.add() which changes the age property value to 33.
  • Then call author1.log() which returns information about the author1 object.


9. Arrays

  • JavaScript arrays are list-like objects. They store multiple values, called elements, in a single variable.
  • You can create an array literal using the array operator "[]".
const arr = ['apple', 'banana', 'orange'];

  • In general, arrays should be assigned to const variables unless you plan to assign that variable name to another array or other value.

  • Each element has an associated index number that is its order in the array. Array indexes are 0 based so the first element is at index 0, the second is at index 1, etc.
  • You can think of arrays as objects whose keys are the index numbers 0, 1, 2, 3 etc.

  • Arrays can change length and the elements can be of one or more data types.

  • Arrays are not their own data type, rather they are a type of object.
let view = typeof []; // returns 'object'

Get and Set Array Elements
  • You can get an array element's value with its index number. Place the index number in square brackets and append it to the array.
const arr = ['apple', 'banana', 'orange'];
let view = arr[0]; // returns 'apple'

  • To get the last element's index number, subtract one from the length property.
view = arr[arr.length - 1] // returns 'orange'

  • You can change an element value using the equals sign.
arr[1] = 'blackberry';
view = arr[1]; // returns 'blackberry'

Add or remove elements from the start or end of the array
  • Shift() removes an item from the front of the array and returns it.
const arr = ['a', 'b', 'c'];
let elem = arr.shift(); // arr is now ['b', 'c'] elem; // returns 'a'

  • Unshift() adds an item to the front of the array.
arr; // returns ['b', 'c']
arr.unshift(1); // arr is now [1, 'b', 'c']

  • Pop() removes an item from the front of the array and returns it.
arr; // returns [1, 'b', 'c']
let elem = arr.pop(); // arr is now [1, 'b']
elem; // returns 'c'

  • Push() adds an item to the end of the array.
arr; // returns [1, 'b']
arr.push(3); // arr is now [1, 'b', 3']

Iterate over an array
  • ForEach() iterates over each item in the array.
  • It takes a callback function as its argument to perform some operation on each element. It does not have a return value so it returns undefined.
  • The example below iterates through an array and logs each element to the console. 
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.forEach((elem) => {
  console.log(elem);
});


10. The DOM - Using JavaScript to manipulate web pages

  • The JavaScript programming language was initially created to manipulate web pages directly in the browser. HTML by itself is static. Without JavaScript if you want to change anything on the web page the server would have to send an entirely new HTML document over the internet. That may be fine for a very simple website but if it involves user interaction it can noticeably hurt performance. So web developers use JavaScript to make the changes locally right in the browser when possible.

  • Web APIs and the DOM: We haven't talked about Web APIs yet. API stands for Application Programming Interface. It is an interface for two or more computer programs to communicate with each other. In the case of Web APIs it is our JavaScript program communicating with the web browser. When an HTML document is sent by a server to the web browser, the browser converts it to an object called the Document Object Model, or the DOM. The browser has a number of Web APIs for JavaScript to access the DOM and manipulate elements on a web page. We will cover the most commonly used DOM-related Web APIs in this section.

  • Let's start with a web page you can use to try out JavaScript code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Try JS</title>
  <link rel="stylesheet" href="/stylesheets/style.css">
  <script src="script.js" defer></script>
</head>
<body>
  <h1 id="heading" class="light-theme">Try JS</h1>
  <button id="btn">Clickme</button>
  <ul id="list"></ul>
</body>
</html>

  • In the head element is a link to a stylesheet to add styling to the page. The stylesheet is below with a couple simple classes that create a light theme and a dark theme.
stylesheets/style.css
.light-theme { background-color: whitesmoke; color: black; }
.dark-theme { background-color: black; color: white; }

  • To attach JavaScript to the HTML file add a script tag with the src (source) attribute set to the JavaScript file path, and a defer attribute to execute the JavaScript file after the important parts of the web page are loaded: <script src="script.js" defer></script>
  • The web page includes a heading element, a button element, and an empty ul (unordered list) element. We will use JavaScript to insert some content. 

Web APIs for manipulating a web page
  • Below are the most essential Web APIs for accessing and manipulating a web page with JavaScript.
  • Get elements: At the top of your script, select the elements you will access by their ids:
    • const elem = document.getElementById('id'); // Gets the first element found that matches the id.
  • Get or set element content: textContent is for text only. innerHTML can include other HTML elements:
    • elem.textContent; // Gets the text content of the element.
    • elem.textContent = 'New text content'; // Sets new text content.
    • elem.innerHTML; // Gets the element's inner HTML content.
    • elem.innerHTML = 'New HTML content'; // Sets new inner HTML content.
  • ClassList: Change the styling of an element by adding or removing classes:
    • elem.classList.contains('className'); // Check if the element contains the class. Returns true or false.
    • elem.classList.add('className1'[, 'className2',...]);  // Adds the class or classes to the element.
    • elem.classList.remove('className1'[, 'className2',...]); // Removes the class or classes from the element.
    • elem.classList.toggle('className1'); // Toggle add and remove a class.
  • Events: Listen for and respond to events on the page such as a button click:
    • targetElem.addEventListener('eventType', handlerFunction[, optionsOrCapture]); // Listens for a specific event type occurring on the target element. Executes the provided function when the event is triggered. Common events include:
      • Mouse click events: "click" or "dblclick": the user clicks or double-clicks an element such as a button.
      • Mouse hover events: "mouseover": the user hovers the mouse over an element.
      • Keyboard events: "keydown": the user presses a specific key.
      • Form events: "focus": the user clicks in a form field. "blur": the user clicks outside the form field. "change": the user changes the value in a form field. "submit": the user submits the form. 
      • Window events: "DOMContentLoaded": the web page finishes loading the critical components. "scroll": the user scrolls up or down the page. "resize": the window is resized. 

Example:
  • Below is a JavaScript file attached to the HTML file above. It uses Web APIs to manipulate the page.
script.js
const heading = document.getElementById('heading');
const btn = document.getElementById('btn');
const list = document.getElementById('list');

console.log(heading.textContent); // logs "Try JS"
heading.textContent = "Try JS code snippets";

const arr = ['Item 1', 'Item 2', 'Item 3'];
let listItems = '';
arr.forEach((item) => {
  listItems += `<li>${item}</li>`; 
});
list.innerHTML = listItems;

btn.addEventListener('click', () => {
  heading.classList.remove('light-theme');
  heading.classList.add('dark-theme');
});

The above page does the following:
  • Get elements: At the top it gets three elements from the HTML document.
  • Text content: Gets the textContent of the heading element, logs it to the console, then sets it to a new value.
  • Inner HTML:
    • Sets a variable called arr to an array of three items. 
    • Creates an empty string variable called list.
    • Iterates over the array. For each item, it inserts it inside li (list item) tags and appends it to the listItems variable.
    • When the iterator finishes the listItems variable will contain all the elements from the array.  Initially the list element on the web page was just an empty ul element. Now its innerHTML property is set to the listItems value and the list gets displayed on the web page.
  • EventListener:
    • The last part of the script registers an event listener on the btn (button) element, listening for the "click" event.
    • When the event is triggered, the function in the second argument gets invoked.
  • ClassList:
    • The classList.remove method removes the "light-theme" class from the heading element. Then classList.add adds the "dark-theme".


Conclusion

  • The next tutorial is a project that uses the above concepts. We will build a To-Do List applications.
Open CheatSheet Back To List Next Tutorial