JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together. One place you will find statements grouped together in blocks, are in JavaScript functions:

HTML file: Displayed by browser:
<body>

<h1>My Web Page</h1>

<p id="myPar">I am a paragraph.</p>
<div id="myDiv">I am a div.</div>
<p>
<button type="button" onclick="myFunction()">Try it</button>
</p>

<script>
function myFunction() {
    document.getElementById("myPar").innerHTML = "Hello Dolly.";
    document.getElementById("myDiv").innerHTML = "How are you?";
}
</script>

<p>When you click on "Try it", the two elements will change.</p>

</body>

My Web Page

I am a paragraph.

I am a div.

When you click on "Try it", the two elements will change.


BackTable of ContentsNext