javascript

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);

[SOLVED] An Implementation Cannot Be Declared in Ambient Contexts Error in TypeScript

Are you experiencing the “an implementation cannot be declared in ambient contexts” error in TypeScript? This error can occur when you try to include logic in declaration files, for example:

car.d.ts

declare module 'car' {
  export class Car {
    color: string;
    maxSpeed: number;
    started: boolean;

    // Error: An implementation cannot be declared in ambient contexts
    start() {
      this.started = true;
    }
  }
}

Ambient declarations only exist in the type system and are erased at runtime, so they are not meant to contain implementations. The car module declaration in the example above is only meant to specify type information for a car module that is implemented somewhere else.

To fix this error, remove the implementation:

car.d.ts

declare module 'car' {
  export class Car {
    color: string;
    maxSpeed: number;
    started: boolean;

    start(); // implementation removed
  }
}

How to convert a Map to JSON in JavaScript

To convert a Map to JSON in JavaScript, call the Object.fromEntries(map), then pass the result to the JSON.stringify() method.

For example:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const json = JSON.stringify(Object.fromEntries(map)); // {"user1":"John","user2":"Kate","user3":"Peter"} console.log(json);

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:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const obj = Object.fromEntries(map); // { user1: 'John', user2: 'Kate', user3: 'Peter' } console.log(obj);

Convert JSON back to Map

To convert the JSON string back to a Map:

  1. Parse the JSON string to an object with JSON.parse().
  2. Call Object.entries() with this object as an argument.
  3. Create a new Map object, passing the result of Object.entries() to the constructor.

For example:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const jsonFromMap = JSON.stringify(Object.fromEntries(map)); const obj = JSON.parse(jsonFromMap); const mapFromObj = new Map(Object.entries(obj)); // Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' } console.log(mapFromObj);

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:

JavaScript
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.

How to Convert an Array to a String with Spaces in JavaScript

To convert an array to a string with spaces in JavaScript, call the join() method on the array, passing a string containing the space as an argument. For example:

const arr = ['coffee', 'milk', 'tea'];

const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee milk tea

The Array join() method returns a string containing each array element concatenated with the specified separator. If no separator is passed as an argument, it will join the array elements with commas:

const arr = ['coffee', 'milk', 'tea'];

const str = arr.join();
console.log(str); // coffee,milk,tea

We can specify other separators apart from a space, like hyphens and slashes:

const arr = ['coffee', 'milk', 'tea'];

const withHypens = arr.join('-');
console.log(withHypens); // coffee-milk-tea

const withSlashes = arr.join('/');
console.log(withSlashes); // coffee/milk/tea

A separator can also contain more than one character. This allows us to separate the array elements with words or multiple spaces. For example:

const arr = ['coffee', 'milk', 'tea'];

const withAnd = arr.join(' and ');
console.log(withAnd); // coffee and milk and tea

const withOr = arr.join(' or ');
console.log(withOr); // coffee or milk or tea

const with2Spaces = arr.join('  ');
console.log(with2Spaces); // coffee  milk  tea

Note: If an element in the array is undefinednull, or an empty array ([]), it will be converted to an empty string ('') before concatenation with the separator. For example:

const arr = ['coffee', null, 'milk', []];

const withComma = arr.join(',');
console.log(withComma); // coffee,,milk,

const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee  milk

How to Fix the Cannot Use Namespace as a Type Error in TypeScript

Are you experiencing the “cannot use namespace as a type” error in TypeScript?

This error can occur when you try to import types declared as a module. For example:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
}

index.ts


import Car from 'car';

// Cannot use namespace 'Car' as a type.
const user: Car = {
  color: 'red',
  age: 2,
  maxSpeed: 120,
};

To fix this error, use an export assignment to specify a default export for the namespace, like this:

car.d.ts

declare module 'car' {
  class Car {
    color: string;
    age: number;
    maxSpeed: number;
  }
  export = Car;
}