Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the position of braces in JavaScript matter? [duplicate]

Tags:

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?

like image 468
Md Nazmoon Noor Avatar asked Jun 09 '14 12:06

Md Nazmoon Noor


People also ask

Why we make block of statement using braces?

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.

When to use curly brackets Java?

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.


1 Answers

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).

like image 84
Denys Séguret Avatar answered Dec 01 '22 11:12

Denys Séguret