Skillversitas

Variables in JavaScript

What Is a Variable?

A variable is a data storage container with a specific name. In programming, variables are used to store, retrieve, and manipulate data. Think of a variable as a labeled box containing something.

// Simple variable example
let name = "John Smith";
let studentId = "2024100123";
let gpa = 3.75;
let active = true;

console.log(name); // "John Smith"
console.log(studentId);  // "2024100123"
console.log(gpa);  // 3.75

Three Ways to Declare Variables

1. var (the Old Way)

var is the variable declaration method from older versions of JavaScript. Although it still works, it is not recommended for modern code.

// Declaration with var
var name = "John Smith";
var semester = 3;
var gpa = 3.75;

// var can be redeclared (dangerous!)
var name = "Mike Johnson";
console.log(name); // "Mike Johnson" — John's data is lost!

// var can be accessed before its declaration (hoisting)
console.log(course); // undefined — no error!
var course = "Web Programming";

2. let (the Modern Way — for data that changes)

let was introduced in ES6 and is the standard for variables whose values can change.

// Declaration with let
let semester = 3;
let gpa = 3.75;

// let CANNOT be redeclared in the same scope
// let semester = 4; // SyntaxError!

// But its value can be changed
semester = 4;
console.log(semester); // 4

// let CANNOT be accessed before its declaration
// console.log(credits); // ReferenceError!
let credits = 20;

3. const (constant — for data that does not change)

const was also introduced in ES6. It is used for values that must not be changed.

// Declaration with const
const CAMPUS_NAME = "University of Indonesia";
const MAX_CREDITS = 24;
const ACADEMIC_YEAR = "2024/2025";

// const CANNOT be reassigned
// MAX_CREDITS = 30; // TypeError!

// const CANNOT be redeclared
// const MAX_CREDITS = 30; // SyntaxError!

// But for objects/arrays, the contents can be modified
const student = {
    name: "John",
    gpa: 3.75
};

// This IS OK — modifying the object's contents
student.gpa = 3.80;
console.log(student.gpa); // 3.80

// This IS NOT OK — replacing the reference
// student = {}; // TypeError!

Comparing var, let, and const

// === COMPARISON ===

// 1. Hoisting
console.log(a); // undefined (hoisted with a default value)
var a = 1;

// console.log(b); // ReferenceError! (TDZ)
let b = 2;

// console.log(c); // ReferenceError! (TDZ)
const c = 3;

// 2. Redeclaration
var x = 1;
var x = 2; // OK

let y = 1;
// let y = 2; // SyntaxError!

// 3. Reassignment
var m = 1;
m = 2; // OK

let n = 1;
n = 2; // OK

const o = 1;
// o = 2; // TypeError!

// 4. Scope
// var: function scope
// let/const: block scope

function demoScope() {
    if (true) {
        var varScope = "var — accessible outside the block";
        let letScope = "let — only inside the block";
        const constScope = "const — only inside the block";
    }

    console.log(varScope);   // OK — exists
    // console.log(letScope);     // ReferenceError!
    // console.log(constScope);   // ReferenceError!
}

Hoisting

Hoisting is JavaScript's behavior of moving variable declarations to the top of the scope during compilation.

// Hoisting with var
console.log(name); // undefined (not an error!)
var name = "John";

// Hoisting with let/const
// console.log(studentId); // ReferenceError! (Temporal Dead Zone)
let studentId = "2024100123";

// Hoisting with functions
console.log(calcCredits(20)); // OK — functions are fully hoisted

function calcCredits(credits) {
    return `Total credits: ${credits}`;
}

// Arrow functions are NOT hoisted
// console.log(identity(85)); // ReferenceError!
const identity = (value) => value;

Temporal Dead Zone (TDZ)

// TDZ: the period from the start of the scope until the let/const declaration
{
    // TDZ for 'score' starts here
    // console.log(score); // ReferenceError!

    // TDZ ends here
    let score = 85;
    console.log(score); // 85
}

// Usage in an academic portal
function processGrading(student) {
    // TDZ — 'result' is not accessible yet
    const classification = determineClassification(student.gpa);

    // After the declaration, it can be accessed
    const result = {
        name: student.name,
        classification: classification,
        passed: student.gpa >= 2.0
    };

    return result;
}

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

Naming Conventions

JavaScript has naming rules that must be followed:

Mandatory Rules

// ✅ Allowed: letters, digits, _, $
let name = "John";
let _private = true;
let $element = document.querySelector(".card");
let学生2 = "Mike"; // Unicode is allowed (not recommended)

// ❌ CANNOT start with a digit
// let 1name = "John"; // SyntaxError!

// ❌ CANNOT use keywords
// let let = 1; // SyntaxError!
// let class = "A"; // SyntaxError!

Naming Conventions

// camelCase — standard for variables and functions
let studentName = "John Smith";
let studentGPA = 3.75;

function calcGPA(scores) {
    // ...
}

// PascalCase — for classes and constructors
class Student {
    // ...
}

// UPPER_SNAKE_CASE — for constants
const MAX_CREDITS = 24;
const API_URL = "https://api.campus.edu";
const ACADEMIC_YEAR = "2024/2025";

// snake_case — common in backend / database (not standard JS)
// let student_name = "John"; // Less recommended

Meaningful Names

// ❌ Bad naming
let x = "John Smith";
let a = 3.75;
let arr = [1, 2, 3];
let temp = true;

// ✅ Good naming
let studentName = "John Smith";
let studentGPA = 3.75;
let creditList = [1, 2, 3];
let activeStatus = true;

Case Study: Storing Student Data in an Academic Portal

// === STUDENT DATA ===

// Constants (do not change)
const CAMPUS_NAME = "University of Indonesia";
const MAX_CREDITS_PER_SEMESTER = 24;
const MIN_GPA_TO_PASS = 2.0;

// Student data (can change with let)
let studentId = "2024100123";
let name = "John Smith";
let major = "Computer Science";
let semester = 3;
let gpa = 3.75;
let activeStatus = true;

// Course list (const because the reference does not change)
const courseList = [
    { code: "IF101", name: "Web Programming", credits: 3 },
    { code: "IF102", name: "Database", credits: 3 },
    { code: "IF103", name: "Algorithms", credits: 4 }
];

// === CHECK FUNCTIONS ===

function checkCreditEligibility(newCredits, currentCredits) {
    if (currentCredits + newCredits > MAX_CREDITS_PER_SEMESTER) {
        return {
            eligible: false,
            message: `Exceeds the maximum of ${MAX_CREDITS_PER_SEMESTER} credits!`
        };
    }
    return {
        eligible: true,
        message: "You are allowed to enroll in the course."
    };
}

function checkAcademicStatus(gpa) {
    if (gpa >= 3.5) return { classification: "Cum Laude", scholarship: true };
    if (gpa >= 3.0) return { classification: "Very Satisfactory", scholarship: true };
    if (gpa >= 2.5) return { classification: "Satisfactory", scholarship: false };
    if (gpa >= 2.0) return { classification: "Fair", scholarship: false };
    return { classification: "Poor", scholarship: false, warning: "Below the minimum threshold!" };
}

// === USAGE ===

const currentCredits = courseList.reduce((total, c) => total + c.credits, 0);
const creditCheck = checkCreditEligibility(6, currentCredits);
console.log(creditCheck.message);

const academicStatus = checkAcademicStatus(gpa);
console.log(`${name} — Classification: ${academicStatus.classification}`);
console.log(`Scholarship Status: ${academicStatus.scholarship ? "Yes" : "No"}`);

// === UPDATE DATA ===
semester = 4; // Can be changed (let)
gpa = 3.80;  // Can be changed (let)
console.log(`Semester: ${semester}, GPA: ${gpa}`);

Summary

Aspect var let const
Scope Function Block Block
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Redeclaration Yes ❌ ❌
Reassignment Yes Yes ❌
Recommendation ❌ Avoid Use Use (default)

Rules of thumb:
- Use const as the default
- Use let only when the value needs to change
- Avoid var entirely