How is it that the sum of 2 and  40 equals to 42?

My mind was completely blown when my coworker showed me this JavaScript code that alerts 42.

alert(2+ 40);

I soon discovered that the seemingly negative sign is actually a mysterious Unicode character with unique functions.

This discovery led me to question why this character doesn't trigger a syntax error during parsing. It made me curious about whether there are other characters out there with similar behavior.

Answer №1

That particular character identified as "OGHAM SPACE MARK", serves as a space character. Hence, the code can be simplified to alert(2+ 40).

I am curious if there are other characters that exhibit this behavior.

In JavaScript, any Unicode character categorized under the Zs class is recognized as a white space character according to standards. As of now there don't appear to be many such characters.

Additionally, JavaScript has provisions for using Unicode characters in identifiers, enabling the use of intriguing variable names like ಠ_ಠ.

Answer №2

After reviewing the responses provided, I developed a straightforward program to identify all Unicode characters within the range U+0000–U+FFFF that act as white spaces. It appears that there are approximately 26 or 27 such characters, with discrepancies surrounding U+0085 and U+FFFE.

It is important to note that many of these characters simply resemble a standard white space.

function isSpace(ch)
{
    try
    {
        return Function('return 2 +' + ch + ' 2')() === 4;
    }
    catch(e)
    {
        return false;
    }
}

for (var i = 0; i <= 0xffff; ++i)
{
    var ch = String.fromCharCode(i);
    if (isSpace(ch))
    {
        document.body.appendChild(document.createElement('DIV')).textContent = 'U+' + ('000' + i.toString(16).toUpperCase()).slice(-4) + '    "' + ch + '"';
    }
}
div { font-family: monospace; }

Answer №3

It seems that the character you are using is longer than the minus sign (hyphen).

 
-

The top shows what you're using, the bottom shows the correct minus sign. You already know this, so let's explore why Javascript behaves this way.

The character you're using is actually the ogham space mark, a whitespace character interpreted as a space by Javascript. So your statement looks like alert(2+ 40) to Javascript.

Javascript has other characters like this; see a full list here on Wikipedia.


I noticed an interesting behavior of this character in Google Chrome and possibly other browsers' address bars.

The bar displays a block with 1680 inside - the unicode number for the ogham space mark. It might just be my machine, but it's peculiar.


I tested this in various languages with these results:


Languages where it fails:

Python 2 & 3

>> 2+ 40
  File "<stdin>", line 1
    2+ 40
        ^
SyntaxError: invalid character in identifier

Ruby

>> 2+ 40
NameError: undefined local variable or method ` 40' for main:Object
    from (irb):1
    from /home/michaelpri/.rbenv/versions/2.2.2/bin/irb:11:in `<main>'

Java (inside the main method)

>> System.out.println(2+ 40);
Main.java:3: error: illegal character: \5760
            System.out.println(2+?40);
                                 ^
Main.java:3: error: ';' expected
            System.out.println(2+?40);
                                  ^
Main.java:3: error: illegal start of expression
            System.out.println(2+?40);
                                    ^
3 errors

PHP

>> 2+ 40;
Use of undefined constant  40 - assumed ' 40' :1

C

>> 2+ 40
main.c:1:1: error: expected identifier or '(' before numeric constant
 2+ 40
 ^
main.c:1:1: error: stray '\341' in program
main.c:1:1: error: stray '\232' in program
main.c:1:1: error: stray '\200' in program

exit status 1

Go

>> 2+ 40
can't load package: package .: 
main.go:1:1: expected 'package', found 'INT' 2
main.go:1:3: illegal character U+1680

exit status 1

Perl 5

>> perl -e'2+ 40'                                                                                                                                   
Unrecognized character \xE1; marked by <-- HERE after 2+<-- HERE near column 3 at -e line 1.

Languages where it works:

Scheme

>> (+ 2  40)
=> 42

C# (inside the Main() method)

Console.WriteLine(2+ 40);

Output: 42

Perl 6

>> ./perl6 -e'say 2+ 40' 
42

Answer №4

It seems like the reason for this behavior has something to do with how it is classified as whitespace:

$ unicode  
U+1680 OGHAM SPACE MARK
UTF-8: e1 9a 80  UTF-16BE: 1680  Decimal: &#5760;
  ( )
Uppercase: U+1680
Category: Zs (Separator, Space)
Bidi: WS (Whitespace)

Answer №5

I would like to know if there are other characters who exhibit similar behavior.

I recall coming across an article that talked about replacing semi-colons (U+003B) with the Greek question mark (U+037E) as a mischievous prank in someone's code.

Although both characters look identical (so much so that even Greeks use U+003B), the article mentioned that one of them does not function the same way.

You can find more information on this topic on Wikipedia here: https://en.wikipedia.org/wiki/Question_mark#Greek_question_mark

There is also a closed question on using this prank on Stack Overflow, although that wasn't where I originally read about it: JavaScript Prank / Joke

Answer №6

When it comes to compiling this expression, most languages shy away. However, my curiosity led me to test Rust's compiler on the matter. Known for its strictness, Rust often imparts knowledge and wisdom in a gentle manner.

So I decided to see how it would handle this:

fn main() {
    println!("{}", (2+ 40));
}

And here is what the compiler had to say:

error: unknown start of token: \u{1680}
  |
  |     println!("{}", (2+ 40));
  |                       ^
  |
help: Unicode character ' ' (Ogham Space mark) looks like ' ' (Space), but it is not

In contrast, JavaScript (tested with the latest and most commonly used browser today) appears to be more lenient towards that character, simply ignoring it.

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

Ways to store information using VueJS lifecycle hooks

I am currently working on setting a data property using the created lifecycle hook within my component. The issue I'm encountering is receiving a "TypeError: Cannot read property 'summary' of undefined" in the console as I run the code. This ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

"Can you explain the concept of an undefined id in an AJAX request

Within my mongodb database, I have two Tables: GstState Store While working on my Store form, I encountered an issue where the JSON response was returning an undefined id when trying to select a state based on country via an ajax call to fetch GstStates ...

Adding an HTML element to the DOM in an AngularJS directive without using jQuery

Looking to enhance my AngularJS directive by including an svg tag within the current element, currently using jQuery for this purpose. link: function (scope, iElement, iAttrs) { var svgTag = $('<svg width="600" height="100" class="svg">< ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

utilizing the dropdown label for validating the value of another dropdown

I'm facing a challenge with two dropdowns: <select name="first_value" id="first_value"> <option value="<?php print"$sum_jan" ?>">January</option> <option value="<?php print"$sum_feb" ?>">February</option ...

Tips on emphasizing the mouse pointer location in three.js

Looking for a way to display a circle on top of a .fbx model rendered in ThreeJS based on the mouse-pointer's position. Struggling to find an example. Is this accomplished through shaders? If so, how can it be done? ...

A Foolproof Method to Dynamically Toggle HTML Checkbox in ASP.NET Using JavaScript

Although there have been numerous inquiries related to this subject, I haven't been able to find a solution specific to my situation. I currently have a gridview that contains checkboxes. What I'm trying to achieve is that when I select the chec ...

The Epub text box feature is malfunctioning

I have a quiz task in an epub format where users need to enter their answers in a text box after reading the question. However, I am facing an issue where the text box does not display the keyboard for typing the answer. Is there a solution using javascr ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Tips for achieving a seamless transition between elements of varying heights in your Bootstrap carousel

I'm currently working on a Bootstrap carousel project with slides of varying heights. The transition animation between slides is quite choppy due to the different sizes of content. I'm looking for a solution to make the transition smoother and mo ...

Node.js server continues running after attempting to stop with ctrl + C following starting the server using the command "npm start"

Whenever I initiate my server by typing node app.js in the command line on Git Bash, I can stop it simply by using ctrl + C. In my package.json file, I have configured a start script that allows me to use the command npm start to kickstart the server: "s ...

Exploring the universal scope in NodeJS Express for each request

I am working with a basic express server that is in need of storing global variables during request handling. Specifically, each request involves multiple operations that require information to be stored in a variable like global.transaction[]. However, u ...

Using Laravel, how can I retrieve the specific user ID associated with an element?

I am seeking a solution to retrieve the User ID from the users table using either JavaScript or Laravel. But why do I need it? The reason is that I want to populate a modal window popup with specific user information. I currently have 10 users, each with ...

Exploring arrays with JavaScript and reading objects within them

Recently, I received assistance from a member of StackOverflow regarding AJAX calls. However, I have encountered a problem now. The code consists of a loop that sends requests to multiple REST APIs and saves the results in an array as objects. The issue ...

Navigating through tabs in a Meteor application: How to maintain the active tab when using the back button

I am working on a multi-page meteor application where each page includes a navigation template. To switch between pages, I am using iron-router. The user's current page is indicated by setting the appropriate navigation link's class to 'ac ...

At times, the status code 0 and ready state 0 is returned by Ajax file uploads

After carefully reviewing the following thread: jQuery Ajax - Status Code 0? I was unable to find a definitive solution to my issue. Therefore, I am reaching out here in hopes that someone can guide me in the right direction. In my code, I have an Angul ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Top method for creating integration tests in React using Redux and Enzyme

Currently, I am working on setting up integration tests within my application. There are a few API calls that occur both when the component mounts and upon a button click. The response from these API calls is stored in the app's store, which then upd ...