JavaScript syntax is the set of rules that defines how JavaScript programs are written and understood by the browser. Just like grammar in a language, syntax tells JavaScript how to read and execute your code correctly. If your syntax is wrong, the browser will not understand your program and will throw an error.
What is JavaScript Syntax?
JavaScript syntax refers to how you write:
- Variables
- Values
- Operators
- Statements
- Functions
- Comments
These elements together form valid JavaScript code.
Example
Here is a simple JavaScript program:
Explanation:
letis used to create a variablemessageis the variable name"Hello, World!"is the value stored in the variableconsole.log()displays the output in the browser console- Each statement ends with a semicolon
;semicolon is optional but recommended for writing structured programs
JavaScript is Case-Sensitive
This means:
These are two different variables.
Identifiers in JavaScript
In JavaScript, identifiers are the names used to identify variables, functions, classes, and other elements in your code. They help JavaScript understand what you are referring to when you write or run a program.
An identifier is simply a name given to a programming element. For example, when you create a variable, the variable name is the identifier.
Rules for Identifiers
JavaScript identifiers must follow these rules:
- Must start with a letter, underscore (_), or dollar sign ($)
- Cannot start with a number
- Can contain letters, numbers, underscores, and dollar signs
- Are case-sensitive
- Cannot use JavaScript reserved keywords (like
let,if,function)
Small Code Example
Explanation:
userName,totalScore, andshowScoreare identifiers- They are used to refer to stored values and a function
JavaScript Keywords
JavaScript keywords are reserved words that have a special meaning in the language and are used to perform specific actions in a program. These words cannot be used as identifiers such as variable names, function names, or class names.
Keywords help define the structure and logic of your code, including creating variables, controlling program flow, and defining functions or classes. Some common JavaScript keywords include let, const, var, if, else, for, while, function, return, and class.
Understanding keywords is important because they form the building blocks of how JavaScript programs are written and executed.