I’ve been working intensively with JavaScript
recently, so here are my notes.
Primitive Types (Each is distinct)
Reference Types (They reference the same location)
Within an array → elements
In an object → properties
Function → method
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
The == operator
is one where JS tries hard to make things equal somehow, so use the === operator
whenever possible for value comparison.
In JS, the following values are also implicitly considered false:
All values other than the above are considered true.
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
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.
const ary = []; // Creates an empty array
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
console.log(object.key); // => "value"
console.log(object["key"]); // => "value"
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.
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) → 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() {
};
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.”
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, 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
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
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.
Even instances generated from the same class may not have identical members
In DOM, obtaining nodes based on relative positions from a specific node.
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
If you don’t need to embed HTML strings, prioritize using the textContent property
.
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
Syntax:
throw new Error(errorMessage)
A function that treats functions as arguments or return values
this
is a special variable that can be referenced from anywhere in the scriptLocation | 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) |
Setting a prototype to an instance to connect instances with “implicit references” and establish inheritance relationships between them.
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)