Adding JS and using I/O

It's easy to add JavaScript to HTML, but we need be able to "see" it running in order to feel confident.

One of the simplest ways to see JavaScript in action is by using the console.log function. Much like when we use it to print to the terminal in Node.js, in a web browser this function outputs messages to the web browser's console, which is a part of the developer tools available in most modern browsers. The developer tools can be accessed by right-clicking on a web page and selecting "Inspect" or by pressing F12 on your keyboard. The console is useful for debugging and testing JavaScript code.

To add JavaScript to an HTML document, you can use the <script> element. This element can be placed within the <head> or <body> sections of your HTML. Here is an example of using the <script> element to include JavaScript directly within an HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <script>
        console.log('This message is logged from an inline script.');
    </script>
</body>
</html>

In the example above, the console.log function is used to print a message to the console when the page loads. This is an inline script because the JavaScript code is written directly within the <script> element.

Another way to add JavaScript to an HTML document is by using an external script file. This approach is useful for keeping your HTML and JavaScript code separate and more organized. To use an external script file, you need to create a separate .js file and link it to your HTML document using the src attribute of the <script> element. Here is an example:

First, create a file named script.js with the following content:

console.log('This message is logged from an external script.');

Next, link this external script file in your HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <script src="script.js"></script>
</body>
</html>

In this example, the console.log function in the script.js file will execute when the HTML page loads, and the message will still be printed to the console.

When does the code execute?

JavaScript code execution depends on where and how the code is included in the HTML document.

  1. Inline JavaScript: If the JavaScript code is not inside a function, it executes as soon as the browser loads it. This means that the code runs immediately when the HTML parser encounters the <script> tag.

  2. Script Loading Order: Script elements are loaded and executed in a top-down manner. This means that the order in which <script> tags appear in the HTML document matters. Scripts at the top of the document will execute before those at the bottom.

  3. External Scripts: When using external scripts (e.g., <script src="script.js"></script>), the browser makes a separate request to the web server to fetch the script file. The execution of these scripts can be delayed due to network latency, and they execute at undetermined times once they are fully loaded.

  4. Async and Defer Attributes:

    • Async: Scripts with the async attribute are fetched asynchronously and executed as soon as they are available, without blocking the HTML parsing.
    • Defer: Scripts with the defer attribute are fetched asynchronously but executed only after the HTML document has been completely parsed.

Understanding these concepts is crucial for optimizing the performance and behavior of your web pages.

Using console.log for Debugging

The console.log function is a powerful tool for developers to debug and test their JavaScript code. It allows you to output messages, variables, and objects to the web browser's console, which is part of the developer tools available in most modern browsers.

Why Use console.log?

  1. Debugging: console.log helps you understand the flow of your code and inspect the values of variables at different points in time. This can be invaluable when trying to identify and fix bugs.
  2. Testing: You can use console.log to test small snippets of code and verify that they produce the expected results.

Limited Audience

It's important to note that the messages logged using console.log are only visible to developers who have access to the browser's developer tools. Almost no end user of your website will see these messages because they are not typically aware of the developer tools or how to access them. Therefore, console.log should never be used as a means of communicating with end users. It is strictly a development tool meant for the developer's eyes only.

In summary, while console.log is an essential tool for debugging and testing during development, it should not be relied upon for user-facing messages or functionality. For user interactions, consider using the DOM to update the content of your web pages dynamically.

Creating an Alert Dialog

Another way to see JavaScript in action is by using the alert function. This function displays a dialog box with a specified message and an OK button. Here is an example of using the alert function:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Alert Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <script>
        alert('This is an alert dialog!');
    </script>
</body>
</html>

In this example, an alert dialog with the message "This is an alert dialog!" will be displayed when the page loads.

Why Alert Dialogs Aren't Ideal

While the alert function can be useful for quickly testing and debugging JavaScript code, it is generally not recommended for use in production code for several reasons:

  1. Interruptive: Alert dialogs are modal, meaning they block user interaction with the rest of the web page until the user dismisses the dialog. This can be disruptive to the user experience.
  2. Limited Customization: Alert dialogs have a standard appearance that cannot be customized, which may not align with the design of your web application.
  3. Security Concerns: Overusing alert dialogs can lead to security concerns, such as clickjacking, where users are tricked into clicking on something they didn't intend to.

Despite these drawbacks, the alert function can still be useful for simple debugging tasks or for educational purposes when learning JavaScript.

To use the alert function, simply call it with a string argument containing the message you want to display:

alert('This is an alert dialog!');

Remember to use alert dialogs sparingly and consider other methods for providing feedback to users, such as updating the DOM or using custom modal dialogs created with HTML and CSS.

Getting Input with a Dialog

In addition to displaying messages, JavaScript can also be used to get input from the user through dialog boxes. The prompt function displays a dialog box that prompts the user to enter some text. Here is an example of using the prompt function:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Prompt Example</title>
</head>
<body>
    <h1>Hello, World!</h1>
    <script>
        var userInput = prompt('Please enter your name:');
        console.log('User entered: ' + userInput);
    </script>
</body>
</html>

In this example, a prompt dialog will appear asking the user to enter their name. The entered value is then logged to the console.

Why Prompt Dialogs Aren't Ideal

Similar to alert dialogs, prompt dialogs are not recommended for production use due to their interruptive nature and limited customization options. Instead of using dialogs, we will soon learn how to use regular HTML forms to get input from users in a more user-friendly and flexible way.

Next - what can we do?

Now that we have some JavaScript executing in the browser, let's learn how to do more than just print or throw ugly dialogs up at the user. The real power of client-side JavaScript lies in our ability to interact with the HTML loaded in the page. Since HTMl has input elements (forms), and many elements for displaying content (nearly every HTML element!), it's far more powerful and effective to use HTML to communicate with the user rather than using alert, prompt, or the console.