2.0 KiB
Title: Lab Ten
Date: 2022-10-17T08:30:00
Tags: cs2613, lab, javascript, methods, tests, classes, prototypes, arrays, recursion
In this lab, I learned about classes, prototypes, arrays and how to use recursion in javascript
Prototypes
In javascript, there is a notion of a prototype, which is a way of making objects by calling the Object.create()
function on a "prototype" of an object, which can be viewed as a form of constructor
Classes
In reality, classes should be made by the new keyword instead of calling Object.create()
. In "recent" times there has been an addition to javascript which allows the use of the class keyword and a constructor keyword, which lets you define an object in a very similar way to Java. It should be noted that both the new and the class/constructor syntax is just the same prototype based system that has been made more convenient to read.
Arrays
Arrays in javascript are implemented as objects, which is similar to java, but due to the type casting nature of javascript can lead to some unintuitive behavior. We were tasked to create a function that takes a range and creates an array filled with numbers from the start of the range to the end. This can be achieved with a simple for loop.
We were also tasked with creating function that sums the elements of a javascript array. This can also be done with a for loop, by looping over each element and adding it to a running total and returning the result. We were introduced to some higher order functions like reduce and forEach, which take functions as arguments and are similar to foldl
in racket. We can use foreach as a way to skip the syntax of a normal for loop and simply operate once on each element of an array.
Recursion
We were tasked with using recursion to recreate the mult
and add
methods from the first javascript lab, but with recursion. In my opinion it was much more readable than the sample racket solution, but there was an noticeable similarity in the syntax