Typeerror cannot read property of undefined javascript

Uncaught TypeError: Cannot read property ‘value’ of undefined

Seems like one of your values, with a property key of ‘value’ is undefined. Test that i1 , i2 and __i are defined before executing the if statements:

var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = ; if(i1 && i2 && __i.user && __i.pass) < if( __i.user.value.length >= 1 ) < i1.value = ''; >else < i1.value = 'Acc'; >if( __i.pass.value.length >= 1 ) < i2.value = ''; >else < i2.value = 'Pwd'; >> 

Either document.getElementById(‘i1’) , document.getElementById(‘i2’) , or document.getElementsByName(«username»)[0] is returning no element. Check, that all elements exist.

thanks. i forget that when user is logged in , there is no input named username or password. i have added if statement ‘ if(i2 && i2) ‘ and it works.. sometimes easiest code may get you in trouble 😀

Try this, It always works, and you will get NO TypeError:

try< var i1 = document.getElementById('i1'); var i2 = document.getElementById('i2'); var __i = ; if( __i.user.value.length >= 1 ) < i1.value = ''; >else < i1.value = 'Acc'; >if( __i.pass.value.length >= 1 ) < i2.value = ''; >else < i2.value = 'Pwd'; >>catch(e) < if(e)< // If fails, Do something else >> 

Thanks for showing the proper way of doing this. Althought I’m curious why the if(e) needs to be inside catch(e) since it already caught the (e)

Читайте также:  Parameters must have type annotation kotlin

@TetraDev ‘e’ will return ‘undefined’ unless it’s a valid TypeError. So you validate the TypeError in the ‘if’ statement and you can also execute custom TypeErrors.

You get no TypeError, nor any other errors, because you’ve caught them all and swallowed them. The least you could do is check what the error is and rethrow if you don’t know.

First, you should make sure that document.getElementsByName(«username»)[0] actually returns an object and not «undefined». You can simply check like

if (typeof document.getElementsByName("username")[0] != 'undefined') 

Similarly for the other element password.

The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property ‘value’ of undefined issue.

There are already here many answers which are correct, but what we don’t have here is the combination for 2 answers that i think resolve this issue completely.

function myFunction(field, data) < if (typeof document.getElementsByName("+field+")[0] != 'undefined')< document.getElementsByName("+field+")[0].value=data; >> 

The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.

Источник

Resolving TypeError: Cannot Read Property of Undefined in JavaScript

Resolving TypeError: Cannot Read Property of Undefined in JavaScript

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.

Error message:

TypeError: Cannot read properties of undefined (reading x)

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:

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)

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

    Rollbar in action

    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!

    Источник

    Почему возникает ошибка: Uncaught TypeError: Cannot read property of undefined or null (reading ***)

    Периодически, при разработке на JavaScript возникает ошибка: Cannot read property *** of undefined или Cannot read property *** of null Например в этом коде:

    const count = result.data.length; 
    const dataMap = response.lines.map(item => item * 2); 

    1 ответ 1

    Cannot read property of undefined/null (reading ‘method’)

    Ошибка нам говорит, что мы пытаемся вызвать свойство или метод method объекта, в то время, как сам объект являет null или undefined

    Рассматривать будем на примере данного объекта

    Ошибка возникнет, если мы попытаемся выполнить следующий код:

    data.errors.forEach(item => console.log(item)); // null.forEach() 

    Uncaught TypeError: Cannot read properties of null (reading ‘forEach’)

    data.values.map(item => console.log(item)); // undefined.map() 

    Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

    Данные ошибки говорят нам о том, что мы пытаемся вызвать методы у ничего(null или undefined).
    data.errors это null. У null нет методов. А data.values вообще не существует. Нельзя вызвать метод у того, что не существует.

    Так же, если объявить переменную и попытаться вызвать у нее какой либо метод без инициализации, то получим ошибку(в данном случае Cannot read properties of undefined (reading ‘push’)):

    const arr; arr.push(1); // undefined.push(); 

    Cannot read property

    of undefined — ключ не определен, т.е. отсутствует в объекте.
    of null — ключ в объекте есть, но имеет значение null. У null нет методов.

    Как понять, где возникла ошибка?

    file:///C:/dev/nodeserver/SO/11.js:10 // Номер строки data.errors.forEach(item => console.log(item)); // null.forEach() ^ TypeError: Cannot read properties of null (reading 'forEach') at ←[90mfile:///C:/dev/nodeserver/SO/←[39m11.js:10:13 ←[90m at ModuleJob.run (node:internal/modules/esm/module_job:193:25)←[39m at async Promise.all (index 0) ←[90m at async ESMLoader.import (node:internal/modules/esm/loader:533:24)←[39m ←[90m at async loadESM (node:internal/process/esm_loader:91:5)←[39m ←[90m at async handleMainPromise (node:internal/modules/run_main:65:12)←[39m 

    Здесь at ←[90mfile:///C:/dev/nodeserver/SO/←[39m11.js:10:13 мы видим номер строки с ошибкой и позицию, где произошла ошибка.

    В браузере это выглядит так:

    Uncaught TypeError: Cannot read properties of null (reading 'forEach') at 123.html?_ijt=vkfkm1ubo3ut5c02m72ihg4lgu:72:15 

    где 72 это номер строки, а 15 это точка, где возникла ошибка.

    Как этого избежать?

    Проверять, что приходит в объекте и существуют ли в объекте нужные нам значения. Один из вариантов проверки, воспользоваться console.log() .
    Можно начать с последнего ключа, однако лучше весь пусть вывести, что бы понимать структуру, с которой работаем:

    console.log(data) // < name: 'TypeError', message: '', errors: null, sayHi: [Function] >console.log(data.errors) // null 

    Так же можно воспользоваться оператором необязательной цепочки вызовов ‘?.

    const a = data?.errors?.forEach(item => console.log(item)); // null.forEach() const b = data?.values?.map(item => console.log(item)); // undefined.map() 

    Оператор необязательной цепочки вызовов будет проверять значение слева. Если значение null или undefined , цепочка прерывается и возвращается значение undefined.

    Для объявленных переменных указывать тип данных

    const arr = []; // Указываем, что меременная это массив arr.push(1); // Можем воспользоваться любым методом массива; 

    Источник

Оцените статью