Consider these two functions.
function func1() { return { foo: 'bar' } } function func2() { return { foo: 'bar' } }
alert(typeof func2()) //return object
alert(typeof func1()) //return undefined
Why does the position of the braces matter when in many other languages it does not? Is it a language feature or a bug?
Braces improve the uniformity and readability of code. More important, when inserting an additional statement into a body containing only a single statement, it is easy to forget to add braces because the indentation gives strong (but misleading) guidance to the structure.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
Because of automatic semicolon insertion. The first code is the same as
function func1() { return; { foo: 'bar' } }
If you wonder why this code doesn't produce a syntax error, foo:
is a label.
Regarding
Is it a language feature or a bug?
It's a feature. But a very dangerous one. The best way to keep it being a feature for you is to stick to consistent formatting style (I'd suggest to use the Google style guide until you're experienced enough to make your own).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With