Reputation: 41
I am still having a hard time figuring out when to use semicolons ; and brackets {}. Anyone break it down for me? This I think is the hardest part of coding. Thanks!
Upvotes: 3
Views: 531
Reputation: 58251
When you complete a statement (a statement can be declaration, function call, any expression e.g assignment expression) then you should add ;
For example:
var i = 10; // declaration
fun(10); // calling a function
i = j + 3 && 20; // an expression
You should use {
}
for you wants to make a block of statements generally when you defines function, while, for, if, switch-case etc.
Example:
(1)
if(a = b){
fun(2); // call a function
a = a + b;
}
(2)
while(1){
statement-1;
statement-2;
}
(3) function:
function f(var){
statement-1;
statement-2;
}
Special more cases:
You need ;
after }
in a for dict and function:
var foo = function() {
statement-1;
}; // not your need both `;` and `}`
This value both function definition and assignment expression
objects:
var obj = {
a : 1,
b: 2,
}; // not you uses both `;` and `}`
Upvotes: 0
Reputation: 7129
Curly braces {}
are for code blocks which can contain multiple to single code statements. Where as a semicolon ;
is to delineate or tell the compiler where a particular line of code ends.
You might want to go through this W3 School page on JavaScript Statements.
Excerpt from the page:
Semicolon separates JavaScript statements.
[...]
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
Upvotes: 0
Reputation: 4860
Semicolons to separate several instructions in a single line
inst1; inst2; inst3;
Brackets when you have more than one line of code in conditionals or loops
if (condition) {
line1
line2
}
Upvotes: 0
Reputation: 1038710
Semicolons should be used to terminate statements. Brackets should be used to group more than one statements in a code block, for example when writing if
conditions, loops (for
, while
) or functions. Brackets are also used when creating objects.
Example:
var foo = 'bar';
if (foo == 'bar') {
for (var i = 0; i < 5; i++) {
alert('Hello ' + i);
}
}
Upvotes: 5