JS Syntax
JavaScript Syntax: Core Rules for Valid Code
JavaScript syntax defines the grammar rules for writing code that the engine can parse and run. Every program combines fixed literal values, named variables, operators, keywords, and expressions.
Fixed Values vs. Variable Values
JavaScript works with two kinds of values:
- Literals (fixed values): Numbers like
42or3.14, strings wrapped in quotes like"Ada", and booleans liketrue. - Variables (named values): Identifiers created with
constorletthat hold values you compute or update later.
Identifier Naming Rules and Case Sensitivity
JavaScript is strictly case-sensitive. A variable named userTotal is completely different from usertotal or USERTOTAL.
Follow these naming rules so every identifier stays valid:
- Allowed starting characters: Begin names with a letter (
a-z,A-Z), an underscore (_), or a dollar sign ($). - Disallowed characters: Never start a name with a digit (
0-9) or use hyphens (-), because-means subtraction. - Standard style: Use
camelCasefor variables and functions,PascalCasefor classes, andUPPER_SNAKE_CASEfor fixed constants.
const TAX_RATE = 0.08;
let itemPrice = 25;
let itemCount = 3;
function computeTotal(price, count) {
const subtotal = price * count;
return Number((subtotal * (1 + TAX_RATE)).toFixed(2));
}
console.log("Total with tax:", computeTotal(itemPrice, itemCount));
Common Mistakes to Avoid
- Mixing up
=and===: A single=assigns a value, while===checks whether two values match in both value and type. - Using reserved words as names: Words like
class,return,await, andswitchbelong to the language and trigger aSyntaxErrorif used as variables. - Inconsistent casing: Calling
getElementbyIdinstead ofgetElementByIdthrows aTypeErrorbecause JavaScript checks exact letter case.
Frequently Asked Questions
Does JavaScript care about single quotes versus double quotes?
No, 'hello' and "hello" create identical strings. Pick one quote style for normal strings and use backticks `...` whenever you embed variables.
Why are hyphens not allowed in JavaScript variable names?
JavaScript parses - as the subtraction operator. Writing first-name tells the engine to subtract name from first, so use firstName instead.
What throws a SyntaxError in JavaScript?
A SyntaxError happens before code runs when brackets do not match, quotes stay unclosed, or reserved keywords appear in invalid places.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.