I use node.js to run JavaScript code in the command line. Install the latest version to get new JavaScript features.
Create a new project with npm init -y
Use Module Import Syntax
To use the new module syntax, the package.json
file must be updated:
"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.
Start as executable
In Linux, the JS file can be executed as other script files.
#!/usr/bin/env node
console.log('Hello World!');
Change file to executable:
chmod +x hello.js
Start ./hello.js
Variable
Declare variables with var
, let
and const
keywords.
Objects
let s = Symbol()
let a = {
b: true,
x: 1,
y: 1.2,
z: 'text',
k: ['a', 'b'],
[s]: 'hidden',
f: function() {
return `${this.b}, ${this.z} ...`
}
}
for (let i in a) {
console.log(i)
}
Object attribute defined by Symbol()
is hidden from JSON.stringify
and for ... in
loops.
Strings
Variable declaration:
let x = 'text'
let y = `more ${x}`
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
1.234.toFixed(2)
- Formats a number to decimal with to digits after the decimal pointer.
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
unshift(e4)
- Adds one element to the front
some(e => e.weight == 4)
- Returns boolean
when any element has weight 4
indexOf
, filter
, slice
, splice
Map
map.set(key, value)
map.get(key)
map.delete(key)
map.size
map.values()
map.forEach()
for (e of map) {
console.log(e)
}
Functions
Functions must have a name when not immediately called. Functions cannot be overloaded with different parameter count.:
function f() {}
Immediately called functions can be without a name:
(function () {})()
Using void
operator to immediately call a function:
void function () {}()
Declare a variable by function expression. That function returns a function and call that:
let f = function () {
return function () {}
}
f()()
Lambdas
Declare a lambdad variable and call it:
let lambda = _ => console.log('lambda')
lambda()
Declare a function that returns a lambda and call that:
let g = function () {
return _ => void 0
}
g()()
let h = _ => _ => void 0
h()()
Classes
class A {
x = 1
y = 'a'
z = null
constructor() {
z = 'constructor'
}
}
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
}
}
Async
Functions:
function delayResult(x) {
return new Promise(r => {
setTimeout(() => {
r(x)
}, 1000)
})
}
async function f() {
let a = await delayResult(x)
...
}
Lambda:
const f = async () => {
...
}
Keywords
typeof
,
Infinity
, NaN
, undefined
, globalThis
Build Environment
root = true
[*]
...
Todo Tests
Explore Web APIs