Academic Block

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!");

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);

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);

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);

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!");

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!");

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);

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);

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!");
}

Some commonly used JavaScript keywords are:

  • let
  • const
  • var
  • if
  • else
  • for
  • while
  • function
  • return
  • class
  • new
  • this

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);

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);

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.");
}

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.");
    }
}

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);

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");

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);

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.");
}

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);
}

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.");
}

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 const when a variable does not need reassignment.
  • Use let when 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.

📝 JavaScript Code
👁 Console Output

Click "Run Code" to see the output here.

Ctrl + Enter to run code Esc to close