What is JavaScript?

JavaScript (JS) is a high-level, dynamic programming language that allows you to make web pages interactive. While HTML provides the structure and CSS adds the style, JavaScript brings the page to life. Image sliders, form validations, and dynamic content updates are all powered by JavaScript. It runs directly in the user's web browser, thanks to a built-in "JavaScript engine" like Google's V8 (used in Chrome and Node.js).

How to Add JavaScript to a Page

There are two primary ways to include JavaScript on your website:

  1. Internal JavaScript: You can write your code directly inside <script> tags within your HTML file. This is fine for small scripts.

html-

<!DOCTYPE html>
<html>
<head>
  <title>My First JS Page</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <script>
    // Your JavaScript code goes here
    console.log("Hello from the internal script!");
  </script>
</body>
</html>
  1. External JavaScript: The best practice is to keep your JavaScript in a separate .js file. This keeps your code organized and reusable. You then link to it from your HTML.

HTML (index.html):


<!DOCTYPE html>
<html>
<head>
  <title>My First JS Page</title>
</head>
<body>
  <h1>Hello, World!</h1>
  <script src="app.js" defer></script>
</body>
</html>

JavaScript (app.js):


console.log("Hello from the external script file!");

Your Best Friend: The Browser Console

The browser console is a tool that lets you "talk" to your webpage. You can use it to log messages, test code snippets, and see errors. To open it, right-click anywhere on a webpage, select Inspect, and then click on the Console tab.

The console.log() command is the most common way to print information to the console. It's essential for debugging and understanding what your code is doing.

Code Snippet: Using console.log Open an HTML file with the code below in your browser, open the console, and see the output!

JavaScript


// in your app.js file
console.log("Starting the application...");

let user = "Alex";
console.log("The current user is:", user);

let calculation = 10 * 5;
console.log("The result is:", calculation); // The result is: 50

The Developer Tools (DevTools) contain the console, but also many other powerful tools like the Elements inspector (for HTML/CSS), the Network tab (to see data requests), and a Debugger, which we'll explore in later lessons.