JavaScript Code Examples: II

Content

  • Types, Values, and Variables
  • Expression, Statement, Functions
  • Objects, Classes
  • Arrays
  • Sync
  • JavaScript in Web Browsers
  • Modules

Expression

Invocation Expressions

Conditional Invocation

let result = json?.name;
let result = json != null ? json.name : undefined;

Null Check

if a != null return a, else return default value

// Ternary Operator
let result = a != null ? a : defaultValue;
// Logical Operator ||
// When it's used with non-boolean values, the || operator will return a non-boolean value of one of the specified expression or operands.
let result = a || defaultValue;
// Nullish Coalescing Operator ??
let result = a ?? defaultValue;

2

if a != null and b != null return b; else return null;

let result = a != null && a.name != null ? a.name : null;
let result = a && a.name;

Statement

For Loop

for (let i = 0; i < arr.length; ++i)
arr.forEach((value, index) => { /* ... */ })
for (let index in arr)
for (const value of arr)

console.log(obj1 [, obj2, ..., objN]);

console.log(obj)
console.log(obj1, obj2)
console.log("obj is: ", obj)
console.log("obj is: ", obj, ". And my name is ", name)
console.log("objects are: ", obj1, obj2)
console.log("obj is: " + JSON.parse(JSON.stringify(obj)))

console.log(msg [, subst1, ..., substN]);

  • %o or %O Outputs a JavaScript object.
  • %d or %i Outputs an integer.
  • %s Outputs a string.
  • %f Outputs a floating-point value.
console.log("obj is %o", obj)
console.log("Hello, %s. You've called me %d times.", "Bob", 1);

Object

Merge object fields

let json1 = {"name": "Jack"};
let json2 = {
...json1,
age: 18
};

Deep copy

let json = {"name": "Jack"};
let copy = JSON.parse(JSON.stringify(json));

Get all keys of JSON/JavaScript object

const obj = {a: 'somestring', b: 123, c: false};
Object.keys(obj);

Get all values of JSON/JavaScript object

const obj = {a: 'somestring', b: 123, c: false};
Object.values(obj);
// ES6
const obj = {a: 'somestring', b: 123, c: false};
Object.keys(obj).map(key => obj[key]);

Traversing JavaScript Object

for-in

// iterates over all enumerable properties of an object.
const jsonObj = {name: "Jack", age: 18}
for (const key in jsonObj) {
console.log(`${key}: ${jsonObj[key]}`);
}

Object.entries() or Object.keys()

// to traverse a Javascript object
const jsonObj = {name: "Jack", age: 18}
Object.entries(jsonObj).forEach(([key, value]) => {
console.log(key, value)
});
Object.keys(obj).forEach(function(key) {
var value = obj[key];
// ...
});

to include non-enumerable properties

Object.getOwnPropertyNames(obj).forEach(function(key) {
var value = obj[key];
// ...
});

Array

Traversal

for (let i = 0; i < arr.length; ++i)
arr.forEach((value, index) => { /* ... */ })
for (let index in arr)
for (const value of arr)

forEach: executes a provided function once for each array element. another type of for loop.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

for in: iterates over all enumerable properties of an object. E.g. key of JSON object, index of array.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
console.log(`${property}: ${object[property]}`);
}

for of: The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
console.log(element);
}
for (const [idx, el] of arr.entries()) {
console.log( idx + ': ' + el );
}

Summary

If you don’t need break for loop use forEach, else use for of.

Find Max in an array

Find max value in an array

// apply
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
Math.max.apply(Math, array.map(o => o.value));

const array = [1,2,3,5,1,2]
Math.max.apply(Math, array);
// ES6 spread
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
Math.max(...array.map(o => o.value));

const array = [1,2,3,5,1,2]
Math.max(...array);
// standard loop
let max = testArray[0];
for (let i = 1; i < testArrayLength; ++i) {
if (testArray[i] > max) {
max = testArray[i];
}
}
// reduce
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
array.reduce((a, b) => Math.max(a.value, b.value));

const array = [1,2,3,5,1,2]
array.reduce((a, b) => Math.max(a, b));

Time cost: standard loop < ES6 spread and apply < reduce

Finding the max value of an attribute in an array of objects

// reduce
const array = [{name: "a", value: 1}, {nama: "b", value: 2}]
const maxValueObject = array.reduce((prev, current) => (prev.value > current.value) ? prev : current)

Convert type of elements of Array

int array to string array

// This will not mutate array. It will return a new array.
let array = [1, 2, 3];
let newArray = array.map(String);
let array = [1, 2, 3];
let newArray = array.map(item => item.toString())
let array = [1, 2, 3];
let newArray = array.join(",").split(",");

string array to int array

// Note: For older browsers that don't support map
let array = ['1', '2', '3'];
let newArray = array.map(Number); // i=>Number(i)
let array = ['1', '2', '3'];
let newArray = array.map(item => parseInt(item));
let array = ['1', '2', '3'];
let newArray = Array.from(array, Number);

Request

URL Parameters

Getting URL parameters

// https://example.com/?id=1
const queryString = window.location.search;
console.log(queryString); // ?id=1
const urlParams = new URLSearchParams(queryString);
const id = urlParams.get('id');
console.log(id); // 1

Checking for the Presence of a Parameter

console.log(urlParams.has('id')); // true

Getting All of a Parameter’s Values

console.log(urlParams.getAll('size'));
// [ 'm' ]

//Programmatically add a second size parameter.
urlParams.append('size', 'xl');

console.log(urlParams.getAll('size'));
// [ 'm', 'xl' ]

Iterating over Parameters

const
keys = urlParams.keys(),
values = urlParams.values(),
entries = urlParams.entries();

for (const key of keys) console.log(key);
// product, color, newuser, size

for (const value of values) console.log(value);
// shirt, blue, , m

for(const entry of entries) {
console.log(`${entry[0]}: ${entry[1]}`);
}

Document

Remove Elements

remove element by id

document.querySelector("#remove").remove();

remove elements by class name

function removeElementsByClass(className){
const elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
const removeElementsByClass = (className) => document.querySelectorAll(className).forEach(el => el.remove());

Empty Elements

empty element by id

document.querySelector("#remove").innerHTML = "";

empty elements by class name

const emptyElementsByClass = (className) => document.querySelectorAll(className).forEach(el => el.innerHTML = "");

Regular Expression

RegExp

// creating regular expression from a string, you have to double-up your backslashes \\.
const regex = new RegExp('^\\d{10}$');
const regex = new RegExp('^\\d{10}$', 'g');

/regex/mod

// if you use regex syntax, you need eacape / by \/
const regex = /^\d{10}$/;
const regex = /^\d{10}$/g;

API

  • RegExp

    • regexp.exec(str) - Returns the first match info array. It likes [matched string, group 1, group 2, ...]. The flag g has no effect.

      /hello(\d)/.exec("hello1, hello2"); // ['hello1', '1', ...]
      /hello(\d)/g.exec("hello1, hello2"); // ['hello1', '1', ...]
    • regexp.test(str) - Returns whether it matches. The flag g has no effect.

      /hello(\d)/.test("hello1, hello2"); // true
      /hello(\d)/g.test("hello1, hello2"); // true
  • String

    • string.match(regexp) - Returns the first match info array [matched string, group 1, group 2, ...], or return an all matched string array [matched string 1, matched string 2, ...] when it uses the flag g.

      let s = "hello1, hello2";
      s.match(/hello(\d)/); // return the first match object ['hello1', '1', ...]
      s.match(/hello(\d)/g); // return all match strings ['hello1', 'hello2']
    • string.matchAll(regexp) - Returns all match info arrays. The regexp must use the flag g (global search).

      let s = "hello1, hello2";
      s.matchAll(/hello(\d)/); // Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument
      for (const match of s.matchAll(/hello(\d)/g)) {
      console.log(match); // the match info array
      console.log(match[0]); // the matched string
      console.log(match[1]); // the group 1 of the matched string
      }
    • string.replace(regexp, replacement) - Returns a string with the first or all matched string replaced.

      let s = "hello1, hello2";
      s.replace(/hello(\d)/, 'hey'); // 'hey, hello2'
      s.replace(/hello(\d)/g, 'hey'); // 'hey, hey'
      // replace with group
      let s = "hello1, hello2";
      s.replace(/hello(\d)/, "hi$1"); // 'hi1, hello2'
      s.replace(/hello(\d)/g, "hi$1"); // 'hi1, hi2'
      // extract group
      s.replace(/hello(\d)/g, "$1"); // '1, 2'
    • string.replaceAll(regexp, replacement) - Returns a string with the all matched string replaced. The regexp must use the flag g (global search).

      let s = "hello1, hello2";
      s.replaceAll(/hello(\d)/, 'hey'); // Uncaught TypeError: String.prototype.replaceAll called with a non-global RegExp argument
      s.replaceAll(/hello(\d)/g, 'hey'); // 'hey, hey'
      // replace with group.
      // replaceAll(/xxx/g, '') results are same with replace(/xxx/g, '')
      s.replaceAll(/hello(\d)/g, "hi$1"); // 'hi1, hi2'
      s.replaceAll(/hello(\d)/g, "$1"); // '1, 2'
    • string.search(regexp)

    • string.split(regexp)

Flags

Flag Description Corresponding property
d Generate indices for substring matches. hasIndices
g Global search. global
i Case-insensitive search. ignoreCase
m Allows ^ and $ to match newline characters. multiline
s Allows . to match newline characters. dotAll
u “Unicode”; treat a pattern as a sequence of Unicode code points. unicode
v An upgrade to the u mode with more Unicode features. unicodeSets
y Perform a “sticky” search that matches starting at the current position in the target string. sticky

Match emoji unicode

const text = "Hello, 😀🚀🌎!";
const emojiRegex = /\p{Emoji}/gu;
const emojis = text.match(emojiRegex);

console.log(emojis); // ['😀', '🚀', '🌎']

Make sure to use the u flag at the end of the regex pattern (/.../u) to enable Unicode mode, which is necessary when working with Unicode property escapes.

References