When to use semicolons and brackets

It’s still hard for me to understand when to use semicolons; and brackets {}. Anyone break me This I consider the most difficult part of coding. Thank!

+3
source share
4 answers

Semicolons should be used to complete statements. Brackets should be used to group several statements in a code block, for example, when writing conditions if, 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);
    }
}
+5
source

{} , . ; , .

, W3 School JavaScript.

:

JavaScript.

[...]

JavaScript .

.

0

inst1; inst2; inst3;

,

if (condition) {
  line1
  line2
}
0

(a statement can be a declaration, a function call, any expression , for example, assignment of an expression), then you must add ;For example:

var i = 10;  // declaration 
fun(10); // calling a function 
i = j + 3 && 20;  // an expression 

You should use { }it if you want to make a block of statements in general when you define a function , and for if if switch-case , etc.

Example:

(1)

if(a = b){
  fun(2);  // call a function 
  a = a + b;
}

(2)

while(1){
  statement-1; 
  statement-2; 
} 
Function

(3):

function f(var){
    statement-1; 
    statement-2; 
}

Special Occasions:

You need ;after }in for the dict and function:

var foo = function() {
    statement-1; 
};  // not your need both `;` and `}`

This value expresses the definition of function and assignment.

objects:

var obj = {
  a : 1,
  b: 2,
};  // not you uses both `;` and `}` 
0
source

All Articles