A small guide on how to use brackets while coding

Hedvig Mejstedt
2 min readDec 6, 2021

--

One thing that you quickly become aware of when learning to code is that there are a variety of parentheses. How to use these do not always feel as obvious, so I thought I would make a small guide on how to think about the use of these.

Foto av Tima Miroshnichenko från Pexels

parentheses ( )

In programming, we mainly use parentheses for three things.
First, to control the order of evaluation in an expression. This area of use is close to the way parentheses are used in mathematical notation.

console.log(1 + (2 * 3)); // 1 + 6
// expected output: 7
console.log((1 + 2) * 3); // 3 * 3
// expected output: 9

The second use of parentheses is to define function parameters. You can call a function without entering parameters between the parentheses, but you can also send parameters to a function, and then you do this between an opening and a closing bracket.

Finally, parentheses are used in for loops and while loops.

for (var i=0; i < list.length; i++)
// Do something 'length' times

Curly brackets { }

According to my experience of coding, the use of curly brackets can be roughly divided into three categories:

  • Curly brackets are used to open and close functions, or blocks of code. It clarifies with these brackets where the limit goes for what is inside and outside the scope of the function.
  • A very useful function in React is that you use JSX, this language allows you to use javascript inside JSX. But for the computer to know when to use which language, you distinguish them with the help of curly brackets.
  • One last use I thought of here is to use curly brackets when defining objects in javascript:
const person = { hair:"brown", eyes:"blue", "Hedvig Mejstedt"};

Square brackets [ ]

In my experience, these brackets are used mainly in relation to arrays or objects (arrays are objects). They are used to define an array or to access the properties of an array.

const characters = ["Lilly","Robin","Ted"];console.log(characters[0]) // expected output: Lilly

Square brackets can also be used to access object properties. Usually, this is done with dot notation, but you can also use square bracket notation. This is especially useful if the object property name is dynamic.

const myTestObject = { foo: "Hello", bar: "World" };const myDynamicProp = "bar";console.log(myTestObject.foo); // expected output: Hello
console.log(myTestObject[myDynamicProp]); // expected output: World

--

--