What is the reason behind the TypeError thrown when attempting to assign to `NaN` or `undefined` in JavaScript

A.S.: The question pertains to the type of error rather than the phenomenon itself

"use strict" results in a TypeError when system variables like NaN and undefined are modified.
But why is it categorized as a TypeError instead of a SyntaxError?


Edit: In reality, this is not a SyntaxError because there are no syntax errors in the code snippet.
The actual issue lies in the fact that certain protected objects cannot be altered manually; therefore, it could be considered an AccessError although such designation does not officially exist.
So, why do access-errors manifest similarly to type-errors?

Answer №1

Within ES5, there exist 6 distinct categories of native errors:

  • EvalError

    The presence of this exception is not currently utilized in this specification. It continues to be included to maintain compatibility with earlier versions of the specification.

  • RangeError

    Signifies that a numeric value has surpassed the allowable range.

  • ReferenceError

    Demonstrates that an invalid reference value has been identified.

  • SyntaxError

    Indicates the occurrence of a parsing error.

  • TypeError

    Specifies that the actual type of an operand differs from the expected type.

  • URIError

    Shows that one of the global URI handling functions was used in a manner conflicting with its definition.

In your situation, the error emerges when attempting to allocate a value to window.NaN or window.undefined, both non-writable properties.

Prior to assignment, the internal [[Put]] method verifies [[CanPut]], which returns false due to the property being non-enumerable. Consequently, [[Put]] will trigger an exception.

The core issue lies in the writability of the assigned reference (left operand in the assignment expression) differing from expectations. In light of the 6 aforementioned error types, TypeError appears most suitable, despite writability not aligning precisely with a type.

Answer №2

The reason why you cannot assign values to NaN and undefined is because they are considered as read-only properties of the window object. These are not operators (such as > or +) or keywords (like var or class).

If you try to assign a value to NaN, Chrome will throw the following error:

TypeError: Cannot assign to read only property 'NaN' of object '#<Window>'

Answer №3

It presents a valid argument that lacks coherence, albeit on the semantic level rather than the syntactic.

Consider this analogy:

1+1=42

While clearly incorrect, this equation is flawed in a different manner compared to:

42 1 1 + =

The former can be interpreted as an arithmetic statement (one plus one equals forty-two), whereas the latter is incomprehensible.

In a similar vein, the code snippet NaN=300; seems plausible in Javascript, equating `NaN` to 300. However, upon execution, the engine rejects it with a resounding "Nope, cannot perform this operation".

Answer №4

Oops, something went wrong
When you see a syntax error in your code, it usually means you've misplaced an operator or used it incorrectly.
To learn more about "syntax errors", check out this article: https://en.wikipedia.org/wiki/Syntax_error

Mismatched data types
Type errors occur when a specific data type does not match the requirements of the program.
For detailed information on "data types", refer to this article: https://en.wikipedia.org/wiki/Data_type

Therefore, the type error is triggered because NaN and undefined are global constants representing data types with fixed values, and "strict mode" ensures their immutability to avoid potential issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Breaking down setInterval IDs for their corresponding function parameters

I plan on running multiple setIntervals, and though there may be a more efficient way to do it, that's something I'll consider later down the line. Is there a method for achieving this? var a = setInterval(function(a){ console.log(a); c ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

The iterator is not iterable because the object is an integer and the reason is unknown

Recently, I embarked on the journey of programming and encountered a code that involved finding the smallest value among 10 integer inputs. Here is my code: x, y = 0, 0 while x < 10: n = int(input()) y += n x += 1 print(y) s = min(y) prin ...

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

How can Swiper efficiently display the next set of x slides?

After exploring SwiperJS at https://swiperjs.com/, I've been unable to locate an option that allows the slide to return immediately to the right once it goes out of view on the left. The current behavior poses a problem where there is no next slide o ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

The SelectedIndexChanged event fails to trigger following an onchange event

I am currently working on validating a dropdown list on the client side based on its selected index/value. My goal is to create a function that triggers an alert when the selected index is 0, or alternatively execute the SelectedIndexChandged method in the ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

Place a call directly from the webpage

Is there a way to initiate a phone call using JavaScript? I've tried the code below: document.location.href = "tel:15555551212" While this code takes me to the dial screen of the mobile application, I actually want to place the call directly. Any ...

Can you explain the significance of the ColSpan property in the Material UI TablePagination?

Why is ColSpan used in this code snippet? Reference: https://material-ui.com/components/tables/#table Check for the arrow symbol <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, ...

Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked. I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clic ...

The statusMessage variable is not defined within the "res" object in a Node Express application

I am currently developing a Node.js & Express.js application and I am in need of creating a route to display the app's status. router.get('/status', function(req, res) { res.send("Current status: " + res.statusCode + " : " + res.stat ...

What is the technique for filtering multiple values using the OR operation in ng-model functions?

Currently, I am using an ng-modal labeled as "myQuery." At the moment, there are two filters in place that look like this: <accordion-group heading="" ng-repeat="hungry_pets in Pets" | filter:{hungry:false} | filter:{name:myQuery}" ... > I have ...

Here is how you can include a date picker with the ability to choose the day, month, and year

Can someone help me create a datepicker with options to select days, months, and years? I've been able to find resources for selecting months and years, but I'm having trouble adding the option to choose specific days. If anyone has experience ...

Error: Attempting to access a property of an undefined value, please verify the key name is

Attempting to incorporate dynamic elements into the assignment, I have written the following code: var contentList = Object.keys(content)[0]; $scope.model.currentLoadedContent[contentList] = content[Object.keys(content)[0]] When trying to execute the seco ...

``I'm having trouble getting the onchange event to function properly in a customized

After following a tutorial, I successfully created a custom select dropdown using the provided link. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select However, I am facing an issue with the onchange event not working for the select ...

Is there a way for me to initiate another joyride adventure?

Encountering a challenge with my joyride tour - after completing one tour, I aim to commence a second. Despite attempting to trigger the second tour in the postRideCallback function, I find myself stuck in a loop with the first tour. Seeking guidance on re ...

The x-axis in c3.js is experiencing issues with plotting when there is interval data in DST time

Trying to create a graph using the c3.js library with an x-axis interval of time. The intervals are determined by selecting a date range in the date picker. For example, if we select the dates 2016-03-13 00:00 to 2016-03-13 04:00, we add 15 minutes to ...