📢 Are you a TestProject user looking to migrate to an open source alternative?

Learn more
Uncaught TypeError: Cannot Read Property of Undefined in JavaScript cover

Uncaught TypeError: Cannot Read Property of Undefined in JavaScript

JavaScript (JS) is the most popular programming language and is ranked as one of the TOP 5 programming languages in the world. TypeScript is JavaScript with type syntax and is a strongly typed programming language based on JS that provides better tooling at any size. But, internally, it’s again JavaScript. Today almost everyone uses JavaScript for front-end web development, and frameworks such as React, Vue, and Angular made JavaScript even more popular.

Before getting in to the article to understand Uncaught TypeError in Javascript, one should understand basics about Javascript, lets go through it below.

What is JavaScript?

JavaScript is a lightweight, interpreted, and all-in-one compiled programming language with first-class functions. It is used chiefly as the scripting language for web pages. Earlier, it was restricted to only client-side scripting with NodeJS. Now, JavaScript is used for both front-end and back-end development of web applications. Since then, it has grown alongside new browsers such as Mozilla Firefox and Google Chrome. The latter even began creating V8, the first contemporary JavaScript engine that translates bytecode into native machine code.

Know More: Comparisons of Top 3 Javascript testing frameworks

Why do we need JavaScript?

JavaScript allows handling complex features of a webpage dynamically. The webpage typically contains three different parts; namely:

HTML: A markup language that provides the structure of a webpage or contents of a webpage. Such as header, footer, images, table, etc.

CSS: Also known as Cascading Style Sheets, CSS is used to style your webpage contents. Such as font, background color, and foreground color. The CSS also provides animations.

JavaScript: An essential part of any webpages, JavaScript can help you dynamically create and update the contents, handle the events, control multimedia, etc.

Advantages of JavaScript

Speed: The JavaScript application is much faster than any application not written in JavaScript.

Scripting Language: JavaScript is a powerful scripting language for web applications. It has become a core of web applications. JS supports both Client-side scripting and service-side scripting.

Interpreter Based: JavaScript doesn’t need any compiler. It is interpreter based. When you run the JS in the browser, the browser engine interprets and executes the JavaScript line by line. Unlike the compiled language like Java, C#, and C++, the code must be compiled first before executing it, but JavaScript doesn’t require it to be compiled.

Event Handling: The event is an action in a system that needs to be handled/responded to. For example, a click is an event: when the user clicks on the button, the click event is triggered and responded to with an alert box. JavaScript can handle such events efficiently and allows you to create custom events.

Control Statements: JavaScript provides the control statements like if-else, switch, etc. It also provides the loop statement such as while, for, and for-each. This helps to write complex logic.

Higher Order Functions: The function that returns a function is called a higher-order function, and JS supports higher-order functions.

Dynamic Typing: One of the essential features of JavaScript. The declaration of a variable is optional. JavaScript doesn’t require the declaration of the variable during the assignment of value. JS determines the type of the value and creates the variable accordingly. That means no need to specify the string, integer, etc. explicitly.

Async Function: JavaScript supports async functions. The async and await keywords enable the asynchronous, promise-based behavior to be written in a clear style—no need to configure the promised change explicitly.

Versatility: JavaScript can be used for both front-end and back-end web development.

Disadvantages of JavaScript

Client-side Security: JavaScript is viewable to the user; some may use it for malicious purposes. It’s easy to identify the application flaws (if any) and inject the malicious code.

Browser Compatibility: The JavaScript code interpretation varies from browser to browser. The code must be thoroughly tested. The older version of the browser might not support some new functionalities. There are also chances that the more recent browser version might lack the support for older functionalities due to security or any reason.

Debugging: Though there are many debugging tools, the console is still the favorite debugging tool for JavaScript. The debugging is considerably tricky compared with other languages.

JavaScript Error Types

JavaScript has the standard built-in objects, a predefined set of objects that helps to develop faster. Undefined is the most error-prone of the six primitive types defined in JavaScript: Boolean, String, Symbol, BigInt, Null, and Undefined.

The problem frequently occurs when the scripts encounter an uninitialized variable or object.

As we are discussing the Error Uncaught TypeError: Cannot read property of undefined, let’s understand the JavaScript built-in error first, then jump to the TypeError.

Error objects are thrown during the runtime errors. This object can also be used as a base object for user-defined exceptions. There are many built-in error objects in JavaScript other than Generic Error.

RangeError

The RangeError object is an error thrown when a value is not in the set or range of allowed values.

Common Scenarios:

  • When you try to create an array of illegal lengths using the Array Constructor
  • Passing non-allowed values to numeric methods such as toExponential(), toPrecision(), and toFixed()
  • Passing non-allowed values to string functions like normalize()

ReferenceError

The Reference Error object indicates an error when a variable that doesn’t exist (or hasn’t yet been initialized) in the current scope is referenced.

Example Error Message: ReferenceError: assignment to the undeclared variable “s”

Common Scenarios:

  • Typo in the variable name
  • When you try to access the variable outside their scopes
  • Referencing a global variable from an external library before it is loaded

SyntaxError

The Syntax Error object indicates an error when trying to interpret syntactically invalid code. It is thrown when the JavaScript engine encounters token or token order that does not conform to the syntax of the language.

Example: Uncaught SyntaxError: Invalid or unexpected token

Common Scenarios:

  • Missing inverted commas
  • Missing Parenthesis, braces
  • Illegal usage of special characters

TypeError

The TypeError occurs when a variable or parameter is not of a valid type.

Common Scenarios:

  • Invoking objects that are not methods
  • Attempting to access properties of null or undefined objects
  • Treating a number as a string or vice versa

Few other common Error Type in JavaScript includes

URIError: The URIError indicates that the global URI handling function was used in the wrong way.

AggregateError: The Aggregate Error is an error when several errors are wrapped into a single error. The aggregate error is useful when multiple errors need to be reported by an operation.

JavaScript is the most flexible language; besides the standard set of Error Types, it also allows custom errors. You can always create a new error type in JavaScript if your requirement is not in the standard error list. Now lets understand about Uncaught TypeError below,

The TypeError: Cannot read property of undefined 

The most common Error in JavaScript is TypeError: Cannot read property of undefined. The “TypeError: Cannot read property of undefined” belongs to the TypeError category in JavaScript. Usually, you get the error message something similar to below

TypeError: Cannot read properties of undefined (reading x)

Causes for TypeError: Cannot Read Property of Undefined

The error clearly says that it is Undefined, which means the variable might be declared or used. Still, there is no value associated with the variable. In short, the value is not assigned.

In JavaScript, properties or functions are Objects, but undefined is not an object type. If you call the function or property on such variable, you get the error in console TypeError: Cannot read undefined properties.

Example of Type Error

Let’s understand the TypeError: Cannot read property of undefined

function someFunc(y) {
console.log(y.x);
}
var someVar;
someFunc(someVar);

Consider the above example,

var someVar: we have declared the someVar, but there is no value associated with it.

someFunc(someVar): This function call passes the someVar to the someFunc. In our case, the variable someVar doesn’t have any value as we have not assigned it, so by default, it’s undefined.

console.log(x.y): Inside the someFunc(), we have console.log, which is trying to access the value of x that belongs to someVar or y. Since the y is undefined, now if you execute this code, you will get the message TypeError: Cannot read properties of undefined (reading ‘x’)

The solution to TypeError: Cannot read properties of undefined 

  • Always conditionally check for the variable that is undefined before accessing the value.

The root cause of the error is that the declared variable doesn’t have any value, so by default, JavaScript treats all variables as undefined if you don’t assign the value. When you write the code, ensure that you have an if check added before accessing.

Code Snippet:

function someFunc(y) {
            if(y!==undefined){
                console.log(y.x);
            }
}

var someVar;
someFunc(someVar);

In the above code, we have modified the someFunc() with the if condition, which checks for undefined.

if(y!==undefined): This line of code checks if the variable is undefined or has the value. Since we have added the if condition, if there is no undefined, then only the control moves to the next statement and prints the console; accidentally, if you forget to assign the value, then the if condition validates and doesn’t throw any error.

  • Ensure the variable has been assigned a value before accessing them.

The TypeError typically occurs when the variable does not have any assigned value. When you write the code, you must ensure that the variable you pass has a valid assigned value.

You can modify the code as follows:

function someFunc(y) {
       console.log(y.x);
}

var someVar = {
      x: 'Testsigma'
};

someFunc(someVar);

In the above code, we have assigned the value to someVar, which now has valid values; when you pass it to the someFunc, it doesn’t cause any error.

The best solution, solution 1, hides the error, and solution 2 addresses the error. The error is caused inside the someFunc(). The someFunc() can be accessed by some other places as well. The best way to avoid the TypeError: Cannot read properties of undefined JavaScript Error is to combine solutions 1 and 2, which always ensures you have a valid value assigned to a variable and always have an if check before accessing the variable.

The code looks like the below:

function someFunc(y) {
       if(y!==undefined){
               console.log(y.x);
        }
}

var someVar = {
      x: 'Testsigma'
};

someFunc(someVar);

In the above code, we have assigned the value to the variable, and we are also checking if the passed variable has an undefined value.

Now ,its clear how to fix Uncaught TypeError, below we can go through the points to avoid the Javascript errors.

Guidelines to Avoid the Errors in JavaScript

  • Have a coding standard checklist and make it mandatory for developers before pushing the code to the repository.
  • Peer Review greatly helps to avoid any mistakes that developers make. Peer Reviews are also a great way to bring and monitor the standards for your framework.
  • If your team has Junior resources or resources with fewer skills, consider Pair Programming. It is the best way to enforce the standards and increase learning.
  • Consider Unit Testing is the best way to catch errors or bugs in the early stage. Unit testing also helps in avoiding regressions.
  • Have a mechanism to log the error. Logging errors sometimes cause a security risk, but you can log the custom error messages, which helps you to trace back and quickly fix the errors.

In the above article , not only you learnt Uncaught TypeError in Javascript but also all Errors in Javascript and how to minimize those bugs.

The above guidelines can minimize the bugs occurring when delivered but guarantee no future bugs. The only way to eliminate the error is through thorough application testing. Testing is time-consuming and needs more effort if it is done manually. Nowadays, many organizations are moving towards Test Automation since the same code can run on multiple browsers without additional effort. One of the challenges of modern test automation is that many tools are available, and every tool requires expertise. Organizations are spending a lot on upskilling resources. Since testing is moving towards automation, manual testers have difficulties adapting and learning new technologies. Some tools like Testsigma allow testers to write the script in basic English and make it easier to transform the testers.

The Record and playback feature helps beginners to upskill their skillsets rapidly and deliver better. Testsigma understands the pain points of both testers and managers. The tester doesn’t want to spend much time learning; the manager needs faster testing and sound reports to highlight the issues. Testsigma provides Summary Reports, Trends, Automated Bug Reporting, etc., making life easy for managers and stakeholders, while codeless automation makes testers’ lives better.


Test automation made easy

Start your smart continuous testing journey today with Testsigma.

SHARE THIS BLOG

RELATED POSTS