开发者

Different JavaScript block types

What is the difference between:

Ex 1.

<script type="text/javascript">   
document.write("<h1>This is a heading</h1>");   
document.write("<p>This is a paragraph.</p>");   
document.write("<p>This is another paragraph.</p>");   
</script>  

Ex 2.

<script type="text/javascript">   
{   
    document.write("<h1&g开发者_开发问答t;This is a heading</h1>");   
    document.write("<p>This is a paragraph.</p>");   
    document.write("<p>This is another paragraph.</p>");   
}   
</script>

W3C Schools says:

Ex 1. Each statement is executed by the browser in the sequence they are written.

Ex 2. The purpose of a block is to make the sequence of statements execute together.

Please explain the above statements. How does the browser acts differently upon the above commands?


No difference at all, the purpose of a block is to be used in ifs and fors, like so:

Ex 1 if () //command to execute

Ex 2 if () { // many commands to execute }

In the second sample, the if statement "sees" the block command as a single command, inside the block, the commands still are executed in order.


IMO Ex 2 will stop executing further statements if an exception occurs.

Either all the statements will run or the remaining statement will not executed after the exception.

But in Ex 1 all the statement will execute.


In this case there's no difference between what your two pieces of code will do.

Blocks are there for use alongside other JS constructs such as functions, if, looping, etc. For example when used with if, they mean "If a condition is met, then execute all the code in the following block". Without the block you can only execute a single line of code based on the result of the if statement.


There really is effectively no difference. Even W3Schools says:

The example above is not very useful. It just demonstrates the use of a block. Normally a block is used to group statements together in a function or in a condition (where a group of statements should be executed if a condition is met).

So you would more often use a block in something like the following:

<script type="text/javascript">
if (someValue==true) {
    document.write("<h1>Executed block 1</h1>");
} else {
    document.write("<h1>Executed block 2</h1>");
}
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜