Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this throw an error [JavaScript]?

Tags:

javascript

If you run this code in your console:

(function(){
    test: "hello";
})();

Or even this:

test: "hello";

Nothing happens, and no error is thrown. Why? Is it as simple as, "Well... It's JavaScript... Deal with it."?

For context, some interns at my company wrote something similar by accident (meaning to use '='). When confronted that it would probably throw an error, they said it hadn't.

And now I'm curious.

like image 256
Fully Avatar asked Dec 15 '22 05:12

Fully


1 Answers

Any statement (including one which creates a string literal and then doesn't do anything with it) in JavaScript can have a label (see ECMAScript 2015 or MDN). It just isn't much use unless you have nested loops that you want to break or continue from.

(function(){     // Begin function expression
    test:        // Label statement
       "hello";  // Create a string and do nothing with it
})();            // End function expression and invoke the created function
like image 55
Quentin Avatar answered Jan 02 '23 13:01

Quentin