Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Get an Object Key by Its Value in JavaScript

Object keys() and Array find()

To get the key of an object by value in JavaScript, call the Object.keys() method to get the object keys, then use the find() to find the key associated with the specified value. For example:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const key = getObjectKey(obj, 'Kate');
console.log(key); // user2

The Object.keys() method takes an object and returns an array of all its keys:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const keys = Object.keys(obj);
console.log(keys); // [ 'user1', 'user2', 'user3' ]

The Array find() method searches for the element in an array for which a certain condition is true. The condition is specified in the callback testing function passed to find(). The condition we specified only evaluates to true for a key in the array if its corresponding value is equal the value passed to the getObjectKey() function.

Info

If the find() method can’t find any element that satisfies the condition, it returns undefined:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const key = getObjectKey(obj, 'Sarah');
console.log(key); // undefined

Array filter() vs Array find()

The find() method only returns the first element in the array that satisfies the testing function. If the object containing multiple keys with the same value, it will return only the first key it finds:

function getObjectKey(obj, value) {
  return Object.keys(obj).find((key) => obj[key] === value);
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // user1

To get all the keys that correspond to a certain value, you can use the Array filter() method in place of find():

function getObjectKey(obj, value) {
  return Object.keys(obj).filter(
    (key) => obj[key] === value
  );
}

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
  user4: 'John',
};

const key = getObjectKey(obj, 'John');
console.log(key); // ['user1', 'user4']

Unlike find(), filter() returns an array of all the keys with matching values.

How to Get the Last Character of a String in JavaScript

In this article, we’ll be looking at some ways to quickly get the last character of a string in JavaScript.

1. String at() Method

The get the last character of a string, we can call the at() method on the string, passing -1 as an argument. For example, str.at(-1) returns a new string containing the last character of str.

const str = 'Coding Beauty';

const lastChar = str.at(-1);
console.log(lastChar); // y

The String at() method returns the character of a string at the specified index. When negative integers are passed to at(), it counts back from the last string character.

2. String charAt() Method

Alternatively, to get the last character of a string, we can call the charAt() method on the string, passing the last character index as an argument. For example, str.charAt(str.length - 1) returns a new string containing the last character of str.

const str = 'book';

const lastCh = str.charAt(str.length - 1);
console.log(lastCh); // k

The String charAt() method takes an index and returns the character of the string at that index.

Tip

In JavaScript, arrays use zero-based indexing. This means that the first character has an index of 0, and the last character has an index of str.length - 1.

Note

If we pass an index to charAt() that doesn’t exist on the string, it returns an empty string (''):

const str = 'book';

const lastCh = str.charAt(10);
console.log(lastCh); // ''

3. Bracket Notation ([]) Property Access

We can also use the bracket notation ([]) to access the last character of a string. Just like with the charAt() method we use str.length - 1 as an index to access the last character.

const str = 'book';

const lastCh = str[str.length - 1];
console.log(lastCh); // k

Note

Unlike with charAt(), using the bracket notation to access a character at a non-existent index in the string will return undefined:

const str = 'book';

const lastCh = str[10];
console.log(lastCh); // undefined

4. String split() and Array pop() Methods

With this method, we call the split() method on the string to get an array of characters, then we call pop() on this array to get the last character of the string.

const str = 'book';

const lastCh = str.split('').pop();
console.log(lastCh); // k

We passed an empty string ('') to the split() method to split the string into an array of all its characters.

const str = 'book';

console.log(str.split('')); // [ 'b', 'o', 'o', 'k' ]

The Array pop() method removes the last element from an array and returns that element. We call it on the array of characters to get the last character.

[SOLVED] Cannot read property ‘constructor’ of undefined in JS

The “cannot read property ‘constructor’ of undefined” error occurs when you attempt to access the constructor property of a variable that is undefined. To fix it, perform an undefined check on the variable before trying to access the constructor property.

const user = undefined;

// TypeError: Cannot read properties of undefined (reading 'constructor')
const User = user.constructor;
const newUser = new User();

In this example, the user variable is undefined, so we get an error when we try to access a property from it. We fix it by checking if the variable is nullish before accessing the constructor property. We can do this with the optional chaining operator (?.):

const user = undefined;

// Optional chaining in if statement
if (user?.constructor) {
  const User = user?.constructor;
  const newUser = new User();
}

Using the optional chaining operator on a variable will return undefined and prevent the property access if the variable is nullish (null or undefined).

We can also use an if statement to check if the variable is truthy:

const user = undefined;

// Check if 'user' is truthy
if (user && user.constructor) {
  const User = user.constructor;
  const newUser = new User();
}

Tip

In JavaScript, the constructor property of an instance object returns a reference to the Object constructor function that created the object.

let obj1 = {};
obj1.constructor === Object; // -> true

let obj2 = new Object();
obj2.constructor === Object; // -> true

let arr1 = [];
arr1.constructor === Array; // -> true

let arr2 = new Array();
arr2.constructor === Array; // -> true

let num = new Number(3)
num.constructor === Number; // -> true

How to Fix the “Cannot Read Property ‘replace’ of Undefined” Error in JavaScript

Are you experiencing the “cannot read property ‘replace’ of undefined” error in JavaScript? This error occurs when you attempt to call the replace() method on a variable that has a value of undefined.

const str = undefined;

// TypeError: Cannot read properties of undefined (reading 'replace')
const newStr = str.replace('old', 'new');

console.log(newStr);

To fix the “cannot read property ‘replace’ of undefined” error, perform an undefined check on the variable before calling the replace() method on it. There are various ways to do this, and we’ll cover 4 of them in this article.

1. Use an if Statement

We can use an if statement to check if the variable is truthy before calling the replace() method:

const str = undefined;

let result = undefined;
// Check if truthy
if (str) {
  result = str.replace('old', 'new');
}

console.log(result); // undefined

2. Use Optional Chaining

We can use the optional chaining operator (?.) to return undefined and prevent the method call if the variable is nullish (null or undefined):

const str = undefined;

// Optional chaining
const result = str?.replace('old', 'new');

console.log(result); // undefined

3. Call replace() on a Fallback Value

We can use the nullish coalescing operator (??) to provide a fallback value to call replace() on.

const str = undefined;

const result = (str ?? 'old str').replace('old', 'new');

console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10

4. Use a Fallback Result Instead of Calling replace()

We can combine the optional chaining operator (?.) and the nullish coalescing operator (??) to provide a fallback value to use as the result, instead of performing the replacement.

const str = undefined;

const result = str?.replace('old', 'new') ?? 'no matches';

console.log(result); // 'no matches'

Note

If the variable is not nullish but doesn’t have a replace() method, you’ll get a different kind of error:

const obj = {};

// TypeError: obj.replace is not a function
const result = obj.replace('old', 'new');

console.log(result);

How to Fix the “Cannot read property of undefined” Error in JavaScript

4 ways to fix the “Cannot read property of undefined” error in JavaScript.

The error happening in Chrome.
The error happening in Chrome.

1. Add undefined check on variable

To fix the the error, check that the value is not undefined before accessing the property:

JavaScript
const auth = undefined; console.log(auth); // undefined // ❌ TypeError: Cannot read properties of undefined (reading 'user') console.log(auth.user.name); 

We can fix the error by adding an optional chaining operator (?.) on the variable before accessing a property. If the variable is undefined or null, the operator will return undefined immediately and prevent property access.

JavaScript
const auth = undefined; console.log(auth); // undefined // ✅ No error console.log(auth?.user?.name); // undefined 

The optional chaining operator also works when using bracket notation for property access:

JavaScript
const auth = undefined; console.log(auth); // undefined // ✅ No error console.log(auth?.['user']?.['name']); // undefined 

This means that we can use it on arrays:

JavaScript
const arr = undefined; console.log(arr?.[0]); // undefined // Array containing an object console.log(arr?.[2]?.prop); // undefined

Before the optional chaining was available, the only way we could avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, for example:

JavaScript
const a = undefined; // Optional chaining if (a?.b?.c?.d?.e) { console.log(`e: ${e}`); } // No optional chaining if (a && a.b && a.b.c && a.b.c.d && a.b.c.d.e) { console.log(`e: ${e}`); }

2. Use replacement for undefined variable

In the first approach, we don’t access the property or method when the variable turns out to be undefined. In this solution, we provide a fallback value that we’ll access the property or method on.

Here, we use ?? to set the variable to a default string value if undefined, to avoid the “Cannot read property ‘replace’ of undefined” error.

JavaScript
const str = undefined; const result = (str ?? 'old str').replace('old', 'new'); console.log(result); // 'new str'

The null coalescing operator (??) returns the value to its left if it is not null or undefined. If it is, then ?? returns the value to its right.

JavaScript
console.log(5 ?? 10); // 5 console.log(undefined ?? 10); // 10

The logical OR (||) operator can also do this:

JavaScript
console.log(5 || 10); // 5 console.log(undefined || 10); // 10

3. Use fallback value instead of accessing property

Another way to fix this error is to avoid the property access altogether when the variable is undefined and use a default fallback value instead.

We can do this by combining the optional chaining operator (?.) and the nullish coalescing operator (??).

By using 0 as a fallback in this example, we prevent the “Cannot read property ‘length’ of undefined” error.

JavaScript
const arr = undefined; // Using "0" as a fallback value const arrLength = arr?.length ?? 0; console.log(arrLength); // 0 const str = undefined; // Using "0" as a fallback value const strLength = str?.length ?? 0; console.log(strLength); // 0

4. Find out why the variable is undefined

The solutions above are handy when we don’t know beforehand if the variable will be undefined or not. But there are situations where the “cannot read property of undefined” error is caused by a coding error that led to the variable being undefined.

Make sure variables are initialized

It could be that you forgot to initialize the variable:

JavaScript
let doubles; const nums = [1, 2, 3, 4, 5]; for (const num of nums) { let double = num * 2; // ❌ TypeError: cannot read properties of undefined (reading 'push') doubles.push(double); } console.log(doubles);

In this example, we call the push() method on the doubles variable without first initializing it, which causes the “Cannot read property ‘push’ of undefined” error.

JavaScript
let doubles; console.log(doubles); // undefined

Because an uninitialized variable has a default value of undefined in JavaScript, accessing a property/method causes the error to be thrown.

The obvious fix for the error, in this case, is to assign the variable to a defined value.

JavaScript
// ✅ "doubles" initialized before use let doubles = []; let nums = [1, 2, 3, 4, 5]; for (const num of nums) { let double = num * 2; // push() called - no error thrown doubles.push(double); } console.log(doubles); // [ 2, 4, 6, 8, 10 ]

Make sure called function returns value

If the property you’re accessing is from a function call result, the error may have occurred because you forgot to actually return a value in the function.

This mistake commonly causes the “Cannot read property ‘then’ of undefined” error in JavaScript:

JavaScript
function fetchData(apiUrl) { // 👇 `return` keyword missing fetch(apiUrl).then((response) => { return response.json(); }); } // ❌ Cannot read property 'then' of undefined fetchData('/api/data') .then((data) => console.log(data))

To fix the error in this case, we’ll simply return fetch()‘s Promise:

JavaScript
async function getUserData(userId) { if (userId) { const response = await fetch(`/api/users/${userId}`); return response.json(); } // 😕 No return if userId is absent } // ❌ Cannot read property 'then' of undefined if userId is absent getUserData().then(data => console.log(data));

Make sure type is correct

Another common mistake that causes this error is accessing an element from an array variable before accessing an Array property/method instead of accessing the property/method on the actual array variable.

JavaScript
const array = []; // ❌ TypeError: Cannot read properties of undefined (reading 'push') array[0].push('html'); array[0].push('css'); array[0].push('javascript'); console.log(array);

Accessing the 0 property with bracket indexing gives us the element at the index 0 of the array. The array has no element, so arr[0] evaluates to undefined and calling push() on it causes the error.

To fix this, we need to call the method on the array variable, not one of its elements.

JavaScript
const array = []; // ✅ Call push() on "array" variable, not "array[0]" array.push('html'); array.push('css'); array.push('javascript'); console.log(array); // [ 'html', 'css', 'javascript' ]

How to Convert JSON to/From a Map in JavaScript

To convert JSON to a Map in JavaScript:

  1. Parse the JSON string to an object with the JSON.parse() method.
  2. Call Object.entries() with this object as an argument.
  3. Pass the result of Object.entries() to the Map() constructor.

For example:

const json =
  '{"user1":"John","user2":"Kate","user3":"Peter"}';

const map = new Map(Object.entries(JSON.parse(json)));

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

We first convert the string to an object and then to an array, because we can’t parse a JSON string to a Map directly. The Object.entries() method takes an object and returns a list of key-value pairs that correspond to the key and value of each property of the object:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const arr = Object.entries(obj);

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr);

The Map() constructor can take an iterable of key-value pairs to create the Map elements, so we pass the result of the Object.entries() directly to it.

Convert Map to JSON

To convert the Map back to a JSON string, call the Object.fromEntries() method with the Map as an argument, and pass the result to the JSON.stringify() method:

const json =
  '{"user1":"John","user2":"Kate","user3":"Peter"}';

const map = new Map(Object.entries(JSON.parse(json)));

const jsonFromMap = JSON.stringify(Object.fromEntries(map));

// {"user1":"John","user2":"Kate","user3":"Peter"}
console.log(jsonFromMap);

We first transform the Map with Object.fromEntries(), because we can’t serialize a Map to a JSON string directly. The Object.fromEntries() method transforms any list of key-value pairs into an object:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const obj = Object.fromEntries(map);

// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

Fix the Cannot Find Name ‘require’ Error in TypeScript

To fix the “cannot find name ‘require'” error in TypeScript, install the @types/node package into your project by running npm i -D @types/node.

This error can occur when you try to use the Node.js require() function in a TypeScript file.

The "cannot find name 'require' error in TypeScript.

You can fix it by running the following command in a terminal window at the root directory of your project:

npm i -D @types/node

If the error persists, try adding "node" to the types array in your tsconfig.json file:

tsconfig.json

{
  "compilerOptions": {
    "types": [
      // ... other types
      "node"
    ],
  },
}

Tip

If you’re just doing simple testing, you can quickly resolve this error by defining a require variable at the top of the TypeScript file:

declare var require: any;

How to Get the First Element of a Map in JavaScript (Easy Ways)

In this article, we’ll be exploring some ways to quickly get the first element of a Map object in JavaScript.

1. Call next() on Map entries()

To get the first element of a Map, we can call the entries() on the Map to get an iterable object, then call the next() method on this iterable. For example:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

const firstElement = map.entries().next().value;

console.log(firstElement); // [ 'key1', 'value1' ]

The Map entries() method returns an iterable of key-value pairs for all elements of the Map. The next() method returns the next element in the iterable sequence. Since it’s the first time we’re calling it on the iterable, it returns the first element in the sequence. We use the value property of the element to get the key-value pair representing the first element of the Map.

2. Array.from()

We can also use the Array.from() method to get the first element of the Map:

const map = new Map([
  ['key1', 'value1'],
  ['key2', 'value2'],
  ['key3', 'value3'],
]);

const firstElement = Array.from(map)[0];
console.log(firstElement); // [ 'key1', 'value1' ]

Note

On a Map with many elements, this method is significantly slower than the first, as it creates a new array from all the Map elements. We conducted a performance comparison between the two methods on a Map with 1 million elements, and these were the results on average:

Iterable next(): 0.015ms
Array from() 251.093ms

How to Convert Map Values to an Array in JavaScript

Let’s look at some ways to easily convert the values of a Map object to an array in JavaScript.

1. Map values() and Array from()

To convert Map values to an array, we can call the values() method on the Map, and pass the result to the Array.from() method. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const values = Array.from(map.values());

console.log(values); // [ 'John', 'Kate', 'Peter' ]

The Map values() method returns an iterable of values in the Map. The Array.from() method can create arrays from iterables like this.

2. Map values() and Spread Syntax (…)

We can also use the spread syntax (...) to unpack the elements of the iterable returned by the Map values() method into an array. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const values = [...map.values()];

console.log(values); // [ 'John', 'Kate', 'Peter' ]

Using the spread syntax allows us to combine the values of multiple Map objects into one array. For example:

const map1 = new Map([['user1', 'John']]);

const map2 = new Map([
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const values = [...map1.values(), ...map2.values()];

console.log(values); // [ 'John', 'Kate', 'Peter' ]

How to Create a Set from an Array in JavaScript

To create a Set from an array in JavaScript, pass the array to the Set() constructor. For example:

const arr = [1, 2, 3];
const set = new Set(arr);

console.log(set); // Set(3) { 1, 2, 3 }

console.log(set.has(2)); // true

set.delete(2);

console.log(set); // Set(2) { 1, 3 }

A Set object only stores unique values, so it won’t contain any duplicates.

const arr = [1, 1, 2, 3, 3, 4];
const set = new Set(arr);

// Set(4) { 1, 2, 3, 4 }
console.log(set);

This makes it useful for removing duplicate elements from an array without mutating it, for example:

const arr = [1, 1, 2, 3, 3, 4];

const distinct = Array.from(new Set(arr));

// [1, 2, 3, 4]
console.log(distinct);