JavaScript Syntax
Subject: JavaScript
JavaScript syntax refers to the set of rules that define how JavaScript code must be written to be correctly understood by the browser. Learning syntax is the first step toward writing valid and bug-free JavaScript code.
Basic Structure of JavaScript Code
A JavaScript program consists of statements that are executed by the browser.
letis a keyword to declare a variable"Hello, JavaScript!"is a string valueconsole.log()prints output to the browser’s console
Key Syntax Rules in JavaScript
1. Statements
Each instruction in JavaScript is called a statement, and statements are usually terminated with a semicolon ;.
2. Case Sensitivity
JavaScript is case-sensitive. For example, let, Let, and LET are all different.
3. Comments
You can write comments to explain code or disable lines during testing.
4. Identifiers (Names)
Variable and function names must follow these rules:
- Must start with a letter,
$, or_ - Can contain letters, digits,
$, or_ - Cannot be reserved keywords (like
var,function, etc.)
5. Whitespace and Line Breaks
JavaScript ignores extra spaces and newlines. They are used to improve readability.
6. Semicolons
Semicolons are used to separate JavaScript statements. They are optional in most cases, but using them is a best practice to prevent automatic semicolon insertion (ASI) errors.
Example: Simple JavaScript Script
Key Takeaways
- JavaScript syntax defines how code is structured and written
- Statements are instructions that end with a semicolon
- JavaScript is case-sensitive and uses meaningful variable names
- Comments improve code readability and help with debugging
- Use consistent indentation and spacing for clean code