JavaScript Syntax and StructureGet Certified
JavaScript syntax is the set of rules that define how JavaScript code should be written and structured. Understanding these rules is one of the first steps toward becoming a confident JavaScript developer.
In this lesson, you will learn how JavaScript statements, expressions, comments, identifiers, keywords, variables, code blocks, whitespace, and semicolons work together to form a JavaScript program.
What Is JavaScript Syntax?
Syntax refers to the rules that determine how JavaScript code should be written. These rules tell the JavaScript engine how to understand and execute your program.
For example, this is a simple and valid JavaScript statement:
// A simple JavaScript statement
console.log("Hello, JavaScript!");
// on a line is a comment. The JavaScript engine skips it completely; it exists only to tell human readers what the code is for.console.log(...) is a statement that prints the text inside the parentheses to the console. The output is Hello, JavaScript!.
The console.log() function prints information to the
browser’s developer console or to the console output of our
built-in editor.
JavaScript Statements
A JavaScript program is made up of statements. A statement is an instruction that tells JavaScript to perform a particular action.
let name = "Michael";
let age = 25;
console.log(name);
console.log(age);
let name = "Michael"; creates a variable called name and stores the string value "Michael".let age = 25; creates another variable that stores the number 25.console.log(name); prints the current value of name.console.log(age); prints the current value of age.The example above contains multiple statements. JavaScript executes them according to the order and control flow of the program.
Semicolons
A semicolon (;) is commonly used to mark the end of
a JavaScript statement.
let firstName = "Michael";
let lastName = "Johnson";
console.log(firstName);
console.log(lastName);
let firstName = "Michael"; declares a variable and ends the statement with a semicolon.let lastName = "Johnson"; does the same for the last name.console.log statements print the stored values. Each statement ends with a semicolon.JavaScript also supports Automatic Semicolon Insertion (ASI). This means JavaScript can automatically insert semicolons in certain situations.
Even though semicolons are often optional, using them consistently can make your code easier to read and can help avoid certain ambiguities.
JavaScript Expressions
An expression is a piece of JavaScript code that produces a value. Expressions can contain values, variables, operators, and function calls.
let a = 10;
let b = 20;
let result = a + b;
console.log(result);
a + b is an expression. It calculates 30 and the result is stored in result.console.log(result); displays the value produced by the expression.
In this example, a + b is an expression because it
produces the value 30.
JavaScript Comments
Comments are notes written inside JavaScript code. They are ignored by JavaScript during execution and are mainly used to explain code or provide useful information to other developers.
Single-Line Comments
A single-line comment starts with two forward slashes
(//).
// This is a single-line comment
console.log("Hello!");
// is ignored by the JavaScript engine.Hello!.Multi-Line Comments
Multi-line comments begin with /* and end with
*/.
/*
This is a multi-line comment.
JavaScript ignores everything
between these symbols.
*/
console.log("Comments are useful!");
/* and */ is ignored. Multi-line comments are useful for longer explanations.JavaScript Identifiers
Identifiers are names used to identify variables, functions, classes, and other elements in JavaScript.
let firstName = "Michael";
let userAge = 25;
console.log(firstName);
console.log(userAge);
firstName and userAge are identifiers — the names we give to variables. Good identifiers describe what the variable holds.console.log statements display the stored values.Rules for Identifiers
JavaScript identifiers follow several important rules:
- They can contain letters, digits, underscores, and dollar signs.
- They cannot begin with a digit.
- They are case-sensitive.
- Reserved keywords cannot normally be used as identifiers.
- Spaces are not allowed inside identifiers.
- Meaningful names should be preferred for readability.
let userName = "Alex";
let user_name = "John";
let $price = 500;
let item2 = "Laptop";
console.log(userName);
console.log(user_name);
console.log($price);
console.log(item2);
userName uses camelCase, the most common style in JavaScript.user_name uses an underscore. This style is also valid.$.JavaScript Keywords
Keywords are reserved words that have special meanings in the JavaScript language. They are used to perform specific tasks and generally cannot be used as ordinary variable names.
const name = "Michael";
if (name === "Michael") {
console.log("Welcome, Michael!");
}
const is a keyword that declares a constant variable.if is a keyword that starts a conditional statement.Some commonly used JavaScript keywords are:
letconstvarifelseforwhilefunctionreturnclassnewthis
JavaScript Is Case-Sensitive
JavaScript is a case-sensitive programming language. This means uppercase and lowercase letters are treated as different characters.
let name = "Michael";
let Name = "David";
console.log(name);
console.log(Name);
name and Name are completely separate identifiers because JavaScript is case-sensitive.
Here, name and Name are two different
variables.
Whitespace and Formatting
Whitespace includes spaces, tabs, and line breaks. JavaScript generally ignores unnecessary whitespace, but good formatting makes your code easier to read and maintain.
let firstName = "Michael";
let lastName = "Johnson";
let fullName = firstName + " " + lastName;
console.log(fullName);
+ operator joins the two strings with a space in between.JavaScript Code Blocks
A code block is a group of JavaScript statements surrounded by
curly braces ({ }).
Code blocks are commonly used with conditions, loops, functions, classes, and other JavaScript structures.
let age = 25;
if (age >= 18) {
console.log("You are an adult.");
console.log("You can continue.");
}
if statement checks whether age is 18 or greater.Nested Code Blocks
JavaScript code blocks can also be placed inside other code blocks.
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive.");
}
}
if checks whether the person is an adult.Strings and Quotes
Strings represent text in JavaScript. They can be written using single quotes, double quotes, or template literals.
let single = 'Hello';
let double = "JavaScript";
let template = `Welcome to JavaScript`;
console.log(single);
console.log(double);
console.log(template);
Basic Variable Syntax
Variables are used to store values that your program can work
with. Modern JavaScript commonly uses let and
const to declare variables.
let city = "New York";
const country = "United States";
console.log(city);
console.log(country);
let creates a variable that can be changed later.const creates a constant that should not be reassigned.Function Structure
Functions are reusable blocks of code designed to perform a
particular task. A function declaration contains the
function keyword, a function name, parentheses, and
a code block.
function greet(name) {
console.log("Hello, " + name);
}
greet("Michael");
function greet(name) declares a function named greet that accepts one parameter.greet("Michael") runs the function and produces the message.Operators in JavaScript
Operators are symbols or keywords used to perform operations on values.
let a = 10;
let b = 5;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
+ adds the two numbers.- subtracts.* multiplies./ divides.% gives the remainder after division.Conditional Structure
Conditional statements allow JavaScript to execute different blocks of code depending on whether a condition is true or false.
let age = 20;
if (age >= 18) {
console.log("You are eligible.");
} else {
console.log("You are not eligible.");
}
else block runs instead. Only one of the two blocks executes.Loop Structure
Loops allow you to execute a block of code repeatedly while a condition is satisfied.
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}
let i = 1 starts the counter, i <= 5 is the condition, and i++ increases the counter after each pass.i from 1 to 5.Putting Everything Together
Let's combine variables, a function, a condition, an expression, and a code block into one example.
// Store user information
const name = "Michael";
const age = 25;
// Check whether the user is an adult
function checkAge(userAge) {
if (userAge >= 18) {
return true;
}
return false;
}
const isAdult = checkAge(age);
if (isAdult) {
console.log(name + " is an adult.");
} else {
console.log(name + " is not an adult.");
}
true or false.isAdult.if...else prints the appropriate message based on the returned boolean.Common Syntax Mistakes
Beginners often encounter syntax errors while learning JavaScript. Most of these errors are caused by small mistakes in the structure of the code.
- Missing parentheses
( ) - Missing curly braces
{ } - Missing quotation marks
- Incorrect capitalization
- Misspelled variable names
- Using reserved keywords incorrectly
- Missing commas or operators
const name = "Michael";
if (name === "Michael") {
console.log("Correct syntax!");
}
JavaScript Syntax Best Practices
- Use meaningful variable and function names.
- Keep your indentation consistent.
- Use spaces to improve readability.
- Use comments when they provide useful context.
- Prefer
constwhen a variable does not need reassignment. - Use
letwhen a variable needs reassignment. - Keep functions focused on a specific task.
- Avoid unnecessarily complicated code.
- Use consistent quotation and formatting conventions.
Quick Summary
- JavaScript syntax defines the rules for writing JavaScript.
- JavaScript programs are made up of statements and expressions.
- Semicolons are commonly used to terminate statements.
- Comments are ignored during program execution.
- Identifiers are names used for variables, functions, and other elements.
- Keywords have special meanings in JavaScript.
- JavaScript is case-sensitive.
- Curly braces create code blocks.
- Functions contain reusable blocks of code.
- Conditions control which code blocks are executed.
- Loops repeat code according to a condition.
- Good formatting makes JavaScript easier to understand and maintain.
Try It Yourself
Modify the following example. Change the name and age, experiment with the condition, and then click Test My Code to see the result.
const name = "Michael";
const age = 25;
if (age >= 18) {
console.log(name + " can vote.");
} else {
console.log(name + " cannot vote.");
}
Tip: Don't try to memorize every syntax rule at once. Write small programs, experiment with the code, and learn from the errors you encounter.
Understanding JavaScript syntax and structure gives you the foundation required for learning variables, data types, operators, functions, objects, arrays, DOM manipulation, asynchronous JavaScript, and advanced JavaScript concepts.
🧪 Test Your JavaScript Code
Edit the code on the left and click "Run Code" to see the console output on the right.
Click "Run Code" to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.