How to Run JavaScript

Client-Side JavaScript and Server-Side JavaScript

JavaScript can run in two different environments:

  1. Client Side (Browser)
  2. Server Side (Server / Node.js)

The way you write and run JavaScript depends on where it is executed.


Client-Side JavaScript (Browser JavaScript)

Client-side JavaScript runs inside the user’s web browser.

Need for Client-Side JavaScript

  1. Web Browser
    • Chrome, Edge, Firefox, Safari
      (All have built-in JavaScript engines)
  2. Text Editor
    • Notepad, VS Code, Sublime, Atom, etc.

No installation required

How Client-Side JavaScript Runs

Client-side JavaScript is executed by the browser’s JavaScript engine when the browser reads an HTML file.

Client-Side JavaScript Runs Using:

  • HTML file
  • <script> tag
  • Browser

Client-Side JavaScript Using <script> Tag

JavaScript Inside HTML

  1. Create a file: index.html
  2. Write code:
<!DOCTYPE html>
<html>
<head>
    <title>Client Side JS</title>
</head>
<body>
<h1>Hello JavaScript</h1>
<script>
    alert("Client-side JavaScript running!");
    console.log("Running inside browser");
</script>
</body>
</html>
  • Browser loads HTML
  • Browser sees <script>
  • Browser executes JavaScript using JS engine

JavaScript in <head>

<head>
    <script>
        console.log("JS in head");
    </script>
</head>
  • Runs before page content loads
  • Can slow page rendering if script is heavy

JavaScript in <body>

<body>
    <h1>JS in Body</h1>
    <script>
        console.log("JS after HTML load");
    </script>
</body>

Why this method is better than others:

  • HTML loads first
  • JS runs after page is ready
  • Fewer errors

External JavaScript (Client Side)

When JavaScript code becomes long, it is best to place it in a separate file.

  • JavaScript file extension: .js
  • Improves readability
  • Easy maintenance
  • Used in professional projects

Steps to Use External JavaScript

  1. Create an HTML file: index.html
  2. Create a JavaScript file: script.js
  3. Place both files in the same folder

index.html

<!DOCTYPE html>
<html>
<head>
    <title>External JavaScript Example</title>
</head>
<body>
<h1>External JavaScript File</h1>
<script src="script.js"></script>
</body>
</html>

script.js

alert("Hello from external JavaScript file!");

console.log("External JavaScript file linked successfully!");
  • src=”script.js” connects the JS file to HTML
  • Browser downloads and executes the JS file

What Client-Side JavaScript Can Do

  • Handle button clicks
  • Validate forms
  • Change UI
  • Fetch data from server
  • Interact with users

It Cannot do these:

  • Access databases directly
  • Access server files

📣 Follow us for more updates:

Follow on LinkedIn Join WhatsApp Channel
Scroll to Top