The TypeError: Cannot read property of undefined
is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable.
Install the JavaScript SDK to identify and fix these undefined errors
Error message:
TypeError: Cannot read properties of undefined (reading x)
Error type:
TypeError
What Causes TypeError: Cannot Read Property of Undefined
Undefined means that a variable has been declared but has not been assigned a value.
In JavaScript, properties and functions can only belong to objects. Since undefined
is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined
.
TypeError: Cannot Read Property of Undefined Example
Here’s an example of a JavaScript TypeError: Cannot read property of undefined
thrown when a property is attempted to be read on an undefined variable:
function myFunc(a) {
console.log(a.b);
}
var myVar;
myFunc(myVar);
Since the variable myVar
is declared but not initialized, it is undefined. When it is passed to the myFunc
function, the property b
is attempted to be accessed. Since a
is undefined at that point, running the code causes the following error:
TypeError: Cannot read properties of undefined (reading 'b')
How to Avoid TypeError: Cannot Read Property of Undefined
When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:
function myFunc(a) {
console.log(a.b);
}
var myVar = {
b: 'myProperty'
};
myFunc(myVar);
In the above example, the myVar
variable is initialized as an object with a property b
that is a string. The above code runs successfully and produces the following output on the browser console:
myProperty
To avoid coming across situations where undefined variables may be accessed accidentally, an if
check should be added before dealing with such variables:
if (myVar !== undefined) {
...
}
if (typeof(myVar) !== 'undefined') {
...
}
Updating the previous example to include an if
check:
function myFunc(a) {
if (a !== undefined) {
console.log(a.b);
}
}
var myVar;
myFunc(myVar);
Running the above code avoids the error since the property b
is only accessed if a
is not undefined
.
Here is how you can handle errors using a try { } catch (e) { }
block.
// Caught errors
try {
//Place your code inside this try, catch block
//Any error can now be caught and managed
} catch (e) {
Rollbar.error("Something went wrong", e);
console.log("Something went wrong", e);
}
Here is how you can setup a JavaScript Error handler: Setup JavaScript Error Handler
Where TypeError Resides in the JavaScript Exception Hierarchy
JavaScript provides a number of core objects that allow for simple exception and error management. Error handling is typically done through the generic Error
object or from a number of built-in core error objects, shown below:
- Error
- InternalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- Cannot read property of undefined
As seen from the hierarchy above, TypeError
is a built-in JavaScript error object that allows for the administration of such errors. The “Cannot read property of undefined” TypeError
is a descendant of the TypeError
object.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!
We’ll often run into errors like “Cannot read properties of undefined (reading ‘id’)”. It’s one of the most common errors that developers encounter during web development. Let’s dig in and understand this error, what it means, and how we can debug it.
Breaking down the Message
TypeError: Cannot read properties of undefined (reading 'id')
In older browsers, this might also be shown as:
Cannot read property 'id' of undefined
TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object. In this case, our code expects to have an object with a id
property, but that object was not present. id
is commonly used on HTMLElement
, but it could be a custom data object from a remote API as well.
This is a blocking error, and script execution will stop when this error occurs.
Understanding the Root Cause
This error can be thrown for a lot of reasons, as it is not uncommon to look for the id
property of an element, or when iterating over a collection of data. For example, let’s say we’re looking for an element in the DOM and reading it’s id
.
For example, if we had a function that acts on a string argument, but is called without a string, we would see this error.
var myElement = document.querySelector('#my-element'); console.log(myElement.id);
But if the query #my-element
doesn’t exist in the document, we’ll get null
back, which obviously doesn’t have an id
property.
Alternatively, you might be making a network request that you expect to return a JSON object with an id
property.
fetch('/my/api') .then(resp => resp.json()) .then(json => console.log(json.id));
If the API returns an error object, or something else you don’t expect, json
may not be defined or not have the expected shape. Or, worse, if the API has a operational failure it can return an HTML error page instead of JSON, leading to errors like SyntaxError: Unexpected Token <
.
How to Fix It
So how do we fix this and prevent it from happening again?
1. Understand why your object is undefined
First and foremost, you need to understand why this happened before you can fix it. You are probably not doing exactly the same thing we are, so the reason your object is undefined may be somewhat different. Consider:
- Are you relying on a network response to be a certain shape?
- Are you processing user-input?
- Is an external function or library calling into your code?
Or maybe its just a logical bug somewhere in your code.
2. Add Defensive Checking
Anytime you don’t completely control the input into your code, you need to be defensively checking that arguments have the correct shape. API response change, functions get updated, and users do terrible, terrible things.
For instance, if you have a fetch
request that receives a JSON response with a foo
string property, you might have a defensive check that looks like this:
fetch("https://example.com/api") .then(resp => { return resp.json(); }) .then(json => { if (!json || !json.id) { // Record an error, the payload is not the expected shape. } });
3. Monitor Your Environment
You’ll need to make sure that the issue is really fixed and that the problem stops happening. Mistakes happen, APIs change, and users are unpredictable. Just because your application works today, doesn’t mean an error won’t be discovered tomorrow. Tracking when exceptional events happen to your users gives you the context to understand and fix bugs faster. Check out TrackJS Error Monitoring for the fastest and easiest way to get started.
Я работаю над большим проектом и больше не могу его запускать из-за этой ошибки:
Когда я запускаю npm run serve
ERROR TypeError: Cannot read property 'NormalModule' of undefined
TypeError: Cannot read property 'NormalModule' of undefined
at VueLoaderPlugin.apply (/Users/<user>/muso-ninjas/node_modules/vue-loader-v16/dist/pluginWebpack5.js:44:47)
at webpack (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/node_modules/webpack/lib/webpack.js:51:13)
at serve (/Users/<user>/muso-ninjas/node_modules/@vue/cli-service/lib/commands/serve.js:163:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Пожалуйста, помогите мне, потому что я застрял, и я хотел бы продолжить свой проект.
2 ответа
Лучший ответ
Попробуйте это сначала:
- В корне вашего проекта запустите
npm install
. Возможно, кто-то еще в вашем проекте изменил/добавил зависимость, и извлечение из вашего репозитория git дало вам код, который полагается на это, но не даст вам саму зависимость.
Если это не решит вашу проблему, попробуйте следующее:
- Удалите папку
node_modules
в корне вашего проекта. - Обновите версию Node.js до последней версии 16.x.
2.1 Убедитесь, что обновление работает, выполнивnode -v
в терминале. - Обновите
npm
: запуститеnpm i -g npm
в терминале.
3.1 Очень сработало обновление, выдавnpm -v
в терминале. - Запустите
npm install
в корневой папке вашего проекта.
Если это не решит вашу проблему, вам нужно обратиться за помощью к другому члену вашей команды.
3
connexo
22 Янв 2022 в 17:12
Как было предложено в ссылке из первого комментария, я удалил node_modules, заменил node-sass в package.json на «sass»: «^1.26.5» и запустил npm install, но это не сработало. .
Затем я повторил шаги и также удалил package-lock.json.
Это помогло, и приложение обслуживалось должным образом.
1
Andrey Yaroshenko
13 Фев 2022 в 12:17
The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined
. You can fix it by adding an undefined
check on the variable before accessing it.
Depending on your scenario, doing any one of the following might resolve the error:
- Add an
undefined
check on the variable before accessing it. - Access the property/method on a replacement for the
undefined
variable. - Use a fallback result instead of accessing the property.
- Check your code to find out why the variable is
undefined
.
1. Add undefined
check on variable
To fix the “cannot read property of undefined” error, check that the value is not undefined
before accessing the property.
For example, in this code:
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 the property access.
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:
const auth = undefined;
console.log(auth); // undefined
// ✅ No error
console.log(auth?.['user']?.['name']); // undefined
This means that we can use it on arrays:
const arr = undefined;
console.log(arr?.[0]); // undefined
// Array containing an object
console.log(arr?.[2]?.prop); // undefined
Note
Before the optional chaining was available, the only way to avoid this error was to manually check for the truthiness of every containing object of the property in the nested hierarchy, i.e.:
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.
For example:
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
The logical OR (||
) operator can also do this:
console.log(5 || 10); // 5
console.log(undefined || 10); // 10
3. Use fallback value instead of accessing property
Another way to solve the “cannot read property of undefined” 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 (??
).
For example:
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
.
It could be that you forgot to initialize the variable:
let doubles;
let 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.
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.
// ✅ "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 ]
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.
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 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.
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' ]
Conclusion
In this article, we saw some helpful ways of resolving the “cannot read property of undefined” error in JavaScript. They might not resolve the error totally in your case, but they should assist you during your debugging.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.
Ayibatari 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.
Hello Guys, How are you all? Hope You all Are Fine. Today I just updated my node to latest version. But As I updated to latest version my Project give me following error while running error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) in node. So Here I am Explain to you all the possible solutions here.
Without wasting your time, Let’s start This Article to Solve This Error.
Contents
- How error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error Occurs ?
- How To Solve error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error ?
- Solution 1: downgrade node to
v14.18.1
- Solution 2: Downgrade nodejs to 16.12.0
- Summary
I just updated my node to latest version. But As I updated to latest version my Project give me following error while running.
error: TypeError: Cannot read properties of undefined (reading 'transformFile')
How To Solve error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error ?
- How To Solve error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error?
To Solve error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error Simplest and easiest solution is Just downgrade node to
v14.18.1
. And then Just deletenode_modules
and then try to rebuild your project and your error must be solved. - error: TypeError: Cannot read properties of undefined (reading ‘transformFile’)
To Solve error: TypeError: Cannot read properties of undefined (reading ‘transformFile’) Error Simplest and easiest solution is Just downgrade node to
v14.18.1
. And then Just deletenode_modules
and then try to rebuild your project and your error must be solved.
Solution 1: downgrade node to v14.18.1
Simplest and easiest solution is Just downgrade node to v14.18.1
. And then Just delete node_modules
and then try to rebuild your project and your error must be solved.
Solution 2: Downgrade nodejs to 16.12.0
In my case I just downgrade my nodejs to downgrading to Node.js 16.12.0. and my error was solved.
Summary
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also, Read
- You haven’t been given access to cloud-managed distribution certificates
As a JavaScript developer, I’m sure you’ve encountered the frustrating runtime TypeError Cannot read properties of undefined
. TypeScript gives you two ways of interpreting null
and undefined
types, also known as Type Check Modes, and one of them can avoid this easily overlooked TypeError.
Until TypeScript 2.0, there was only one type check mode — regular — and it considersnull
and undefined
as subtypes of all other types. This means null
and undefined
values are valid values for all types.
TypeScript 2.0 introduced Strict Type Check Mode (also referred to as strict null checking mode). Strict Type Check differs from Regular Type Check because it considers null
and undefined
types of their own.
I’ll show you how Regular Type Check handles undefined
(the same applies to null
) and how Strict Type Check prevents you from introducing unwanted behavior in our code, like that infamous TypeError Cannot read properties of undefined
.
When undefined becomes a problem
The function translatePowerLevel below takes a number as argument and returns strings one
, two
, many
or it's over 9000!
.
function translatePowerLevel(powerLevel: number): string {
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
}
However, this code doesn’t handle 0, a valid input — yes, looking at you, Yamcha.
Yamcha’s Power Level
When JavaScript reaches the end of a function that has no explicit return, it returns undefined
.
The translatePowerLevel
function return value is typed explicitly as string
, but it is possibly also returning undefined
when the argument powerLevel
has the value 0. Why is TypeScript not triggering an error?
In Regular Type Check Mode, TypeScript is aware that a function might return undefined
. But at the same time, TypeScript infers the return type to be only of type string
because TypeScript is widening the undefined
type to string
type.
As another example, if you assign null
or undefined
to variables while in Regular Type Check Mode, TypeScript will infer these variables to be of type any
.
const coffee = null;
const tea = undefined;
Interpreting undefined
or null
as subtypes of all other types can lead to runtime problems. For example, if you try to get the length of the result of translateNumber(0)
, which is undefined
, JavaScript will throw this TypeError at runtime: Cannot read properties of undefined (reading 'length').
const powerLevel = translatePowerLevel(0); // undefined
console.log(powerLevel.length); // Uncaught TypeError: Cannot read properties of undefined (reading 'length')
Unfortunately, TypeScript’s Regular Type Check Mode is not able to alert you to when you may have made that mistake.
Strict Type Check Mode to the Rescue
Strict Type Check Mode changes how TypeScript interprets undefined
and null
values. But first, let‘s enable Strict Type Check Mode.
How to Enable Strict Type Check Mode in TypeScript
In the root of your project, there should be a tsconfig.json file
. This is the TypeScript’s configuration file and you can read more about it here.
// tsconfig.json example
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
Inside compilerOptions
property, all we need to do is add the property "strictNullChecks": true
.
It will look something like this:
// tsconfig.json
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true,
"strictNullChecks": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
Now that we have switched to Strict Type Check Mode, TypeScript throws this error for translatePowerLevel
function: Function lacks ending return statement and return type does not include 'undefined'
.
That error message is telling you the function is returning undefined
implicitly, but its return type does not include undefined
in it.
Awesome! TypeScript is now aware the return type does not match all possible return values, and this could lead to problems at runtime! But how can you match the return type to all possible return values?
You can either add a return statement so the function always returns a string
(solution #1), or change the return type from string
to string | undefined
(solution #2).
Match All Possible Return Values: Solution #1
Adding a return statement so it is always explicitly returning a value — in the code below, it is now returning the string zero
.
// Solution #1: add a return statement so it always returns a string
function translatePowerLevel(powerLevel: number): string {
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
// new return statement
return 'zero';
}
Match All Possible Return Values: Solution #2
Make the undefined
return type explicit so wherever translatePowerLevel
is used, you have to handle nullish
values as well.
// Solution #2: return type as string | undefined
function translatePowerLevel(powerLevel: number): string | undefined {
if (powerLevel === 1) {
return 'one';
}
if (powerLevel === 2) {
return 'two';
}
if (powerLevel > 2 && powerLevel <= 9000) {
return 'many';
}
if (powerLevel > 9000) {
return 'it's over 9000!';
}
}
If you were to compile the following code again using Solution #2, TypeScript would throw the error Object is possibly 'undefined'
.
const powerLevel = translatePowerLevel(0); // undefined
console.log(powerLevel.length); // Object is possibly 'undefined'.
When you choose a solution like Solution #2, TypeScript expects you to write code that handles possible nullish
values.
There’s no reason not to use Strict Type Check Mode
Now you understand how TypeScript interprets null
and undefined
types and how you can migrate your project to Strict Mode.
If you are starting a new project, you should definitely enable Strict Type Check Mode from the beginning. And in case you will migrate from Regular to Strict Type Check, our team can help with strategies to do so in a less painful way.
At Bitovi we highly recommend using — or migrating to — Strict Type Check Mode for Angular application development, as it can help you produce better, more reliable code.
Need more help?
Bitovi has expert Angular consultants eager to help support your project. Schedule your free consultation call to get started.