Write the syntax of javascript with a code to demonstrate it?

JavaScript Tags

JavaScript code must be placed within HTML <script> tags to execute properly. These script tags can be positioned in different locations within an HTML document.

Where to Place JavaScript

JavaScript can be embedded in three main locations:

  • Head section: Scripts in the <head> tag load before the page content
  • Body section: Scripts in the <body> tag execute as the page loads
  • External file: Scripts can be linked from separate .js files

Basic JavaScript Syntax

JavaScript syntax includes variables, functions, and DOM manipulation. Here's the fundamental structure:

// Variable declaration
let variableName = value;

// Function syntax
function functionName() {
    // code block
}

// DOM manipulation
document.getElementById("elementId").property = value;

Example: JavaScript in HTML Body

<html>
<body>
   <h2>JavaScript Syntax Demo</h2>
   <p>This example demonstrates basic JavaScript syntax and DOM manipulation.</p>
   <p id="demo"></p>
   
   <script>
      // Variable declaration
      let message = "JavaScript is not Java";
      let number = 42;
      
      // Function definition
      function displayMessage() {
         return "Hello from JavaScript!";
      }
      
      // DOM manipulation
      document.getElementById("demo").innerHTML = message + "<br>" + displayMessage();
   </script>
</body>
</html>

Output

JavaScript Syntax Demo
This example demonstrates basic JavaScript syntax and DOM manipulation.
JavaScript is not Java
Hello from JavaScript!

Example: JavaScript in Head Section

<html>
<head>
   <script>
      function loadMessage() {
         document.getElementById("content").innerHTML = "Page loaded with JavaScript!";
      }
   </script>
</head>
<body onload="loadMessage()">
   <h3>JavaScript in Head Example</h3>
   <p id="content">Loading...</p>
</body>
</html>

Output

JavaScript in Head Example
Page loaded with JavaScript!

Key Syntax Rules

  • Case Sensitive: JavaScript is case-sensitive (myVar ? MyVar)
  • Semicolons: End statements with semicolons (optional but recommended)
  • Comments: Use // for single-line or /* */ for multi-line comments
  • Script Tags: All JavaScript must be within <script> tags or external files

Conclusion

JavaScript syntax requires proper placement within <script> tags and follows specific rules for variables, functions, and DOM manipulation. Understanding these fundamentals is essential for web development.

Updated on: 2026-03-15T23:18:59+05:30

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements