To check if a key exists in a js object, you can: compare the key’s value to undefined, use .hasOwnProperty, or use “key in object” syntax. Each method behaves a bit differently, so let’s do some examples.
Javascript
Copy an object in Javascript
There are several ways to copy an object in Javascript, and they fall into two categories: shallow copies and deep copies. Before going deeper, it might be helpful to define the two: If you’re copying a simple Javascript object with top-level properties only, all copies will be deep copies, regardless of what method you use. […]
Flatten an array in Javascript
Flattening an array means making it one-dimensional. The easiest way to flatten an array is via Array.prototype.flat. For many years, doing this in javascript required the use of concat, spread, or reduce. Not anymore. Flatten with Array.prototype.flat This method does exactly what you’d expect: By default, flat only flattens one level deep: But flat accepts […]
Javascript map function
The javascript map() function takes in a callback function, applies that callback function to each element of an array, and returns a new array containing the results. Many languages have a map function, and they all behave roughly this way. Javascript map basics map() accepts a single callback function, and passes each element of the […]
Javascript forEach
Javascript’s forEach method is one of its basic array methods, and it’s used all the time. It does as its name suggests, and performs a function for each element of an array: In the function above, I only accessed one argument, item. However, forEach actually makes 3 arguments available to its callback function if you […]
Insert into javascript array at a specific index
There are two options when inserting into an array in javascript: slice() and splice(). Array.prototype.slice Array.prototype.slice returns a copy of a portion of an array, like so: Let’s say we want to insert c where it belongs in this list, between b and d. The three dots … in the above example are known as javascript spread syntax, […]
Calculate Date Difference in Javascript
You have two main options: Let’s go through a quick example of each approach. Using date-fns to get date difference Above, I mentioned luxon, day.js, and date-fns. They’re all great packages, but I personally prefer date-fns due to its easily searchable documentation. date-fns has a ton of other functionality and the docs are very good […]
Convert between timezones in Javascript
Javascript dates are frequently stored in UTC, or Coordinated Universal Time, specifically so we don’t have to store time-zone-adjusted dates. You’ll often see ISO-formatted date strings ending in Z like this: 2022-12-15T21:07:49.883Z. That Z means “Zulu”, and is just military jargon for “UTC”. Greenwich Mean Time (GMT) is also exactly the same: GMT === UTC […]