MIstake in my code and difficulties with the use of brackets


#1

Dear codeacademy community,

as you can see I am a newbie but willing to learn.

Unfortunately I am totally confused regarding the use of brackets in coding JavaScript. :sweat:

When do I use...?
- )? (This bracket is necessary for e.g. function () )
-}? (I thought the curly bracket is optional and just makes it easier to read the JS code but not necessary)
-};? (This one is only used to highlight that this is a code of block which will be executed and the semilicon marks the seperation or end of command)
-)};? (This one is to mark the ending of a command and block of code ending right after the semicolon)
-});? (Does this combination make any sense? And if so, when do I use it?)

This is my code and I think the mistake I made here is hopefully only the confusion with the brackets...If somebody could have a look at it, it would be great!

Thanks in advance!


#2

Hi Minikazi

Understanding how brackets (or parentheses () ) and braces (or curly brackets {}) are used in Javascript (and any other language for that matter) is fundamental to both writing and reading code.

I'll try my best to sum up the most common uses for them in Javascript.

Brackets/parentheses ()

  • Grouping expressions:
    (a + b) * c

  • Containing expressions:
    if (a < b)
    e.g. attached to a conditional if statement, the expression is checked and returns a value equal to true or false

  • Containing parameters:
    myFunction(parameter1, parameter2, parameter3)
    e.g. creating or calling a function which requires a certain set of parameters to be passed in. If no parameters are required, the parentheses are left empty.

Curly brackets/braces {}

  • Containing statements/function blocks:
    e.g. Marking the beginning and ending of a statement or function block:

    if (a < b) {
        console.log("Foo"); 
    };

    var myFunction() {
        console.log("Bar");
    };
  • Containing values in array declarations:
    var myArray = { a, b, c };

So sometimes you may have a situation where a function is called and its parameter is another function (in your case, see the .click() line).

I've written a one-line example which hopefully makes it easier to see how these are being used:

$(".article").click(function() { console.log("Foobar") });

If you were to remove them one-by-one, you'd find that every opening parenthesis and curly bracket has a closing equivalent.

I hope this helps your understanding!

P.S. Indenting your code properly in Javascript is not necessary, but makes it much easier to separate and understand the segments. Learning Python is a great way to get into this as it relies on indentation to function correctly.