Web Development - JavaScript Syntax
JavaScript Syntax
JavaScript syntax is the set of rules that tells the browser how to read and run your code. It's like grammar for your web page's language.
JavaScript Statements
JavaScript programs are made up of statements. Each statement is a command that the browser runs, one after another.
Example
JavaScript changes the text inside an HTML element:
<p id="demo">Hello</p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
// This is a statement
</script>
Try it Yourself »
Each line is a JavaScript statement that tells the browser what to do.
Semicolons ;
You can end JavaScript statements with a semicolon (;).
It tells the browser that the command is complete.
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "First line";
document.getElementById("demo").style.color = "blue";
</script>
Try it Yourself »
Note: Semicolons are optional in many cases, but using them makes your code easier to read and prevents small errors.
White Space and Line Breaks
JavaScript ignores extra spaces and line breaks. You can use them to make your code more readable.
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML="Hello";
document.getElementById( "demo" ).innerHTML = "Hello";
// Preferred
document . getElementById ( "demo" ) . innerHTML = "Hello";
</script>
All three lines above do the same thing - spaces don't matter.
Case Sensitivity
JavaScript is case sensitive.
That means document.getElementById and Document.getelementbyid are not the same.
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "This works!";
Document.getElementById("demo").innerHTML = "This will cause an error";
</script>
Try it Yourself »
JavaScript Code Blocks
Code blocks group statements together using curly braces { }.
You'll see them more when learning about functions and loops.
Example
<p id="demo"></p>
<script>
{
document.getElementById("demo").innerHTML = "Hello!";
document.getElementById("demo").style.color = "green";
}
</script>
Summary
- JavaScript code is made of statements that tell the browser what to do.
- Semicolons (
;) end statements. - Extra spaces and line breaks are ignored.
- JavaScript is case sensitive.
- Code blocks group multiple statements together.
Next, you'll learn how to store and reuse information in JavaScript.