20 March, 2021

JavaScript Notes

I use node.js, install the latest version to get new JavaScript features.

Create a new project with npm init -y

Use Module Import Syntax

Update package.json to use the new module syntax add:

"type": "module",

Create file index.js

import formatDate from './format-date.js' 

console.log(formatDate(new Date()))

Create the file format-date.js

function pad(text) {
  return `00${text}`.substring(`${text}`.length)
}

export default function formatDate(date) {
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}-${pad(date.getSeconds())}`
}

Call node index to test-run the script.

Strings

parseInt, parseFloat

var new Date(1411229689063)

text.replaceAll('DEV_', 'd_') // not available before 15 in node
text.replace(/DEV_/g, 'd_')

Number('1234') - Convert string to number

Arrays

Array.isArray(a1) - Returns boolean, true when object a1 is an array

includes(e1) - Returns boolean

push(e1, e2, e3) - Adds one or more elements to the end

some(e => e.weight == 4) - Returns boolean when any element has weight 4

Bind this

In a class with a callback funtion which uses member variables we have to use bind. When bind is not done, the additionalFilter uses the list instance for this:

class SomeComponent {
  parameter = 'something'

  constructor(list) {
    list.additionalFilter = this.additionalFilter.bind(this)
  }

  /* called by list */
  additionalFilter(entries) {
    // use this.parameter
  }
}

Todo Tests

Explore Web APIs