We use three different types of brackets in JavaScript { }, ( ) and [ ].
The curly brackets are used to define the start and end of the function, they also separate code into blocks within the function. The curly brackets help JavaScript to understand the structure of our script and what we want it to do.
In the page about functions you saw that functions start with a "{ " and end with a "}". Like this:
function MyFunction(){
alert("Hello world!")
}
It is also used to separate blocks of code within the function, like this:
function MyFunction(){
if(a==1){
alert("Hello world!")
}else{
alert("Goodbye world!")
}
}
This means that if the variable "a" is equal to 1 the message "Hello world!" is displayed, else the message "Goodbye world!" is displayed.
To make the script easier to read we use indentions, like this:
function MyFunction(){
if(a==1){
alert("Hello world!")
}else{
alert("Goodbye world!")
}
}
The indentions also make it easier to see that all opening brackets are matched by closing brackets. It's also much easier to see where the "if" statement starts and ends and what the two options are.
When we send and receive parameters we use the standard parentheses "( )". You have already seen a lot of examples of that. Note that the "alert" that displays an alert message also is a function, but it is one of the built-in functions in JavaScript.
I will not go into "[ ]" brackets yet. They are used with arrays. Arrays are a more advanced form of variables and will be covered in a separate tutorial.
The semi colon ";" is also important in JavaScript. You should end every statement with a semi colon, like this:
function MyFunction(){
if(a==1){
alert("Hello world!");
}else{
alert("Goodbye world!");
}
}
Personally I skip them most of the time. I know that it isn't correct syntax, but the lack of semi colons has never given me a problem. You will have to decide for yourself if you want to use them or not. One thing is sure, you will never be punished for using them!
Back to tutorial index <<
|