OIM3690 - Web Technologies

contain

Variables

Variables in JavaScript

  • A variable is a container that holds a value.
    • It can store values like numbers, text, objects, or DOM elements.
  • Note:
    • Variables aren't the values themselves; they are containers for values.
    • You can think of them like little cardboard boxes that store things.

Declaring Variables using let and const

  • Creating a variable in JavaScript is called "declaring" a variable
  • Use let to declare a variable when the variableโ€™s value may change.
    • Example:
      let x = 10; 
      //Some JS statements 
      x = 20;
      
  • Use const to declare a variable with a constant value.
    • Example:
      const COLUMNS = 80;  
      // ...  
      COLUMNS = 120; // Uncaught TypeError: Assignment to constant variable.
      
  • Avoid Using var (outdated)

Avoid Using var in Modern JavaScript

  • var has function scope, while let and const have block scope.
  • var allows re-declaring the same variable in the same scope, which can cause bugs.
  • var is hoisted, but in an unexpected way (declared but uninitialized).

Naming Conventions

  • Follow JavaScript naming rules:
    • Start with a letter, _, or $ (not a number).
    • No spaces or special characters (&, %, etc.).
    • JavaScript is case-sensitive (myVar != myvar).
  • Avoid conflicts with built-in DOM objects
    • ๐Ÿ‘Ž: form, element, backgroundColor
    • ๐Ÿ‘: userForm, mainElement, bgColor
  • Use standard naming styles:
    • Variables & functions โ†’ lowerCamelCase
    • Constants โ†’ CONSTANT_CASE (Recommended by Google Style Guide)
    • Classes โ†’ UpperCamelCase

Arithmetic Manipulation of Variables

  • Example 1: Declaration & Assignment
    let x;  // Declare a variable x
    x = 10; // Assign 10 to x
    
  • Example 2: Arithmetic Manipulation
    let x = 10;  // Declare and assign x
    x = x + 10;  // Add 10 to x
    x = x * 5;   // Multiply x by 5
    x = x / 5;   // Divide x by 5
    
    // Alternative shorthand
    x += 10;  // Equivalent to x = x + 10
    x *= 5;   // Equivalent to x = x * 5
    x /= 5;   // Equivalent to x = x / 5
    

Basic Data Types in JavaScript

  • JavaScript is dynamically typed, meaning a variableโ€™s type can change at runtime.
    • let x = 10; // x is a number
      x = "Hello"; // Now x is a string
      
  • Common Data Types:
    • Numbers: Integers and floating-point numbers.
    • Strings: Text enclosed in single ('text') or double ("text") quotes.
    • Booleans: Represents true or false.
    • Null: Explicitly set to indicate "no value".
    • Undefined: Default value for uninitialized variables.
    • Objects: Data structures that store multiple values in key-value pairs.
      • Objects can include arrays, functions, and other objects as properties.

Arithmetic Operators

  • Some common arithmetic operators
    • + (addition), - (subtraction), * (multiplication), / (division), % (modulo)
    • ++ (increment), -- (decrement)
    • +=, -=, *=, /=, %= (compound assignment)
  • Examples:
    let x = 10, y = 3;
    
    console.log(x + y);  // โž 13  (Addition)
    console.log(x - y);  // โž 7   (Subtraction)
    console.log(x * y);  // โž 30  (Multiplication)
    console.log(x / y);  // โž 3.33 (Division)
    console.log(x % y);  // โž 1   (Remainder)
    console.log(x ** y); // โž 1000 (Exponentiation)
    x++; console.log(x); // โž 11  (Increment)
    y--; console.log(y); // โž 2   (Decrement)
    

Practice

  • Open Console in your browser Developer Tools.
  • Try each arithmetic operator on different numbers.
  • Questions:
    • What is the result of 10 % 3? What about 12 % 4?
    • Try x += y; and x *= y;. What do they do?
    • What happens if you mix strings with numbers using +?

Handling Strings

  • String Concatenation: Combining strings using +.
  • Example:
    let firstName = "Michael"; 
    let lastName = " Scott";
    let fullName = firstName + lastName;  
    console.log(fullName); // "Michael Scott"
    
    let age = 21;
    let message = "I am " + age + " years old.";  
    console.log(message); // "I am 21 years old."
    
    // Mixing numbers and strings
    console.log("10" + 5); // "105" (5 is converted to string)
    console.log(10 + 5);   // 15 (Both are numbers)
    

Functions

What is a Function?

  • A function is a reusable block of code that performs a task.
    • Functions help organize code and avoid repetition.
  • JavaScript provides two types of functions:
    • Built-in functions (provided by JavaScript).
    • User-defined functions (you create them).
  • JavaScript functions should:
    • Take input (parameters).
    • Perform actions.
    • Return a result (optional).

Built-in JavaScript Functions

  • Global Functions (No object needed)
    parseInt("42");  // Converts a string to a number
    alert("Hello!"); // Displays a popup
    
  • Methods (Functions attached to objects)
    console.log("Hello!"); // Method of the console object
    document.getElementById("id"); // Finds an element in the DOM
    document.write("Hello!"); // Writes to the document
    
    • A function that belongs to an object is called a "method".

Write Your Own Functions

  • Syntax:
      function functionName(parameter(s)) {
          // Function body (instructions)
          // ...
          return result; // Optional
      }
    
  • Functions can:
    • Accept parameters (values passed to the function).
    • Use the return keyword to send back a result.
    • Be called multiple times with different arguments.

Examples of Functions

  • Example 1: Runs a task but does not return a value
    • function greet() {
          console.log("Hello, welcome to JavaScript!");
      }
      
      greet(); // Output: "Hello, welcome to JavaScript!"
      
    • When side effects (e.g., printing to the console, updating page) are needed.
  • Example 2: Takes input and returns an output
    • function add(a, b) {
          return a + b;
      }
      
      let sum = add(5, 3);
      console.log(sum); // Output: 8
      
    • The returned value can be stored in a variable (sum) or used directly.

Exercise: ex14.html

  • Download ex14.html from GitHub (OIM3690/resources/templates).
  • Write a function that will enlarge the image when user moves mouse over the image.
    • How do we define this function in script?
    • What is the event? Element (eventTarget)?
    • How do we change the image size using JavaScript?
    • Let's write pseudo-code together.
    • Besides enlarging the image, can you also change something else in the same function?

Exercise: ex14.html (cont.)

  • Write another function that will resize the image to original size when user moves mouse off it.
  • Update sitemap.html and commit/push to GitHub

Exercise: ex14-2.html (Optional)

  • Same as ex14.html, but you need to use same functions to work with multiple images.
    • Need to add parameters/arguments to functions.
    • This could be very confusing if you don't understand the purpose of arguments.
  • Update sitemap.html and commit/push to GitHub

Questions?