Projects People Resources Semesters Blog About
JavaScript

JavaScript

An extremely powerful language that has evolved from inside the browser to being used in all aspects of the tech stack with the right libraries.

At it’s heart JavaScript is a scripting language and its dynamic typing and easy to write nature means you can prototype very fast, but you have to me more careful of bugs.

Types

Like all programming languages, types play an important role in storing all different kinds of data. Unlike statically typed languages, you don’t explicitly declare the type of a variable.

Variables are declared using the let and const keywords. const should be used for all constant variables that won’t change throughout the program and let should be used for all other variables.

// Example uses of const
const API_KEY = "asdfgfdxc"
const SIZE = 50

// Variable Declarations
let str = "Hello, world" // Declaring a String
let num = 1234 // Declaring a number
let bool = true // Declaring a boolean

Arrays

Arrays are a collection of elements that can be accessed very easily. There are several ways to declare an array in JavaScript, and array access is also very fast.

// Declaring an Array
let arr1 = [1, 2, 3, 4] // An array with starting values 1, 2, 3, 4
let arr2 = [1, true, "hello, world"] // Arrays can be declared with different types
let arr3 = new Array() // An empty array
let arr4 = new Array(4) // An empty array of length 4

Built-In Functions / Properties

Within an array there are valuable built-in functions that will always remain useful:

Array.length - Returns the size of an array

Array.push(var) - Add a new array element to the end of the array

Array.pop() - Remove an item from the end of the array

Array.forEach(function(currentElement, index, array) {...}) - Loop over an array with a predefined or callback function

Array.map(function(currentElement) {...}) - Iterates over an array and returns a new array of the potentially modified elements

Array.reverse() - Reverses an array

Array.filter(function(element) {/*Returns a boolean*/}) - Returns an array of elements that pass the condition of the callback function.

Array.some(function(element) {/* Returns a boolean*/}) - Returns true if any of the elements return true from the callback function

Array.slice(startIndex, endIndex) - Returns a portion of an array into a new array object selected from start to end indexes. If no start is provided, slice will begin at index 0, and if no end is provided slice fill go to the array’s length.

There are a whole host of useful built-in functions that can be used with arrays that can help to solve many problems you may encounter. Remember you don’t necessarily have to rebuild the wheel and write all your code from scratch.

Loops

Just like all modern programming languages, iteration plays an important role in accessing and modifying information. Before jumping into the trusted while and for loops, as mentioned above when you have to iterate through arrays there are useful functions like map, forEach, reduce, filter, includes, and many others that may serve the use that you’re looking for.

While

The while statement should seem very familiar if you’ve worked with other programming languages. Simply it repeats a section of code while a condition is true.

Syntax:

while([Condition]) {
// Write code here
}

Example:

// Execute code as long as n is less than three
while(n < 3) {
console.log(n) //print n
n++;           // Increment n by one
}

For

The for statement creates a loop that consists of three optional expressions: an initialization, condition, and final-expression, enclosed in parentheses and separated by semicolons. The block of code following the for will execute so long as the condition is true

Syntax:

for ([initialization]; [condition]; [final-expression]){
// Write code here to execute
}

Example:

for (let i = 0; i < 9; i++) { // While i is less than 9 execute the statment below
   console.log(i);
   // more statements
}                            // Once the code finishes executing, increment i by one

Each of the expressions in the for statement are optional so long as they’re included elsewhere

let i = 0;               // Initialize variable i
for (; i < 9; i++) {     // For statement ommitting the initialization expression
    console.log(i);
    // more statements
}

For...In

The for...in statement iterates over all properties of an object that are keyed by strings. It may be most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise)

Example:

var obj = {a: 1, b: 2, c: 3};

for (const prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

For...of

The for...of statement creates a loop iterating over including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

Example:

const iterable = [10, 20, 30];  // Initialize the iterable

for (let value of iterable) { 
  value += 1;
  console.log(value);
}
// Output:
// 11
// 21
// 31

Break

There might be times you need to exit a loop before it’s finished. That’s where break comes in.

With break you can exit the scope of any loop or function early.

Example:

for (let i = 0; i < 9; i++) { // While i is less than 9 execute the statment below
   console.log(i);
   if (i === 3) {
		console.log("exiting for statement");
		break;      
   }
} 
// Output:
// 1
// 2
// 3
// Exiting for statementp0

Objects

At the heart of JavaScript are objects. From arrays, maps, classes, even function are all stored as objects. That’s where JavaScript’s Object Notation, JSON, comes into play. In JavaScript all objects are represented between braces {...}. Objects are a way to represent complex outside of the primitive types above. For example if you wanted to represent a student:

let student = {
	"name": "Matt"
	"gradYear": 2024
	"id": 1234
	"onCoop": true
}

Objects can even have arrays:

let students =  {
	[
		{
			"name": "Matt",
			"gradYear": 2024,
			"id": 1234,
			"onCoop": true
		},
		{
			"name": "Rachel",
			"gradYear": 2023,
			"id": 0987,
			"onCoop": false
		},
		{
			"name": "Gabe",
			"gradYear": 2025,
			"id": 4567,
			"onCoop": true
		}
	]
}

Accessing Objects

Many times you might need to access a certain field of an object. To reference any field from an object all you need to do is [ObjectName].[FieldName]. Using the student example from above, to get the student’s name you would need to do: student.name. The same hold true for an array of objects ex: students[0].name will get the name of the first student in the array.

Functions

Functions are a way for organizing sections of code and repeatable operations.

Basic function definition:

function myFunction(arg1, arg2) {
	// Code goes here
	return val;
}

Breakdown:

All functions begin with the function keyword followed by the name of the function itself.

Within the parentheses, the arg1, arg2 are function parameters, or in other words variables that can be passed into the function and used in its scope.

Everything inside the braces {...} of a function are inside the functions scope. All variables initialized inside a functions scope can’t be used anywhere else outside the function.

Functions might be used to modify some data or information passed to it. In that case the modified data will be returned at the end of the function. That’s where the return keyword comes into play returning whatever data is placed after it and exiting the function.

Calling Functions

Example:

function addNumbers(num1, num2) {
	return num1 + num2
}

addNumbers(4, 5)

//Output:
// 9

To call the function addNumbers(...), or any function, type the function name and include the necessary parameters: addNumbers(1, 2). Functions can also be a part of an object or class ex: className.function1().

Callback Functions

A Callback function is when a function is passed into another function as a parameter:

function addNumbers(num1, num2) {
	return num1 + num2
}

function applyFunc(f) {
	return f(1, 2)
} 

applyFunc(addNumbers)

// Output:
// 3

The example may seem trivial, but it shows the versatility of JavaScript and what can be done with the language. Callback functions don’t even have to be defined as it’s own function, but can be defined within the function call.


function applyFunc(f) {
	return f(1, 2)
} 

applyFunc((num1, num2) => { return num1 + num2 })

// Output 
// 3

This example is has the same result as the previous example yet they’re written in two different ways. A function that’s not explicitly defined and only used once is called an Anonymous Function. Anonymous functions are used frequently when iterating over data structures with forEachmap, etc:

let arr = [1, 2, 3, 4, 5]

arr.map((el) => { return el * el })

// Output:
// [1, 4, 9, 16, 25]

Void Functions

There will be times when inside a function you don’t want to return any data. This might be from modifying a field of a class or changing mutable data. Whatever the case may be, all you have to do is leave out the return keyword from your function for it not to return anything. Then the function will exit once there’s no more code left to run.

Classes

If you’ve worked with any object-oriented programming language before you’ll know that classes are essential to creating modular data types, inheritance, and good information hiding. In JavaScript, classes start with the class keyword. As mentioned before everything in JavaScript is an object so the object below:

{
	"name": ...,
	"year": ...,
	"onCoop": ...,

	"getName": function getName() {
		// Function code goes here		 
	}
}

Is the same as this class:

class Student {
	// These are called "fields"
	name
	year
	onCoop

	// The constructor initializes a class' data the first time it's called.
	constructor(name, year, onCoop) {
		this.name= name
		this.year = year
		this.onCoop = onCoop
	}

	function getName() {
		return this.name
	}
}

Classes can offer more flexibility in how the data is modified than defining complex data as an object from the get-go.

Fields

Inside a class fields are attributes that relate to a specific instance on the class. In the student example above, each field’s data is unique to a single student where the fields are the name, year, and onCoop. A field’s data can be initialized in either the constructor, where the field is defined, or later on in a function the user can call.

// Initializing a field in-line
class Student {
  // This should only be done only if the inital data is the same across
	//all instances of the class.
	name = "Matt" 
	// ...
}

If a field isn’t initialized at some point it’s data will be undefined and can lead to bug later down the line.

Constructor

The constructor is called when a class gets initialized for the first time. This can be used to initialize any field data if need be or perform any operations to set-up the class before it’s used elsewhere. In JavaScript there can only be one constructor, so make sure it covers all usages.

The constructor is also optional. If no data or fields need to be initialized then it can be omitted from the class.

Class Functions

Functions can be defined inside a class for any repeatable operations or ways to modify a class’ data. Functions within classes operate like any normal function. They can have different parameters return types, etc. Functions defined inside a class may return a certain part of a class’ field or modify a field entirely with new data.

Initialization

To use a class after its been written and to define it as a variable:

let student1 = new Student("Matt", "2024", true);

If you have a constructor that has one or more arguments they go in-between the parentheses. Otherwise if you don’t have a constructor (or it doesn’t take any arguments):

let student2 = new Student();

The new means the variable is a new reference to the class and the constructor should be called. Once that’s done the variable with the class reference can be used throughout your program referencing the fields and functions you defined in your class.

let student1 = new Student("Matt", "2024", true);

student1.getName() // Output: Matt
student1.year      // Output: 2024

This Keyword

In the basic class definition above, the this keyword was used several times. Inside a class typing this refers to the current instance of the object that’s being referenced. Just as let student1 = new Student("Matt", "2024", true) lets you use student1 as a reference to the class, this does the same thing:

let student1 = new Student("Matt", "2024", true);

class Student {
// code
	function getName() {
		// In the reference variable above, this.name will output Matt
		return this.name 
	}
}

Extending Classes

In order to create complex data structures, classes might be related to each other.

class ChildClass extends ParentClass { ... }

After extending, the child class has access to all the fields and methods of the parent class. This is useful when having one general class then child classes that are more specific versions of the parent. For example a Polygon might me a parent class and a Square can be the child class.

class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Note: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = 'Square';
  }

  function area() {
    return this.height * this.width;
  }
}

Working with HTML

Adding JavaScript to HTML adds more versatility to the projects you can create. Inside an HTML file you can use the <srcipt> </script> tags and anything written in between will be executed as JavaScript code. Additionally you can do <script src="file/path.js"> to include an external JavaScript file into your HTML page.

Accessing HTML Elements

// Finds the element that has the #foo id
let byId = document.getElementById("foo");

// Finds all p tage
let byTag = document.getElementsByTag("p"); 

// Finds elements with the class name .bar
let byClassName = document.getElementsByClassName("bar"); 

// Gets the inner html of an element
let innerHtml = document.getElementById("foo").innerHTML


// The inner HTML of an element can also be set using the same field
document.getElementById("foo").innerHTML = "Hello World"

JavaScript adds a ton of functionality to what can be done in a webpage, and there are many libraries out there that make this even easier.

Additional Resources

Like all programming languages, JavaScript is a complicated beast with built-in functions senior developers have probably never seen or used before. W3 School’s JavaScript Docs are a useful point to dive deep into the language and everything it can do.