shou2017.com
JP

JavaScript: My Personal Notes

Sun Jun 16, 2019
Sat Aug 10, 2024

I’ve been working intensively with JavaScript recently, so here are my notes.

Main Data Types in JavaScript

Primitive Types (Each is distinct)

  • Number type (numb
  • String type (stri
  • Boolean type (boole
  • Symbol type (symb
  • Special types (null/undefined)

Reference Types (They reference the same location)

  • Array (array)
  • Object (object)
  • Function (function)

Terminology for Individual Data

Within an array → elements

In an object → properties

Function → method

undefined and null

undefined indicates that a variable’s value has not been defined

null represents a state of emptiness

⚠️ They often cause bugs in actual application development.

Example 1:

In a backend implementation using Ruby.

When the return value of name is undefined,

In Ruby: false

Similarly, when the return value of name is null,

In Ruby: true

name = params[:name] == '' ? nil : User.find(params[:name]).name

Use === operator whenever possible for value comparison

The == operator is one where JS tries hard to make things equal somehow, so use the === operator whenever possible for value comparison.

Falsy values

In JS, the following values are also implicitly considered false:

  • Empty string ("")
  • Number 0, NaN (Not a Number)
  • null, undefined

All values other than the above are considered true.

Exception handling try…catch…finally statement

try {
    Commands that might cause an exception
} catch(variable to receive exception information) {
    Commands to execute when an exception occurs
} finally {
    Commands to execute at the end regardless of exception
}

finally is similar to ensure in Ruby

Built-in Objects

In JS, you need to instantiate objects to use them, but since JS allows you to use literals directly as corresponding built-in objects, you rarely need to be conscious of instantiation.

As a rule, do not instantiate primitive data types using the new operator

Array Object

const ary = []; // Creates an empty array

Object Literal

Object literals allow you to create a new object by writing {}. Object literals allow you to define the contents at the same time as creating the object. You can create and initialize an object by writing key-value pairs separated by : inside {}.

const object = {}; // Creates an empty object

const object = {
    key: "value"
};

Methods to reference an object’s key

Dot Notation

console.log(object.key); // => "value"

Bracket Notation

console.log(object["key"]); // => "value"

Stack

A Last In First Out (LIFO) data structure. Used for purposes like saving operation history in applications and retrieving the last executed operation first.

Can be implemented with push and pop methods.

Queue

First In First Out (FIFO). Processes the first element that entered first. Similar to food displays.

Can be implemented with push and shift methods.

function statement (function declaration) and function literal (function expression)

• function statement (function declaration) → Directly defines the function getTriangle • function literal → Defines a nameless function “function (base, height) {…}” and stores it in the variable getTriangle.

Function literals are called anonymous functions because they don’t have a name at the time of declaration.

// function statement
function getTriangle(base, height) {
  return base * height / 2
}
console.log('Triangle area:' + getTriangle(5, 2));

// In function declarations, the "function name" cannot be omitted
function functionName() {
}
// function literal
const getTriangle = function (base, height) {
  return base * height / 2;
};
console.log('Triangle area:' + getTriangle(5, 2));

// In function expressions, the "function name" can be omitted since it's referenced by the variable name
const variableName = function() {
};

Arrow Function

Syntax:

(parameters,...) => { ...function body... }
const getTriangle = (base, height) => {
    return base * height / 2;
}
console.log('Triangle area:' + getTriangle(5, 2));

Even if there are no arguments, you cannot omit (). This is because () also carries the meaning of “executing a function.”

let scope

With var, block-level scope doesn’t exist, and variable i remains valid even after exiting the block.

if (true) {
  var i = 5;
}

console.log(i); // => 5

With let, you can declare variables that respect block scope.

if (true) {
  let i = 5;
}

console.log(i); // => error

The “…” operator for argument expansion

The “…” operator, when used in actual arguments, can expand objects that can be processed in a for ...of block into individual values.

console.log(Math.max(...[15, -3, 78, 1])); //78

Destructuring assignment

The key point is that the target variables are also enclosed in brackets.

let data = [56, 64, 94, 89];
let [x0, x1, x2, x3] = data

console.log(x0); // 56
console.log(x3); //89

Prototypes, not classes

The simplest class.

This is just assigning an empty function literal to the variable Member, but this is a class in JavaScript.

var Member = function() {};

To instantiate this Member class, use the new operator.

var menm = new Member();

In the world of JavaScript, the concept of “class in the strict sense” doesn’t exist.

In JavaScript, functions (Function objects) are given the role of classes.

Loosely bound classes

Even instances generated from the same class may not have identical members

Node walking

In DOM, obtaining nodes based on relative positions from a specific node.

Problems with event handlers using onxxxx properties

Multiple event handlers cannot be attached to the same element/same event.

What can be tied to the same event on the same element multiple times is an event listener.

addEventListener method

elem.addEventListener(type, listener, capture)
  elem: element object    type: event type
  lister: process to execute in response to the event  capture: event direction

• onload event handler → Executed when the content body and all images are loaded • DOMContentLoaded event → Executed when the content body is loaded (= doesn’t wait for images to load)

Page initialization processing is typically represented by DOMContentLoaded event listener

Embedding HTML strings

If you don’t need to embed HTML strings, prioritize using the textContent property.

Terminology

Constructor

A method that initializes an (instance) object. Constructor names typically begin with a capital letter to distinguish them from ordinary (non-constructor) functions.

Constructors do not require a return value.

const Member = function (firstName, lastName) {
  // this refers to the instance generated by the constructor (i.e., itself)
  // You can set instance properties by specifying variables for this
  this.firstName = firstName;
  this.lastName = lastName;
  // Declare getName method-like by passing a function literal to the getName property
  this.getName = function () {
    return this.lastName + '' + this.firstName;
  }
};
let mem = new Member('tarou', 'tanaka');
console.log(mem.getName());

Property definition:

this.propertyName = value;

In JavaScript, strictly speaking, there is no independent concept of a method, but a property whose value is a function object is considered a method

throw statement

Syntax:

throw new Error(errorMessage)

Higher-order function

A function that treats functions as arguments or return values

this keyword

  • this is a special variable that can be referenced from anywhere in the script
  • Its contents change depending on the calling location and context
Location What this references
Top level (outside functions) Global object
Function Global object (undefined in strict mode)
call/apply method Object specified in the argument
Event listener Event source
Constructor Created instance
Method The calling object (= receiver object)

Prototype chain

Setting a prototype to an instance to connect instances with “implicit references” and establish inheritance relationships between them.

Event handler, event listener

A block of code (function) that defines how to process an event.

Reference: JavaScript in Depth: From Modern Style Basics to Practical Applications (Revised New Edition)

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで

See Also