JavaScript Syntax
JavaScript syntax defines a set of rules on how programs are constructed. These rules include keywords, operators, and punctuation. Proper syntax ensures that the code is understandable by the JavaScript engine.
Key Topics
Basic Syntax
JavaScript programs are made up of statements that end with semicolons. Curly braces define code blocks, and variables are declared using var
, let
, or const
.
let x = 10;
let y = 20;
let sum = x + y;
console.log("Sum: " + sum);
Output
Sum: 30
Case Sensitivity
JavaScript is case-sensitive. This means that myVariable
and MyVariable
are treated as two different identifiers.
let myVariable = "Hello";
let MyVariable = "World";
console.log(myVariable);
console.log(MyVariable);
Output
Hello
World
Semicolon Usage
In JavaScript, semicolons are used to separate statements. Although they are optional in many cases due to automatic semicolon insertion (ASI), it's good practice to include them explicitly for clarity.
let a = 5;
let b = 10;
console.log(a + b);
Output
15
Examples of Syntax
Below are examples demonstrating various syntax rules:
- Variable Declaration:
let age = 25;
- Conditional Statement:
if (age > 18) { console.log("Adult"); }
- Function Definition:
function greet() { return "Hello"; }
- Loop:
for (let i = 0; i < 5; i++) { console.log(i); }
Key Takeaways
- Basic Syntax: Statements end with semicolons, and curly braces define code blocks.
- Case Sensitivity: JavaScript distinguishes between uppercase and lowercase letters.
- Semicolon Usage: While optional, semicolons improve readability and prevent errors.
- Syntax Rules: Following proper syntax ensures code is understandable and runs without errors.