"

Quick Reference Guides

46 JavaScript Reference

Here are some quick reference reminders about JavaScript. This textbook is just designed to give you a toehold in how to use JavaScript for client-side web app programming. Once you understand how the language works and how JavaScript interacts with the DOM in a browser, you can get more details elsewhere. One great place for tutorial-style basic JavaScript (including exhaustive language references) is w3schools.

Quick Facts

  • JavaScript is dynamically typed (no need to declare variable types).
  • JavaScript is weakly typed (values of the “wrong” type are converted to a usable type, sometimes with unpredictable results).
  • JavaScript supports first class functions (anonymous functions, function passing as parameters, etc.)
  • JavaScript programs run on the client side of the client-server architecture. JavaScript functions can make dynamic changes to a document after it is loaded.
  • JavaScript responds to events by making changes to the DOM.
  • JavaScript input can come from user events and from the contents of input elements.

Script Elements

<script> 
    //your code here 
</script> 

<script src="js/code.js"></script>

Debugging Output

console.log("Hello, World!");

You can use console.log to print a log trace of your program into the browser’s JavaScript console. Use it to mark whenever the program enters a code block or a function, and to print the value and types of variables at various moments.

Variables

Variables should be declared with the let keyword. Variables are local to the block in which they were declared.

let x; // declares
let x = 5; // declares and initializes

If you forget to use the let keyword, your variables will be global.

y = 6; // if y undeclared, creates a global variable

Types

JavaScript supports values of type number, string, boolean, object, function, undefined, and null.

typeof x; // returns the type of the value stored in x

Here are some functions for converting to numbers

parseInt(x); // returns integer or NaN
parseFloat(x); // returns float or NaN
isNan(x); // True if x cannot be converted to a number

Arrays

Arrays are highly flexible objects with instance variables and methods. Array literals are enclosed in square brackets.

let a = [1, "two", 3.0]; 
a.push("four");

JavaScript will never raise an index error. You can assign to any index, and you can access any index (it will return the value undefined if it’s not a legal index).

a[5]; // returns "undefined"
a[5] = "five"; // succeeds

Strings

Strings are objects with instance variables and methods. You can treat them like just like arrays of single-character strings.

Single and double quotes are equivalent for string literals.

let x = "hello";
let y = 'there';

Functions

JavaScript supports default parameter values. When calling a function, the number of arguments does not need to match the number of parameters. Extra arguments are discarded, extra parameters get the value undefined.

function foo(a, b=0, c=0) {
    return a + b + c;
}

JavaScript supports first class functions. This means that function names are variable names, and functions are values that can be assigned to variables.

let foo = function(a, b=0, c=0) {
    return a + b + c;
}

Functions can be defined within other functions. A function inside another function is local to that function.

function outer() {
    // inner is local to outer
    function inner() {
        console.log("inner");
    }
    inner();
}

Functions can also be passed as arguments to other functions

doSomething(foo);

doSomething(function() { 
    // this is an anonymous function
});

The “Main Function”

You should put all your code into a window load event. This ensures that it will execute after the DOM is built, and that you won’t accidentally overwrite any important global variables.

window.addEventListener("load", function(event) { 
    // your code here 
});

Control Structures

Here are the main JavaScript control structures used in this book. This list is not exhaustive.

if (boolean) { 
    // do something
} else { 
    // do something else
} 

while (boolean) { 
    // do something
} 

do {
    // do something
} while (boolean);

for (initialize; test; change) {
    // do something
} 

for (let e of a) { 
    // process e here
    // e is an element of array a
}

Operators

JavaScript supports all the arithmetic and Boolean operators you learned in your first programming course. But watch out for automatic type conversion (weak typing). Here are some examples:

  • 35 + “1” is “351”, not 36
  • “” == false is true

To help get around automatic type conversion, JavaScript also supports === (true if the type and value match) and !== (true if either the type or the value do not match).

The logical AND, OR, and NOT operators are &&, ||, and ! respectively.

Objects

Objects are bundles of instance variables (also known as fields). Objects are highly flexible and can be created with object literals.

let obj = { name: "Sam", number: 23};

Objects are equivalent to associative arrays and support the dot operator and array indexing operator (square brackets) as two different ways to access an instance variable.

obj.name = "Sam Scott";
obj["name"] = "Anne St-Amand";

Instance variables can hold function values. This makes them methods. Inside a method, the this keyword refers to the current object.

let obj = {
    name: "Sam",
    number: 23,
    increaseNumber(inc) {
        this.number = this.number + inc;
    }
}

obj.increaseNumber(10);

Classes

A class is a blueprint for creating objects. It contains instance variables and methods (functions). You can use a constructor method to set up instance variables when the object is created.

class Person {
    number = 23;

    constructor(name) {
        this.name = name;
    }

    increaseNumber(inc = 1) { 
        this.number = this.number + inc; 
    }
}

New objects are created from a class using the new keyword.

let p1 = new Person("Sam");
let p2 = new Person("Anne");

The Document Object

The Document Object Model (DOM) is contained in the document object. There are many ways to retrieve DOM Elements (nodes). Here are the two we use the most in this book:

let node = document.getElementById("some_id");
let nodelist = document.querySelectorAll("some_CSS_selector");

HTML Element Objects

Once you have retrieved an HTML Element Object (node) from the DOM, you can retrieve information from it and manipulate it using its instance variables.

node.innerHTML = "new HTML content";
node.style["css-property"] = "css-value";
node.classList.add("new_class");
node.classList.remove("old_class");
node.value; // access or set an input element value
node.attribute_name; // access or set any HTML attribute

DOM Events

(Note: For form elements and the submit event, see PHP Reference.)

You can add a function as an event listener to any DOM node.

node.addEventListener("event_Type", function);

Here is a list of generic event types:

click, dblclick 
mousedown, mouseup, mouseover, mouseout, mousemove
keyup, keydown, 
load

Here are some event types that are relevant to input elements:

input, change, focus, blur

An event listener function receives an event object parameter that contains information about the event. Here are some of its instance variables.

event.target, event.button
event.pageX, event.pageY, event.clientX, event.clientY
event.keyCode, event.key, event.ctrlKey, event.altKey

The target of the event (event.target) is an element but it might not be the same element you attached the listener to. You can use the this keyword to access the element the listener is attached to.

The HTML Canvas

To draw on a canvas, you retrieve it from the DOM and then retrieve its 2D context object:

let c = document.getElementById("testCanvas");
let ctx = c.getContext("2d");

Here are some relevant instance variables of the context object:

ctx.fillStyle, ctx.strokeStyle, ctx.lineWidth, ctx.font

Here are some basic drawing methods:

ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
ctx.clearRect(x, y, width, height);
ctx.fillText(text, x, y);
ctx.strokeText(text, x, y);

To draw polygons or arcs, use the following methods:

ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.closePath();
ctx.fill();
ctx.stroke();

To figure out where a mouse event occurred in the canvas, use the following calculations in an event listener.

function mouseListener(event) {
    let x = event.pageX - this.offsetLeft;
    let y = event.pageY - this.offsetTop;
    // code continues... (x, y) is where the event happened
}

Advanced DOM

You can create and insert nodes using innerHTML, or you can do it by creating and adding new HTML Element Objects.

let node = document.createElement("html_tag_name");
parent.appendChild(node);
parent.insertBefore(node, existing_child);
parent.removeChild(node);

A Diagram of the DOM Tree

You can move around the DOM by accessing the parent, children, and siblings of a node.

node.childNodes;
node.children;
node.nextSibling;
node.previousSibling;
node.parentNode;

Client-side Storage

To remember information about the user, you can use the localStorage object. Anything you store there should be accessible the next time the same client accesses your web site, unless the user has cleared their cached data in the meantime. The sessionStorage object is also available but it gets cleared out when the current tab is closed.

localStorage.some_variable = "long term";
sessionStorage.some_variable = "short term";

You can use an if statement to find out if there is anything already stored in localStorage. This can tell you whether the user has been here before.

if (localStorage.been_here) {
    // the user has been here before
} else {
    // this is the user's first visit
    localStorage.been_here = "true";

Both localStorage and sessionStorage only store strings, so values have to be converted to and from the string type when being stored and retrieved. For objects, arrays, and other structured types, you can convert them to JSON strings. This will not

localStorage.my_object = JSON.stringify(my_obj);
my_obj = JSON.parse(localStorage.my_object);

Note that JSON cannot encode methods, so you will lose those in the process.

Some Useful Global Functions

Converting to Numbers:

parseInt(x);
parseFloat(x);
isNaN(x);

Mathematical functions are in the Math object:

Math.random();
Math.round(number);
Math.floor(number);
Math.floor(Math.random() * 10) + 1;

Timers can be used to create animations or timeouts:

let id = setTimeout(function, time_ms);
let id = setInterval(function, time_ms);
clearTimeout(id);

AJAX

See PHP Reference.

License

Icon for the Creative Commons Attribution-NonCommercial 4.0 International License

Full Stack Web Development for Beginners Copyright © 2025 by Sam Scott is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License, except where otherwise noted.