Skillversitas

JavaScript Basic Syntax

Introduction to Syntax

Every programming language has writing rules (syntax) that must be followed. JavaScript's syntax is relatively flexible compared to other languages, but it still has basic rules that you must know.

Case Sensitivity

JavaScript is a case-sensitive language. That means uppercase and lowercase letters are considered different.

// Case sensitivity example
let name = "John";
let Name = "Mike";
let NAME = "Alice";

// These three variables are DIFFERENT
console.log(name); // "John"
console.log(Name); // "Mike"
console.log(NAME); // "Alice"

// Example in an academic portal
let student = "John Smith";
let Student = "Mike Johnson";

console.log(student); // "John Smith"
console.log(Student); // "Mike Johnson"
// student !== Student

Common Mistakes Caused by Case Sensitivity

// ❌ Wrong — error due to different case
let studentName = "John";
console.log(StudentName); // ReferenceError!

// ❌ Wrong — the correct method is querySelector, not QuerySelector
document.QuerySelector(".card"); // Error!

// ✅ Correct
document.querySelector(".card"); // Works!

💡 Tip: Consistency in how variable names are written is very important. Follow the conventions that already exist in your project.

Statements

Every instruction in JavaScript is called a statement. Statements end with a semicolon (;), although JavaScript can add them automatically (Automatic Semicolon Insertion / ASI).

// Statements with semicolons
let studentId = "2024100123";
let name = "John Smith";
let gpa = 3.75;

// Statements without semicolons (still works because of ASI)
let studentId2 = "2024100124"
let name2 = "Mike Johnson"
let gpa2 = 3.50

⚠️ Best Practice: Always use semicolons consistently. This prevents hard-to-debug bugs caused by unpredictable ASI.

Whitespace and Line Breaks

JavaScript ignores excessive whitespace (spaces, tabs, line breaks). This makes it possible to write cleaner code.

// All of these produce the same result
let a=1;let b=2;let c=3;

let a = 1;
let b = 2;
let c = 3;

let   a   =   1;
let   b   =   2;
let   c   =   3;

Indentation

JavaScript uses indentation (leading spaces) to make code easier to read. The common standard is 2 spaces or 4 spaces.

// ✅ Code with correct indentation
function calcGPA(gradeList) {
    let totalCredits = 0;
    let totalWeight = 0;

    for (let i = 0; i < gradeList.length; i++) {
        let { score, credits } = gradeList[i];

        if (score >= 85) {
            totalWeight += 4 * credits;
        } else if (score >= 70) {
            totalWeight += 3 * credits;
        } else if (score >= 55) {
            totalWeight += 2 * credits;
        } else {
            totalWeight += 1 * credits;
        }

        totalCredits += credits;
    }

    return totalWeight / totalCredits;
}

Comments

Comments are used to explain code and are not executed by JavaScript.

// This is a single-line comment

/*
   This is a
   multi-line
   comment
 */

// Example in an academic portal
// Function to calculate a student's GPA
function calcGPA(scores) {
    /*
      * GPA formula:
      * Total (score × credit units) / Total credit units
      * Scale: 4.0
      */
    let total = 0;
    let totalCredits = 0;

    for (let item of scores) {
        total += item.score * item.credits;
        totalCredits += item.credits;
    }

    return total / totalCredits;
}

Writing Your First Script in the Browser Console

Browsers come with a built-in Console that lets you run JavaScript directly without needing to create a .html file.

How to Open the Console

  1. Chrome: Press F12 or Ctrl+Shift+J (Windows) / Cmd+Option+J (Mac)
  2. Firefox: Press F12, then select the "Console" tab
  3. Safari: Enable the Developer menu in Preferences → Advanced, then press Cmd+Option+C

First Script Example

// First script in the browser console

// 1. Display a message
console.log("=== Academic Portal ===");

// 2. Student data variables
const student = {
    studentId: "2024100123",
    name: "John Smith",
    major: "Computer Science",
    semester: 3,
    gpa: 3.75
};

// 3. Display the data
console.log("Student ID:", student.name);
console.log("Name:", student.name);
console.log("Major:", student.major);
console.log(`GPA: ${student.gpa}`);

// 4. Calculate the classification
function determineClassification(gpa) {
    if (gpa >= 3.5) return "Cum Laude";
    if (gpa >= 3.0) return "Very Satisfactory";
    if (gpa >= 2.5) return "Satisfactory";
    if (gpa >= 2.0) return "Fair";
    return "Poor";
}

console.log("Classification:", determineClassification(student.gpa));

Console Output

=== Academic Portal ===
Student ID: John Smith
Name: John Smith
Major: Computer Science
GPA: 3.75
Classification: Cum Laude

Multi-line Strings

There are several ways to write strings that contain multiple lines:

// Method 1: escape character (\n)
let text1 = "Welcome to\nAcademic Portal\nUniversity of Indonesia";
console.log(text1);

// Method 2: template literals (ES6) — recommended
let text2 = `Welcome to
Academic Portal
University of Indonesia`;
console.log(text2);

// Method 3: usage example in an academic portal
const classSchedule = `
================================
FALL SEMESTER CLASS SCHEDULE
================================
Course      : Web Programming
Day         : Monday
Time        : 08:00 - 10:30
Room        : Computer Lab 3
Instructor  : Dr. Brown, MCS
================================
`;

console.log(classSchedule);

Escaping Characters

Some special characters need to be escaped with a backslash (\):

// Escape characters
let quote = "John said, \"Hello!\"";     // Use a backslash
let path = "C:\\Users\\John\\Documents";    // Literal backslash
let newline = "Line 1\nLine 2";          // Newline
let tab = "Name\t: John Smith";          // Tab
let backtick = `This is a template \`literal\``;  // Backtick

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

console.log(path);
// Output: C:\Users\John\Documents

Semicolons and Automatic Semicolon Insertion (ASI)

// ASI adds a ; automatically at the end of a statement
let name = "John"    // ASI adds the ; here
console.log(name)    // ASI adds the ; here

// CAREFUL: ASI can cause bugs!
function getData() {
    return          // ASI adds the ; here, returning undefined!
    {
        name: "John"
    }
}

console.log(getData()); // undefined — not an object!

// Fix: use ; explicitly
function getDataFixed() {
    return {
        name: "John"
    };
}

console.log(getDataFixed()); // { name: "John" }

Basic Syntax Summary

Aspect Description Example
Case-sensitive Uppercase/lowercase are different name ≠ Name
Statements End with ; (recommended) let x = 1;
Whitespace Ignored let x=1; let y=2;
Comments Not executed // comment
Strings Use backticks for multi-line `text`
ASI JavaScript adds ; automatically Can cause bugs

Understanding basic syntax is the foundation before moving on to more complex topics. Always remember to keep your code consistent.