JavaScript has its own unique syntax that differs from HTML and CSS, although they work together in web development. Here’s an overview of JavaScript syntax and its structure:
Basic Structure
JavaScript uses curly braces {} to define blocks of code, rather than the tag-based approach of HTML:
// Function definition
function greetUser() {
// Code block inside curly braces
console.log("Hello there!");
}
// Conditional statement
if (userLoggedIn) {
// Another code block
showDashboard();
} else {
showLoginForm();
}
Opening and Closing Syntax
Unlike HTML which uses <tag> and </tag> for opening and closing, JavaScript uses different approaches:
1. Code Blocks: Curly Braces {}
// Opening and closing a function
function calculateTotal() {
// Code goes here
}
// Opening and closing an if statement
if (condition) {
// Code goes here
}
2. Statements: Semicolons ;
JavaScript statements typically end with semicolons (though they’re sometimes optional):
let name = "John";
console.log(name);
3. Arrays: Square Brackets []
// Opening and closing an array
let colors = ["red", "green", "blue"];
4. Objects: Curly Braces {}
// Opening and closing an object
let user = {
name: "John",
age: 30,
isAdmin: false
};
5. Comments
// Single line comment
/*
Multi-line
comment
*/
Comparison with HTML and CSS
| Language | Primary Enclosing Syntax | Example |
|---|---|---|
| HTML | Tags: <tag></tag> | <div>Content</div> |
| CSS | Curly braces: {} | selector { property: value; } |
| JavaScript | Curly braces: {} | if (x > 10) { console.log(x); } |
Would you like me to explain any specific part of JavaScript syntax in more detail?