Week 3: Talking to Your Program and Mastering Text

Learn how to interact with users and manipulate strings effectively in JavaScript.

Explore Chapter 3

Chapter 3: Interacting with the User and Working with Text

Output: Displaying Information (console.log, alert, DOM).

Displaying information is crucial for understanding what your program is doing and for communicating with the user.

console.log()

This is the most common way to output information for debugging and development purposes. It prints messages to the browser's developer console (usually opened with F12).

console.log("Hello from the console!");
let user = "Alice";
let score = 100;
console.log("User:", user, "Score:", score); // Outputs multiple items

The console is invaluable for seeing variable values, checking program flow, and diagnosing errors.

alert()

Displays a simple pop-up dialog box with a message and an "OK" button. It halts the execution of the script until the user clicks "OK". Primarily used for simple notifications, but can be intrusive.

alert("This is an alert message!");
alert("Welcome, " + user + "!");

Interacting with the DOM (Brief Intro)

A more common way to display information in a web page is by manipulating the Document Object Model (DOM). This involves changing the content of HTML elements. We'll cover this more in Week 9, but here's a tiny preview:

<p id="messageArea">Initial text.</p>

<script>
  // Find the paragraph element by its ID
  let messageElement = document.getElementById("messageArea");
  // Change its text content
  messageElement.textContent = "New message set by JavaScript!";
</script>

Input: Getting Data (prompt, DOM Elements).

Programs often need to get input from the user.

prompt()

Displays a dialog box that prompts the user for input. It includes a message, an input field, an "OK" button, and a "Cancel" button.

let userName = prompt("Please enter your name:");
let ageStr = prompt("Enter your age:", "18"); // Optional second argument for default value

console.log("User entered name:", userName);
console.log("User entered age string:", ageStr);

// IMPORTANT: prompt() always returns a string or null (if cancelled)
if (ageStr !== null) {
  let ageNum = parseInt(ageStr); // Convert string to number
  if (!isNaN(ageNum)) { // Check if conversion was successful
     console.log("Age as number:", ageNum);
  } else {
     console.log("Invalid age entered.");
  }
} else {
  console.log("User cancelled the age prompt.");
}

Like alert(), prompt() halts script execution and can be disruptive to the user experience. It's rarely used in modern web applications.

Getting Values from HTML Elements

The standard way to get user input in web applications is through HTML form elements like <input>, <textarea>, <select>, etc. JavaScript is then used to read the values from these elements, often triggered by events like button clicks.

<label for="emailInput">Email:</label>
<input type="email" id="emailInput">
<button onclick="showEmail()">Show Email</button>

<script>
  function showEmail() {
    // Get the input element
    let emailInputElement = document.getElementById("emailInput");
    // Get the current value from the input field
    let email = emailInputElement.value;
    alert("You entered: " + email);
  }
</script>

We'll delve deeper into handling form inputs and events later in the course.

String Properties and Basic Manipulation.

Strings are sequences of characters. JavaScript provides ways to access information about strings and perform basic operations.

length Property

The length property returns the number of characters in a string.

let text = "JavaScript";
console.log(text.length); // Output: 10

Accessing Characters (Indexing)

You can access individual characters in a string using bracket notation [] with the character's index (position). Indices start at 0.

let language = "JavaScript";
let firstChar = language[0];       // 'J'
let secondChar = language[1];      // 'a'
let lastChar = language[language.length - 1]; // 't'

console.log("First:", firstChar, "Last:", lastChar);

// Note: Strings are immutable in JS. You cannot change a character like this:
// language[0] = 'j'; // This will not work or cause an error silently.

Trying to access an index outside the string's bounds usually returns undefined.

Concatenation (+) Operator)

The + operator concatenates (joins) strings together.

let str1 = "Hello";
let str2 = "World";
let combined = str1 + " " + str2 + "!"; // "Hello World!"
console.log(combined);

Common String Methods: Powerful Text Tools.

JavaScript strings have many built-in methods for manipulation. These methods return *new* strings; they don't modify the original string (since strings are immutable).

  • toUpperCase() / toLowerCase(): Converts the string to uppercase or lowercase.
    let message = "Learning JS";
    console.log(message.toUpperCase()); // "LEARNING JS"
    console.log(message.toLowerCase()); // "learning js"
  • trim(): Removes whitespace from both the beginning and end of the string. (trimStart(), trimEnd() also exist).
    let padded = "    Extra Space    ";
    console.log(padded.trim()); // "Extra Space"
  • indexOf(substring) / lastIndexOf(substring): Returns the index of the first (or last) occurrence of a substring. Returns -1 if not found.
    let sentence = "The quick brown fox jumps over the lazy dog.";
    console.log(sentence.indexOf("fox")); // 16
    console.log(sentence.indexOf("cat")); // -1
    console.log(sentence.indexOf("the")); // 31 (finds the second 'the')
    console.log(sentence.lastIndexOf("the")); // 31
  • includes(substring): Returns true if the string contains the specified substring, false otherwise.
    console.log(sentence.includes("brown")); // true
    console.log(sentence.includes("elephant")); // false
  • slice(startIndex, endIndex): Extracts a section of the string and returns it as a new string. endIndex is exclusive. Negative indices count from the end.
    let word = "Programming";
    console.log(word.slice(0, 4)); // "Prog"
    console.log(word.slice(4));    // "ramming" (from index 4 to end)
    console.log(word.slice(-4));   // "ming" (last 4 characters)
  • replace(searchValue, newValue): Returns a new string where the *first* occurrence of searchValue (can be a string or regex) is replaced by newValue. Use replaceAll() or a global regex for multiple replacements.
    let msg = "Please visit Microsoft!";
    let newMsg = msg.replace("Microsoft", "Our Website");
    console.log(newMsg); // "Please visit Our Website!"
  • split(separator): Splits the string into an array of substrings based on the separator.
    let data = "apple,banana,cherry";
    let fruitsArray = data.split(',');
    console.log(fruitsArray); // ["apple", "banana", "cherry"]
    
    let phrase = "JavaScript is fun";
    let wordsArray = phrase.split(' ');
    console.log(wordsArray); // ["JavaScript", "is", "fun"]
  • Many others (startsWith(), endsWith(), charAt(), padStart(), padEnd(), etc.)

Template Literals (Template Strings).

Introduced in ES6, template literals provide an easier and more readable way to create strings, especially those containing variables or expressions.

They are enclosed by backticks (`` ` ``) instead of single or double quotes.

Features:

  • Embedded Expressions: You can embed variables and expressions directly within the string using the ${expression} syntax. The expression is evaluated, and its result is included in the string.
    let userName = "Bob";
    let items = 3;
    let total = 75.50;
    
    let report = `User: ${userName}
    Items purchased: ${items}
    Total cost: $${total.toFixed(2)}`; // .toFixed(2) formats the number
    
    console.log(report);
    /* Output:
    User: Bob
    Items purchased: 3
    Total cost: $75.50
    */
  • Multiline Strings: Strings created with backticks can span multiple lines without needing special characters like \n.
    let poem = `The rain in Spain
    falls mainly on the plain.`;
    console.log(poem);

Template literals are generally preferred over traditional string concatenation (+) for embedding variables due to their improved readability.

Quick Look: JavaScript and the Web Page (DOM)

While we've focused on core language features, remember that a primary use of JavaScript is interacting with HTML web pages. This is done via the Document Object Model (DOM).

The DOM represents the HTML document as a tree of objects. JavaScript can access and modify these objects (elements, attributes, text) to dynamically change the page content and style.

We briefly saw examples using document.getElementById() and .textContent. We will explore DOM manipulation in much more detail in Week 9.

// Example reminder: Changing text
// Assuming: <p id="demo">Hello</p>
// document.getElementById("demo").textContent = "Hello JavaScript!";
Syllabus