TypeError: getFullYear() Is Not A Function In JavaScript – How To Fix?

TypeError: getFullYear() is not a Function in JavaScript

If you are getting the TypeError: getFullYear() is not a function in JavaScript, then don’t worry. This error is not difficult to fix. Here are some examples of this error, and I will show you how to fix it quickly and effectively.

Why does the TypeError: getFullYear() is not a function in JavaScript happen?

The “TypeError: getFullYear() is not a function” in JavaScript is a common error. It happens when you use the getFullYear() method with incorrect syntax, use a different date object to call the method, … etc.

Example:

var num = 14387912987987;
var str = "Hello world!!";
var date = new Date();
var yearNum = num.getFullYear() // Error
var yearStr = str.getFullYear() // Error

The error message occurs as follows:

Uncaught TypeError: num.getFullYear is not a function

How to fix this error?

To avoid encountering the Uncaught TypeError: getFullYear is not a function, you first need to write the correct syntax of the getFullYear() method.

Syntax:

Date.getFullYear()

Here are some solutions that will help you fix this error.

Initialize a new date to call the method

With this solution, we won’t be afraid that the variable we use to call the method is not a date anymore, and then our error won’t be thrown anymore.

Example:

var num = 14387912987987;
var str = "Hello world!!";
var yearNum = new Date(num).getFullYear();
console.log(yearNum);

// New Date(str) ==> Invalid Date
var yearStr = new Date(str).getFullYear();
console.log(yearStr);

Output:

2425
NaN

In this example, after I initialize the new date with the created variables, the program will throw an error if we don’t do this, because the above variables are not dated objects.

In the above example, with a variable of type string we passed to the constructor that is not a date format string, the generated date will be invalid, and the result will return a variable with a value of NaN.

Check if the object has a getFullYear() method

For this method, you use a conditional statement to check whether the variable we passed in is an object and has a getFullYear() method.

Example:

function checkHasgetFullYear(variable) {
	// Check if there is The getFullYear() method
	if (typeof variable == "object" && variable !== null && 'getFullYear' in variable) {
		console.log(variable.getFullYear())
	} else {
		console.log("The getFullYear() method cannot be used")
	}
}

checkHasgetFullYear(num);
checkHasgetFullYear(str);
checkHasgetFullYear(date);

Output:

The getFullYear() method cannot be used
The getFullYear() method cannot be used
2022

Summary

In this article, I have given some examples and ways to fix the TypeError: getFullYear() is not a function in JavaScript. Let’s try these methods, I hope they are helpful for you. Good luck!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *