Everything About Curly Braces in JS

In code we find many different characters that help us distinguish its individual elements. In my opinion, curly braces deserve special attention, because they play several different roles in JS code.

Curly braces

From this article you will learn:

  • In which language were curly braces used for the first time?
  • How can we create objects in JS?
  • What is a code block?
  • What are labels in JavaScript and how do they work?
  • How does object destructuring work in JS?

We usually start learning a foreign language by getting to know its basic vocabulary. As our level increases, we try to touch more and more complex aspects of it, its exceptions and oddities - in other words, its grammar.

Programming languages also have their grammar, which is nothing more than the syntactic correctness of the code we write. So what is code made of? In principle, the answer is very simple - expressions and statements. Expressions in code are the equivalent of sentences. I will risk saying that writing a program is like writing a story. The better the sentences, the more interesting the story.

In natural languages, to achieve the intended effect, we use punctuation and language devices such as metaphors and paraphrases, and we divide the story into paragraphs and chapters. In code we can find many analogies - classes and objects as chapters, blocks as paragraphs, semicolons and brackets as punctuation marks.

I could probably write quite a lot about syntax itself in general terms, but today I would like to focus on one kind of character used in JavaScript code, namely curly braces.

Famous Curly Braces

I would not be myself if I did not start this story from the beginning - that is, from the 1960s. Until the 1960s, code was written using only two kinds of brackets: parentheses () and square brackets []. This quickly became problematic, because programs were becoming more and more complex, and the code became confusing as a result.

The first language that introduced a new punctuation mark, {}, was BCPL (Basic Combined Programming Language). BCPL was designed in 1967 by Martin Richards at the University of Cambridge. The language laid the groundwork for the B language, which appeared a few years later. This is interesting because, with the development of B, the C language appeared on the market, and JavaScript drew quite heavily from C.

Object Literals

A classic example of using curly braces in JS is the object literal. We can create an object in JS in several ways: by using the new keyword, by using the built-in static method Object.create, or by using an object literal, meaning {}. The most common way to create new objects is precisely to use a literal. Look at the code below:

js
const obj = {
  name: 'Matt',
  age: 34,
};

typeof obj; // 'object'

It is worth paying attention to the notation - in the example above we create a new object that contains two properties: name and age. The rule is simple: the property name, then a colon, then the assigned value, and finally a comma, which is necessary if the added property is not the last one in the object.

Getting a value from such an object is very simple. We can use dot notation, for example:

js
obj.name // 'Matt'

Objects created with literals can store any data types. We also have access to the object itself through the this reference, as long as the function added to the object is not an arrow function.

Blocks

Using curly braces to create objects is very natural in JavaScript. The remaining uses are less popular, which does not mean they are worse. We can meet curly braces in JS in one more place. Let us analyze the examples below:

js
const settings = {
  visible: false,
};

function show(settingsObject = {}) {
  if ('visible' in settingsObject && settingsObject.visible) {
  		let result = 1;   
	
		return result;
  }

	return 0;
}

show(settings); // 0

The example above shows another use of curly braces - as blocks. What is this block? A code block is nothing more than a group of statements that can follow any keyword: if, else, for, while, and so on. The boundaries of a block are marked by curly braces.

The statements inside the show function are inside the block of that function. Similarly, assigning a value to the result variable and returning it from the function happen inside the block of the conditional statement.

Both examples - the block and the literal - are fairly intuitive and logical. So let us look at another kind of block:

js
{
	let isVisible = false;

  const show = () => {
		isVisible = true;		
	}

	show();
}

The most interesting braces in the example above are the curly braces that frame the entire code. Such braces mean that we have closed our code in a block, not in an object. The syntax used tells us this. Notice that a notation like the one below will not be valid.

js
{
  a: () => {},
  b: 1,
} // SyntaxError: Unexpected token '

And what happens if we write the example above a little differently?

js
{
  a: function a() {};
  b: b = 1;
}

This notation is valid! But why? The answer is simple... labels.

Labels

One of the little-known features of JavaScript is so-called labels. Labels are used to mark statements with an identifier. They can be useful together with the break and continue keywords, which let us jump between statements that have been marked with a label. In the last example, inside the block, we created two statements, described respectively with labels a and b.

Why did b: 1 inside the block return an error, while b: b = 1 did not? 1 by itself is not a statement, because it is a value, but assigning the value 1 to the variable b (a global one in this case) is already a statement.

The syntax of a label looks as follows: <label> <colon> <statement>.

So now it is time for a task for you. What value will be displayed in the console?

js
let value = 0

{
  myLabel: {
    value = 10;
    break myLabel;  
    value = 100;
	  value = 1000;
  }
  
  console.log(value);
}

Of course, 10. The break myLabel; statement stopped further processing of the block, and the following value assignments did not happen.

Destructuring

Another place where we find curly braces is object destructuring expressions, both in function arguments and outside a function.

js
const obj = {
  name: 'Matt',
	age: 34,
};

const { name, age } = obj;

name; // 'Matt'
age; // 34

const whoIs = ({ name, age }) => {
  return `${name}: ${age}`
}

whoIs(obj); // 'Matt: 34'

Destructuring lets us get direct access to values. In the example const { name, age } = obj;, the variables name and age are created and contain the corresponding values from the properties of the destructured object. The property name became the variable name. In the whoIs function, however, contrary to appearances, we are not dealing with an object literal or a code block. The mechanism is identical to the situation with variables.

Summary

Curly braces have been with us since the late 1960s. They settled permanently in high-level programming languages and became an important element of their grammar. In JS they are responsible for many mechanisms, the most interesting of which are object literals, destructuring, and blocks. I hope I managed to clarify a few things today. Grammar is difficult by nature (in natural languages, even more so), but by learning its rules well, we can create really valuable things without falling into the strange traps of programming languages, such as JavaScript labels mentioned today.

Sources

Share this article:

Comments (0)

    No one has posted anything yet, but that means.... you may be the first.

You may be interested in

If this article interested you, check out other materials related to it thematically. Below you will find articles and podcast episodes authored by me, as well as books I recommend that expand on this topic.

Binary system - transistors by YouraPechkin
Article
2023-09-28

Binary System

Numbers, numbers, numbers - they have been with us for thousands of years. We keep trying to organize them, transform them, understand them, and write them down. One of the number systems we invented is the binary system, which forms the foundation of the entire IT world. Welcome to the world of zeros and ones.

Read more
Hoisting by Likoper
Article
2023-01-30

Understanding Hoisting

Some JavaScript concepts seem unusual, not to say strange. Today I would like to look at one of those mechanisms: hoisting.

Read more
Moduły w JS by
Article
2023-01-15

Modules in JS

It is hard to imagine an application made of a single file. It is just as hard to imagine developing such code and maintaining it later. Fortunately, JavaScript supports modules, but it was not always like that.

Read more

Zapisz się do newslettera

Bądź na bieżąco z nowymi materiałami, ćwiczeniami i ciekawostkami ze świata IT. Dołącz do mnie.