Web Technology IUnit 514 min read

JavaScript Basics: Data Types, Variables, Functions & Logic

Unit 5 of Web Technology I introduces the core building blocks of JavaScript—data types, variables, functions, and basic logic—explaining how they work under the hood, their practical applications, and how they enable dynamic web interactions.

TAKEAWAYS:

  • JavaScript is a client-side scripting language that powers dynamic content, interactivity, and form validation on web pages.
  • Data types (primitives like string, number, boolean) and variables (containers for data) form the foundation of any JavaScript program.
  • Functions modularize code, improve reusability, and enable event-driven programming (e.g., button clicks).
  • Operators (+, ==, &&) and control structures (if, for) allow logic to manipulate data dynamically.
  • Scope rules (global vs. local) determine variable accessibility, preventing conflicts in larger applications.
  • Real-world use cases include eSewa’s transaction validation, Khalti’s payment logic, and Daraz’s dynamic product filtering.

1. Introduction to JavaScript: The Language of the Web

JavaScript (JS) is the only programming language natively supported by web browsers. It runs on the client side, enabling real-time user interactions without server requests. Unlike HTML (structure) or CSS (styling), JavaScript adds behavior—think of it as the "brain" of a webpage.

How JavaScript Works Under the Hood

When a browser loads a webpage, it:

  1. Parses HTML/CSS.
  2. Executes JavaScript in the JavaScript Engine (e.g., V8 in Chrome, SpiderMonkey in Firefox).
  3. Interacts with the DOM (Document Object Model) to update content dynamically.

Key Idea: JavaScript is interpreted (not compiled like Java/C++), meaning it executes line-by-line. Modern engines optimize this with JIT (Just-In-Time) compilation.


2. Data Types: The Building Blocks of JavaScript

JavaScript has primitive and non-primitive (reference) data types. Primitives are immutable (cannot be changed after creation).

Primitive Data Types

Type Example Description Example Value
string "Hello" Text data, enclosed in single/double quotes. "JavaScript"
number 42, 3.14 Integer or floating-point numbers. 100, -0.5
boolean true, false Represents logical values. isLoggedIn = true
null null Represents "no value" (intentional absence). let result = null
undefined undefined Default value for undeclared variables. let x; → x
symbol Symbol() Unique and immutable identifier (rarely used in basics). const id = Symbol()
bigint 123n Represents integers larger than 2^53 - 1. 9007199254740991n

Non-Primitive (Reference) Types

  • object: Collections of key-value pairs (e.g., arrays, JSON).
    let person = { name: "Alice", age: 25 };
    
  • array: Ordered list of values.
    let fruits = ["apple", "banana", "cherry"];
    

Visualization:

mindmap
  root((JavaScript Data Types))
    Primitive Types
      string
      number
      boolean
      null
      undefined
      symbol
      bigint
    Non-Primitive Types
      object
        arrays
        JSON

Worked Example: Data Type Conversion Convert the following to the opposite type:

  1. "10" + 5 → "105" (string concatenation)
  2. Number("10") + 5 → 15 (explicit conversion to number)
  3. String(10) + 5 → "105" (explicit conversion to string)

Real-World Tie:

  • eSewa’s Transaction Validation: When a user submits a payment, eSewa checks if the input is a valid number (e.g., 1000 vs. "abc"). Invalid inputs trigger client-side validation using JavaScript’s typeof operator:
    if (typeof amount !== "number") {
      alert("Please enter a valid amount!");
    }
    

3. Variables: Storing and Manipulating Data

Variables are containers for data. JavaScript uses let, const, and var to declare them.

Keyword Scope Re-declarable? Hoisted? Example
let Block (function) No Yes let x = 10;
const Block (function) No Yes const PI = 3.14;
var Function (global) Yes Yes var y = 20; (legacy)

Key Rules:

  • const cannot be reassigned (but properties of objects can be changed).
  • let can be updated but not redeclared in the same scope.
  • var is function-scoped and hoisted (avoid in modern JS).

Visualization:

stateDiagram-v2
    [*] --> VariableDeclaration
    VariableDeclaration --> LetScope: Block-scoped (let)
    VariableDeclaration --> ConstScope: Block-scoped (const)
    VariableDeclaration --> VarScope: Function-scoped (var)

Worked Example: Variable Scope

function example() {
  if (true) {
    let x = 10;
    var y = 20;
  }
  console.log(x); // Error: x is not defined (block-scoped)
  console.log(y); // 20 (function-scoped)
}

Real-World Tie:

  • Khalti’s Payment Flow: When a user selects a payment method (e.g., credit card), Khalti stores the selected option in a let variable and updates the UI dynamically:
    let paymentMethod = "credit_card";
    document.getElementById("payment-method").textContent = paymentMethod;
    

4. Operators: Manipulating Data

Operators perform operations on variables/values. Key categories:

Arithmetic Operators

Operator Example Description
+ 5 + 3 Addition
- 5 - 3 Subtraction
* 5 * 3 Multiplication
/ 5 / 3 Division
% 5 % 3 Modulus (remainder)
** 2 ** 3 Exponentiation (ES6+)

Comparison Operators

Operator Example Description
== 5 == "5" Loose equality (type coercion)
=== 5 === 5 Strict equality (type + value)
!= 5 != "5" Not equal (loose)
!== 5 !== "5" Not equal (strict)
> 5 > 3 Greater than
< 5 < 3 Less than

Key Difference:

  • == converts types before comparison (e.g., "5" == 5 → true).
  • === checks both type and value (e.g., "5" === 5 → false).

Worked Example: Comparison Pitfalls

console.log(0 == false);   // true (0 is falsy, false is falsy)
console.log(0 === false);  // false (types differ)

Logical Operators

Operator Example Description
&& true && false Logical AND
|| true || false Logical OR
! !true Logical NOT

Real-World Tie:

  • Daraz’s Order Queue: When a user adds an item to their cart, Daraz checks if the cart is not empty (!isEmpty) and the user is logged in (isLoggedIn) before proceeding:
    if (!isEmpty && isLoggedIn) {
      proceedToCheckout();
    }
    

5. Functions: Reusable Code Blocks

Functions group reusable code, improve readability, and enable modularity. Syntax:

function functionName(parameters) {
  // code
  return value; // optional
}

Types of Functions

  1. Named Functions:
    function greet(name) {
      return `Hello, ${name}!`;
    }
    
  2. Arrow Functions (ES6+):
    const greet = (name) => `Hello, ${name}!`;
    
  3. Immediately Invoked Function Expression (IIFE):
    (function() {
      console.log("Runs once");
    })();
    

Function Parameters vs. Arguments

  • Parameters: Placeholders in the function definition.
  • Arguments: Actual values passed when calling the function.

Worked Example: Function Call

function add(a, b) { // Parameters: a, b
  return a + b;
}
let result = add(5, 3); // Arguments: 5, 3 → result = 8

Scope Inside Functions

Variables declared inside a function are local (accessible only within that function).

function example() {
  let z = 30;
  console.log(z); // 30 (local to example)
}
console.log(z); // Error: z is not defined

Real-World Tie:

  • Pathao’s Ride Booking: When a user requests a ride, Pathao uses a function to calculate fare based on distance and time:
    function calculateFare(distance, time) {
      return distance * 0.5 + time * 0.2;
    }
    let fare = calculateFare(5, 10); // $3.50
    

6. Control Structures: Logic and Flow

Control structures alter the flow of execution based on conditions.

Conditional Statements

  1. if Statement:
    if (condition) {
      // code
    }
    
  2. else if and else:
    if (score >= 90) {
      grade = "A";
    } else if (score >= 80) {
      grade = "B";
    } else {
      grade = "C";
    }
    
  3. Ternary Operator (shorthand if):
    let message = (score >= 80) ? "Pass" : "Fail";
    

Loops

  1. for Loop:
    for (let i = 0; i < 5; i++) {
      console.log(i); // 0, 1, 2, 3, 4
    }
    
  2. while Loop:
    let i = 0;
    while (i < 5) {
      console.log(i);
      i++;
    }
    
  3. do...while Loop:
    let i = 0;
    do {
      console.log(i);
      i++;
    } while (i < 5);
    

Visualization:

sequenceDiagram
    participant User
    participant JavaScript
    User->>JavaScript: Checks if (score >= 80)
    alt True
        JavaScript->>User: Sets grade = "A"
    else False
        JavaScript->>JavaScript: Checks if (score >= 70)
        alt True
            JavaScript->>User: Sets grade = "B"
        else False
            JavaScript->>User: Sets grade = "C"
        end
    end

Worked Example: Grade Calculator

function calculateGrade(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  return "F";
}
console.log(calculateGrade(85)); // "B"

Real-World Tie:

  • NTC’s Traffic Light System: Traffic lights use a while loop to cycle through red, yellow, and green states:
    let currentLight = "red";
    while (true) {
      if (currentLight === "red") {
        console.log("Stop");
        setTimeout(() => { currentLight = "green"; }, 30000);
      }
      // ... (similar for yellow/green)
    }
    

7. Common Pitfalls and Best Practices

Pitfall Solution Example
Hoisting (var) Use let/const Avoid var x; x = 5; → use let x = 5;
Type Coercion (==) Use === for strict comparison if (age === 18) instead of if (age == 18)
Global Scope Pollution Declare variables in smallest scope Use const inside functions
Uninitialized Variables Always declare variables let x; → let x = null;
Infinite Loops Add loop conditions carefully for (let i = 0; i < 10; i++)

In the Real World

  1. eSewa’s Transaction Validation:

    • Idea: JavaScript’s typeof and if statements validate user inputs (e.g., ensuring an amount is a number).
    • Example: When a user submits a payment of "abc", eSewa’s frontend checks:
      if (typeof amount !== "number") {
        alert("Invalid amount!");
      }
      
  2. Khalti’s Dynamic Payment UI:

    • Idea: Arrow functions and event listeners update the UI based on user selections (e.g., switching between credit card and mobile wallet).
    • Example: Selecting "Mobile Wallet" triggers:
      document.getElementById("payment-method").addEventListener("change", (e) => {
        if (e.target.value === "mobile") {
          document.getElementById("wallet-field").style.display = "block";
        }
      });
      
  3. Daraz’s Product Filtering:

    • Idea: Loops and arrays filter products dynamically (e.g., showing only "Electronics" when the user clicks a category).
    • Example:
      const electronics = products.filter(product => product.category === "Electronics");
      
  4. Pathao’s Fare Calculation:

    • Idea: Functions encapsulate logic (e.g., calculateFare(distance, time)) for reusability.
    • Example: A ride from Thapathali to Gaushala (5 km, 10 mins) costs:
      let fare = calculateFare(5, 10); // $3.50
      

Exam Tip

This unit is highly practical and often tested with:

  1. Short Answer Questions (SAQs):
    • Define let, const, and var with examples.
    • Explain the difference between == and ===.
    • Write a function to reverse a string.
  2. Long Answer Questions (LAQs):
    • Design a JavaScript function to validate a user’s email format (using if and regex).
    • Explain how scope works in JavaScript with a diagram.
    • Write a loop to sum all even numbers in an array.
  3. Coding Questions:
    • Debug a given JavaScript snippet (e.g., hoisting issues, type errors).
    • Write a function to check if a number is prime.
    • Use for...of or map() to process an array.

Key Focus Areas:

  • Syntax: Correct use of let, const, functions, and loops.
  • Logic: Writing conditions (if/else) and loops (for/while).
  • Real-World Mapping: Connect JS concepts to apps like eSewa or Daraz.
  • Common Errors: Avoid hoisting (var), type coercion (==), and global scope pollution.

Pro Tip:

  • Always declare variables before use (let x = 5 instead of x = 5).
  • Use strict equality (===) to avoid unexpected type coercion.
  • Practice debugging by intentionally introducing errors (e.g., missing return in a function).

Based on the TU BIM syllabus for Web Technology I (IT237), unit 5.

Discussion

Loading…