What is JavaScript?
JavaScript is a powerful, high-level programming language that is primarily used to make web pages interactive and dynamic. It is one of the core technologies of the web, alongside HTML and CSS.
Definition:
JavaScript (often abbreviated as JS) is a scripting language that runs in the browser and allows you to create:
- Interactive websites (forms, buttons, sliders)
- Dynamic content updates (without refreshing the page)
- Games, animations, and real-time features (like chat)
- Backend applications (via Node.js)
Key Features of JavaScript
- Client-side scripting: Runs directly in the user’s browser.
- Dynamically typed: You don’t need to specify variable types.
- Event-driven: Executes code in response to user actions.
- Interpreted language: No compilation required.
- Object-oriented and functional: Supports both paradigms.
- Cross-platform: Works in all modern browsers and many environments (like Node.js).
Quick History:
- Created in 1995 by Brendan Eich at Netscape in just 10 days.
- Originally called Mocha, then LiveScript, and finally JavaScript.
- Despite the name, JavaScript is not related to Java.
- Has evolved significantly—modern JavaScript (ES6+) supports classes, modules, async/await, and more.
Why is JavaScript Important?
- Enables interactivity: Forms, games, modals, tabs, etc.
- Drives modern front-end frameworks like React, Vue, Angular.
- Used in full-stack development (Node.js on the server).
- Largest developer community and an ever-growing ecosystem.
- Powers popular tools, sites, and apps (e.g., Gmail, Facebook, Netflix).
What Can JavaScript Do?
- Validate user input before form submission
- Load new data using AJAX or Fetch API
- Create mobile apps using React Native or Ionic
- Control the browser (window, history, alerts)
- Animate elements and manipulate the DOM
JavaScript vs. HTML/CSS
Feature | HTML | CSS | JavaScript |
---|---|---|---|
Structure | YES | NO | NO |
Styling | NO | YES | NO |
Interactivity | NO | NO | YES |
Summary:
JavaScript is the engine behind interactivity on the web. From simple alerts to full-fledged applications, it’s an essential tool for web developers. If HTML is the structure and CSS is the style, JavaScript is the brain of the webpage.
History and Role of Java Script in web development
History of Java Script
Here is the history of Java Script (JS) since 1995 to present day.
1995 – Birth of JavaScript
Brendan Eich created JavaScript in just 10 days at Netscape. It was originally named Mocha, then LiveScript, and finally JavaScript (to ride on Java’s popularity, although the two are unrelated).
Late 1990s – Early Use and Standardization
Microsoft introduced its own version, JScript, for Internet Explorer. To unify browser behavior, JavaScript was standardized as ECMAScript (ECMA-262) by ECMA International in 1997.
2000s – DOM Manipulation Era
JavaScript began being used more heavily to interact with HTML documents via the Document Object Model (DOM), enabling dynamic effects and simple form validation.
2005 – AJAX Revolution
The rise of AJAX (Asynchronous JavaScript and XML) transformed web applications by enabling dynamic, real-time data loading without page refresh. This led to web apps like Gmail, Google Maps, and Facebook.
2009 – Node.js Launch
JavaScript left the browser with the release of Node.js, allowing JS to run on servers and making it a full-stack language.
2015 – Modern JavaScript (ES6/ES2015)
ES6 introduced significant updates like let, const, arrow functions, classes, modules, template literals, and promises—bringing JS up to speed with other modern languages.
Present Day
JavaScript is everywhere—from front-end to back-end, mobile to desktop apps, IoT devices, and even machine learning.
JavaScript’s Role in Web Development
JavaScript is a core component of web development, working alongside HTML and CSS to build modern, responsive, and interactive web applications.
- HTML – Provides the structure
- CSS – Provides the styling
- JavaScript – Brings interactivity and logic
JavaScript in Action:
Area | Role of JavaScript |
---|---|
User Interaction | Click events, modals, dropdowns, validation |
Dynamic Content | Real-time updates, AJAX calls, content generation |
Animation & UX | Smooth transitions, canvas drawing, sliders |
APIs & Backends | REST API consumption, data processing with Node.js |
Frameworks/Tools | React, Angular, Vue, Svelte, Express, Next.js, etc. |
Mobile/Desktop | Cross-platform apps using React Native, Electron |
Why JavaScript Remains Crucial
- Runs in every browser
- Huge ecosystem and community
- Enables full-stack development
- Highly demanded by employers
- Continuously evolving
Summary:
JavaScript has evolved from a simple scripting language to a cornerstone of modern web development, powering nearly every interactive element on the internet today. Its history reflects the web’s growth—from static pages to rich, dynamic applications.
How browsers execute JavaScript
When a browser loads a webpage, it follows a specific process to parse and execute JavaScript, enabling dynamic behavior and interactivity on the page. Here’s how it works step-by-step:
Browser execute JavaScript types.
1. HTML Parsing Begins
- The browser starts reading the HTML document from top to bottom.
- It builds a DOM (Document Object Model) to represent the structure of the page.
- When it encounters a <script> tag (either inline or linked), it pauses HTML parsing.
2. JavaScript Engine Takes Control
- The browser passes the script to its JavaScript engine:
- Chrome → V8
- Firefox → SpiderMonkey
- Safari → JavaScriptCore
The engine parses the code into an Abstract Syntax Tree (AST), compiles it into bytecode or machine code (via JIT), and then executes it.
3. Execution Context & Call Stack
- The engine creates a Global Execution Context and adds it to the Call Stack.
- Each function call creates a new context and gets stacked.
- Once the function finishes, it’s popped off the stack.
- This is how JavaScript runs synchronously, one task at a time.
4. Handling Async with Event Loop
- When async tasks like setTimeout(), fetch(), or event listeners occur:
- They go to Web APIs (provided by the browser).
- After completion, the callback is queued in the Callback Queue.
- The Event Loop checks the Call Stack, and if it’s empty, pushes callbacks from the queue into the stack for execution.
- This allows JavaScript to handle asynchronous tasks without blocking.
5. DOM Manipulation & Re-rendering
- JavaScript can update HTML elements via the DOM (document.getElementById(), etc.).
- When changes happen, the browser re-renders the affected parts of the page.
In Summary:
The browser parses HTML, delegates JavaScript to its engine for parsing and execution, uses the call stack and event loop to manage sync and async operations, and updates the DOM to reflect any changes.
Writing and running JS in browser (Console & <script>)
1. Using the Browser Console
This is great for quick testing, debugging, or learning JavaScript interactively.
How to Open the Console
- Chrome: Right-click > Inspect > go to the Console tab.
- Firefox: Ctrl + Shift + K or Cmd + Option + K
- Edge: F12 or Ctrl + Shift + I > Console
- Safari: Enable “Show Develop Menu” in preferences, then Cmd + Option + C
Writing JavaScript in the Console
Just type code and press Enter. Multiline code can be written using Shift + Enter.
// Simple log
console.log(“Hello from console!”);
// Variables and functions
let name = “Alice”;
function greet(user) {
return `Hello, ${user}`;
}
console.log(greet(name));
// DOM manipulation
document.body.style.backgroundColor = “lightblue”;
Tips for the Console
- Use $_ to access the last result.
- Arrow keys to scroll through history.
- console.dir(obj) to explore object properties.
2. Using <script> in HTML
This is used for actual projects or static HTML + JS pages.
Inline JavaScript
Embed JavaScript directly inside your HTML file using a <script> tag.
<!DOCTYPE html>
<html>
<head>
<title>Inline JS</title>
</head>
<body>
<h1>Hello World</h1>
<script>
document.querySelector(‘h1’).style.color = “green”;
console.log(“Page loaded!”);
</script>
</body>
</html>
- This code runs as soon as the browser reaches the script tag.
External JavaScript File
You can also link a .js file with the src attribute.
<!DOCTYPE html>
<html>
<head>
<title>External JS</title>
<script src=”script.js” defer></script>
</head>
<body>
<h1>Hello External Script</h1>
</body>
</html>
// script.js
document.querySelector(‘h1’).style.color = “blue”;
console.log(“External script running!”);
Why Use defer?
- It waits for HTML to load before running JS.
- Keeps the DOM accessible when the script runs.
Common Pitfalls:
Problem | Why It Happens | Fix |
---|---|---|
null on document.querySelector | Script runs before DOM loads | Use defer or DOMContentLoaded |
Uncaught ReferenceError | Variable or function not defined | Check order of script tags |
JS not working | Wrong file path or MIME type | Ensure script path is correct & served properly |
Bonus: Using
To ensure your script runs only after HTML is loaded:
document.addEventListener(“DOMContentLoaded”, function () {
document.body.style.background = “beige”;
});
Linking external JS files
1. Basic Syntax for Linking JS
Use the <script> tag with the src attribute inside your HTML file:
<script src=”path/to/your-script.js”></script>
This tells the browser to fetch and run the code inside the external JS file.
2. File Structure Example
Let’s say your project is structured like this:
project-folder/
│
├── index.html
└── js/
└── app.js
To link app.js in index.html:
<script src=”js/app.js”></script>
This path is relative to the location of the HTML file.
3. Where to Place the <script> Tag
Option 1: At the End of <body>
This is the classic and safe approach.
<body>
<!– page content –>
<script src=”js/app.js”></script>
</body>
- Ensures the HTML is fully loaded before JS runs.
- No need to wait or wrap your code in DOMContentLoaded.
Option 2: In the <head> with defer
<head>
<script src=”js/app.js” defer></script>
</head>
defer tells the browser:
- Download immediately (non-blocking),
- but run after HTML is parsed.
- Keeps scripts and markup cleanly separated.
Avoid async for scripts that interact with the DOM — it can run before the DOM is ready.
4. Common Issues
Issue | Cause | Fix |
---|---|---|
Uncaught ReferenceError | Script ran before the HTML loaded | Move script to end of body or add defer |
Script doesn’t load | Wrong path | Double-check file structure and file names |
JS file not found (404) | Mistyped path | Use browser dev tools (Network tab) to debug |
5. External JS Example
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src=”app.js” defer></script>
</head>
<body>
<h1>Welcome</h1>
<button id=”btn”>Click Me</button>
</body>
</html>
JavaScript (app.js):
document.getElementById(“btn”).addEventListener(“click”, function () {
alert(“Button clicked!”);
});
- Clicking the button will trigger the alert.
6. Linking Multiple JS Files
If you need to load several JS files:
<script src=”lib.js” defer></script>
<script src=”utils.js” defer></script>
<script src=”main.js” defer></script>
- Order matters if the scripts depend on each other.
- With defer, they execute in order.