JavaScript Syntax
JavaScript syntax is the set of rules for writing instructions that the computer can understand. Just like English sentences need proper grammar, JavaScript needs proper syntax to make the code work.
Here are the main rules every beginner should know:
Case-Sensitivity
JavaScript is case-sensitive.
myName
and myname
are two different variables.
let myName = "Sara";
let myname = "Alex";
console.log(myName); // Sara
console.log(myname); // Alex
Semicolons (;)
Semicolons mark the end of a statement.
let age = 20;
console.log("You are", age);
Code Blocks { }
Code blocks group multiple statements.
if (true) {
let message = "Hello!";
console.log(message);
}
Whitespace
Extra spaces, tabs, or new lines don’t affect the code — but they make it easier to read.
// Good
let name = "Alex";
console.log("Hello", name);
// Bad
let x=10;console.log(x);
Keywords
Keywords are reserved words like let
, if
, return
.
They cannot be used as variable names.
let color = "Blue"; //
let if = 5; // Error
Comments
Comments are ignored by JavaScript but help explain code.
// Single-line comment
/* Multi-line
comment */
Identifiers & Naming Rules
Identifiers are names for variables, functions, etc.
Rules:
- Must start with a letter,
_
, or$
- Cannot start with a number
- Cannot be a keyword
let userName = "Alex"; // ✅
let 123name = "Sara"; // ❌
Literals
Literals are fixed values in code.
let age = 25; // Number literal
let name = "Sara"; // String literal
let isOnline = true; // Boolean literal
Operators
Operators perform actions on values.
let x = 5 + 10; // Addition
let y = 20 - 5; // Subtraction
let z = x * y; // Multiplication