Category: Week 3

Console log groups trick

Earlier in the week I learned about the utility of console log groups in testing. Today one of the other project groups shared Console.groupCollapsed which gives the default view in the console of all the test groups collapsed. This is much more useful when you have loads of tests and you don’t want to clutter the console!

function test(name, testFunction) {
  console.groupCollapsed(name);
  testFunction();
  console.groupEnd();
}
 
test("Example test 1", () => {
  console.log("test 1 log");
});
 
test("Example test 2", () => {
  console.log("test 2 log");
});

test("Example test 3", () => {
  console.log("test 2 log");
});

test("Example test 4", () => {
  console.log("test 2 log");
});

Outputs this to the console:

How to make elements focusable

In HTML, only form elements and anchors with href attributes have default focus behaviour that makes them tab-able by a keyboard-only user.

You can make your elements that are not natively focusable receive keyboard focus by adding the attribute tabindex="0". The element with this attribute will then be included the the tab sequence based on its order in the DOM.

Event.currentTarget vs. Event.target

The Event.target property identifies the element that triggered event, i.e. what you actually clicked on.

The Event.currentTarget property identifies the element that has the event listener, i.e. what you bound the event to that will never change.

I made a quick Pen below with a <div> that has the id #deadly-box and contains an <img> of a cat that has the id #schrodingers-cat.

The #deadly-box has an event listener added to it. Clicking between the box and the cat shows what id is returned by .target and .currentTarget.

How to check if arrays are equal

The quickest way is to use JSON.stringify to convert the arrays to strings and then check their equality. For example:

arraysEqual = (arr1, arr2) => JSON.stringify(arr1)==JSON.stringify(arr2);

However, this method will only work if the arrays do not contain objects. Then you would need to check if the arrays are the same length, and then iterate over both arrays to check if the items match and are in the same order. See below:

function arraysEqual (arr1, arr2) {
  if (arr1.length !== arr2.length) return false;
  for (var i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) return false;
  }
  return true;
};

Console log groups

Today we put Console.group() to use when testing our functions in the console to separate the results of our different tests.

This example below:

function test(name, testFunction) {
  console.group(name);
  testFunction();
  console.groupEnd();
}

test("Example test 1", () => {
  console.log("test 1 log");
});

test("Example test 2", () => {
  console.log("test 2 log");
});

Outputs this to the console: