Skip to content

JavaScript Basic Structure

JavaScript programs consist of multiple basic structures that define how code is organized and executed. Understanding the basic structure of JavaScript is essential for writing well-structured, maintainable code. In this chapter, we'll learn the basic components of JavaScript programs.

Basic Components of JavaScript Programs

A typical JavaScript program contains the following basic components:

  1. Variable Declarations: Used to store data
  2. Function Definitions: Reusable code blocks
  3. Expressions and Statements: Perform specific operations
  4. Control Structures: Control program execution flow
  5. Comments: Explain code functionality

Variable Declarations

Variables are containers for storing data. In JavaScript, there are three ways to declare variables:

javascript
// Using var (function scope, not recommended in modern JavaScript)
var oldVariable = "This is the old declaration method";

// Using let (block scope, recommended for mutable variables)
let mutableVariable = "This is a mutable variable";
mutableVariable = "Variable value can change";

// Using const (block scope, recommended for immutable variables)
const immutableVariable = "This is an immutable variable";
// immutableVariable = "This will cause an error"; // TypeError: Assignment to constant variable.

Function Definitions

Functions are reusable code blocks used to perform specific tasks. JavaScript has multiple ways to define functions:

Function Declaration

javascript
function greet(name) {
    return "Hello, " + name + "!";
}

console.log(greet("John")); // Output: Hello, John!

Function Expression

javascript
const greetExpression = function(name) {
    return "Hello, " + name + "!";
};

console.log(greetExpression("Jane")); // Output: Hello, Jane!

Arrow Function

javascript
const greetArrow = (name) => {
    return "Hello, " + name + "!";
};

// Simplified syntax (single line return)
const greetSimple = (name) => "Hello, " + name + "!";

// More simplified (parentheses can be omitted for single parameter)
const greetMinimal = name => "Hello, " + name + "!";

console.log(greetArrow("Bob")); // Output: Hello, Bob!

Expressions and Statements

Expressions

Expressions are code fragments that produce values:

javascript
// Simple expressions
5 + 3
"Hello" + " World"
true && false

// Complex expressions
let result = (5 + 3) * 2 > 10 ? "greater than 10" : "less than or equal to 10";

Statements

Statements are code fragments that perform specific operations:

javascript
// Declaration statement
let x = 5;

// Assignment statement
x = 10;

// Conditional statement
if (x > 5) {
    console.log("x is greater than 5");
}

// Loop statement
for (let i = 0; i < 3; i++) {
    console.log("Loop: " + i);
}

Control Structures

Control structures are used to control the execution flow of a program:

Conditional Structures

javascript
// if...else statement
let age = 18;

if (age >= 18) {
    console.log("Adult");
} else if (age >= 13) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// switch statement
let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Monday");
        break;
    case "Tuesday":
        console.log("Tuesday");
        break;
    default:
        console.log("Other day");
}

Loop Structures

javascript
// for loop
for (let i = 0; i < 5; i++) {
    console.log("for loop: " + i);
}

// while loop
let count = 0;
while (count < 3) {
    console.log("while loop: " + count);
    count++;
}

// do...while loop
let num = 0;
do {
    console.log("do...while loop: " + num);
    num++;
} while (num < 3);

// for...of loop (iterating over iterable objects)
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
    console.log("Fruit: " + fruit);
}

// for...in loop (iterating over object properties)
let person = {name: "John", age: 25, city: "New York"};
for (let key in person) {
    console.log(key + ": " + person[key]);
}

Error Handling Structure

javascript
try {
    // Code that might cause errors
    let result = riskyOperation();
} catch (error) {
    // Handle error
    console.log("Error occurred: " + error.message);
} finally {
    // This will execute regardless of errors
    console.log("Cleanup work");
}

Object and Array Structures

Object Literals

javascript
const person = {
    // Properties
    name: "John",
    age: 25,
    
    // Method
    greet: function() {
        return "Hello, I am " + this.name;
    },
    
    // ES6 shorthand method
    sayAge() {
        return "I am " + this.age + " years old";
    }
};

console.log(person.greet()); // Hello, I am John
console.log(person.sayAge()); // I am 25 years old

Array Literals

javascript
// Create arrays
const numbers = [1, 2, 3, 4, 5];
const mixed = [1, "string", true, {name: "John"}];

// Array operations
numbers.push(6); // Add element
numbers.pop(); // Remove last element
numbers.shift(); // Remove first element
numbers.unshift(0); // Add element at beginning

Module Structure

Modern JavaScript supports modular development:

Export

javascript
// math.js
export const PI = 3.14159;

export function add(a, b) {
    return a + b;
}

export function multiply(a, b) {
    return a * b;
}

// Default export
export default function subtract(a, b) {
    return a - b;
}

Import

javascript
// main.js
import subtract, { PI, add, multiply } from './math.js';

console.log(PI); // 3.14159
console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(subtract(10, 3)); // 7

Asynchronous Structures

JavaScript supports asynchronous programming:

Promise

javascript
const fetchData = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Data fetched successfully");
        }, 1000);
    });
};

fetchData()
    .then(result => console.log(result))
    .catch(error => console.log(error));

async/await

javascript
async function getData() {
    try {
        const result = await fetchData();
        console.log(result);
    } catch (error) {
        console.log("Error: " + error);
    }
}

getData();

Code Organization Structures

Immediately Invoked Function Expression (IIFE)

javascript
(function() {
    // Private scope
    let privateVariable = "Private variable";
    
    console.log("This function executes immediately");
    
    // Can return a value
    return "Execution completed";
})();

Closure Structure

javascript
function createCounter() {
    let count = 0;
    
    return function() {
        count++;
        return count;
    };
}

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

Event Handling Structure

javascript
// DOM event handling
document.getElementById("myButton").addEventListener("click", function(event) {
    console.log("Button was clicked");
    console.log("Event object:", event);
});

// Custom events
const customEvent = new CustomEvent("myEvent", {
    detail: { message: "Custom event" }
});

document.addEventListener("myEvent", function(event) {
    console.log("Received custom event:", event.detail.message);
});

// Dispatch custom event
document.dispatchEvent(customEvent);

Class Structure (ES6)

javascript
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return "Hello, I am " + this.name;
    }
    
    static getSpecies() {
        return "Human";
    }
}

class Student extends Person {
    constructor(name, age, grade) {
        super(name, age);
        this.grade = grade;
    }
    
    study() {
        return this.name + " is studying";
    }
}

const student = new Student("Tom", 18, "Senior");
console.log(student.greet()); // Hello, I am Tom
console.log(student.study()); // Tom is studying

Code Convention Structure

Naming Conventions

javascript
// Variables and functions use camelCase
let userName = "John";
function calculateTotal() {
    // Function body
}

// Constants use UPPER_CASE with underscores
const MAX_SIZE = 100;
const API_URL = "https://api.example.com";

// Class names use PascalCase
class UserManager {
    // Class body
}

Comment Conventions

javascript
/**
 * Calculate the sum of two numbers
 * @param {number} a - The first number
 * @param {number} b - The second number
 * @returns {number} The sum of the two numbers
 */
function add(a, b) {
    return a + b;
}

// Single line comments for simple logic
let result = add(5, 3); // Calculate 5 + 3

/*
 * Multi-line comments for complex logic
 * Here you can explain the algorithm in detail
 */
if (result > 10) {
    console.log("Result is greater than 10");
}

Summary

The basic structures of JavaScript programs include:

  1. Variable Declarations: Use let, const to declare variables
  2. Function Definitions: Function declarations, function expressions, arrow functions
  3. Expressions and Statements: Code that produces values and performs operations
  4. Control Structures: Conditional statements, loop statements, error handling
  5. Objects and Arrays: Data organization methods
  6. Module Structure: Modular code organization
  7. Asynchronous Structure: Handle asynchronous operations
  8. Class Structure: Object-oriented programming
  9. Event Handling: Respond to user interactions
  10. Code Conventions: Naming conventions and comment conventions

Understanding these basic structures helps you write clear, maintainable JavaScript code. In the next chapter, we'll dive deeper into JavaScript variable declarations.

Content is for learning and research only.