LearnContact
Lesson 135 min read

Introduction to JavaScript

Learn what JavaScript is, why it was created, how it works with HTML and CSS, where JavaScript runs, and how it powers the modern web.

Introduction

Modern websites are not only static documents that display text and images. Users can click buttons, submit forms, search for products, play videos, open menus, receive notifications, update content without refreshing the page, and interact with complete applications directly inside a web browser.

JavaScript is the programming language that makes these interactions possible. It adds logic, behavior, calculations, decision-making, and dynamic functionality to websites and web applications.

HTML creates the structure of a webpage. CSS controls its appearance. JavaScript controls what the webpage can do.

The Three Core Technologies of the Web
  • HTML creates the structure and content.
  • CSS controls the design and layout.
  • JavaScript adds logic, behavior, and interactivity.

What is JavaScript?

JavaScript is a high-level, dynamic programming language primarily used to create interactive and dynamic web pages and applications.

It allows developers to write instructions that a computer can execute. These instructions can perform calculations, make decisions, repeat operations, store information, respond to user actions, modify webpage content, and communicate with servers.

JavaScript was originally created to run inside web browsers. Today, JavaScript can also run on servers, mobile devices, desktop computers, smart devices, and many other environments.

Programming Language

JavaScript allows developers to write logic, calculations, conditions, loops, functions, and complete application workflows.

Web Technology

JavaScript is one of the three core technologies used to build modern websites and web applications.

Interactive

JavaScript allows webpages to respond immediately to clicks, typing, scrolling, form submissions, and other user actions.

Dynamic

JavaScript can change webpage content, styles, and elements while the page is running.

Simple Definition
  • HTML tells the browser what to display.
  • CSS tells the browser how it should look.
  • JavaScript tells the browser what should happen.

Why Do We Need JavaScript?

Without JavaScript, most webpages would behave like static documents. Users could read content and follow links, but advanced interactions and application behavior would be extremely limited.

JavaScript allows a webpage to react to users and perform actions while the application is running.

Respond to User Actions

Execute code when users click buttons, type text, move the mouse, scroll the page, or submit forms.

Change Content Dynamically

Update text, images, lists, tables, and other webpage content without reloading the entire page.

Perform Calculations

Calculate totals, discounts, taxes, scores, percentages, dates, and other values.

Validate User Input

Check whether form data is correct before sending it to a server.

Communicate with Servers

Request and send data using APIs without requiring a complete page reload.

Build Applications

Create games, dashboards, editors, chat systems, maps, media players, and complete web applications.

Why Learn JavaScript?

JavaScript is one of the most important technologies in modern software development. Almost every interactive website uses JavaScript, and it is a fundamental requirement for becoming a Frontend Developer or Full Stack Developer.

Learning JavaScript also provides the foundation required for modern frontend libraries and frameworks. These technologies make application development easier, but they are built on JavaScript concepts.

Web Development

JavaScript is the language of the web and is used by millions of websites to create interactive experiences.

Full Stack Development

Use JavaScript for frontend development in the browser and backend development with Node.js.

Mobile Applications

Build cross-platform mobile applications using technologies such as React Native and Ionic.

Desktop Applications

Create cross-platform desktop applications using JavaScript-based technologies.

Modern Frameworks

Strong JavaScript fundamentals are required before learning React, Angular, Vue, Next.js, and other modern technologies.

Career Opportunities

JavaScript skills are required for Frontend, Backend, Full Stack, Mobile, and Web Application development roles.

Real-World Analogy

Imagine a modern car. The physical body and internal structure represent HTML. The paint, shape, interior design, and visual appearance represent CSS. The engine, controls, sensors, and electronic systems represent JavaScript.

HTML — Structure

The body, doors, seats, steering wheel, and physical parts of the car.

CSS — Appearance

The color, design, interior style, wheel appearance, and visual presentation.

JavaScript — Behavior

The engine, controls, sensors, automatic systems, and functionality that make the car operate.

Web Development Analogy
Modern Car              Webpage
──────────              ───────
Car Structure           HTML
Car Design              CSS
Engine                  JavaScript
Controls                JavaScript Events
Sensors                 JavaScript Logic
Dashboard Updates       Dynamic JavaScript

HTML, CSS & JavaScript

HTML, CSS, and JavaScript work together to create a complete webpage. Each technology has a different responsibility.

HTML

Creates headings, paragraphs, images, links, buttons, forms, tables, and the overall webpage structure.

CSS

Controls colors, fonts, spacing, borders, layouts, responsive design, transitions, and animations.

JavaScript

Controls calculations, conditions, user interactions, dynamic content, events, data processing, and application logic.

HTML
<button id="welcomeButton">Click Me</button>

<p id="message"></p>
CSS
button {
    background-color: #f7df1e;
    color: #111;
    padding: 12px 24px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}
JavaScript
const button = document.getElementById('welcomeButton');
const message = document.getElementById('message');

button.addEventListener('click', function () {
    message.textContent = 'Welcome to JavaScript!';
});
Output

What Can JavaScript Do?

JavaScript can perform simple tasks such as displaying a message and complex tasks such as managing complete applications.

Change Text

JavaScript can dynamically update headings, paragraphs, labels, and other text content.

Change Images

JavaScript can change image sources, create image galleries, and build interactive sliders.

Change Styles

JavaScript can dynamically change colors, sizes, visibility, positions, and CSS classes.

Validate Forms

JavaScript can check names, email addresses, passwords, numbers, and other form values.

Process Data

JavaScript can sort, filter, calculate, transform, and display application data.

Fetch Remote Data

JavaScript can communicate with APIs to retrieve weather, products, users, messages, and other information.

Create Animations

JavaScript can control complex interactive animations and visual effects.

Build Games

JavaScript can create browser-based 2D and 3D games.

Where Does JavaScript Run?

JavaScript needs an execution environment. An execution environment provides the system required to read and execute JavaScript code.

The two most common environments are web browsers and server-side JavaScript runtimes.

Web Browser

JavaScript runs inside modern web browsers and controls webpage behavior and interaction.

Server

JavaScript can run on servers using runtime environments such as Node.js.

Mobile Applications

JavaScript can be used to build mobile applications with technologies such as React Native and Ionic.

Desktop Applications

JavaScript can be used to create cross-platform desktop software.

Client-Side JavaScript

Client-side JavaScript runs inside the user’s web browser. The browser downloads the JavaScript code along with the webpage and executes it on the user’s device.

Client-side JavaScript is commonly used for webpage interactions, form validation, DOM manipulation, animations, event handling, and API communication.

Client-Side Flow
User Opens Website
        ↓
Browser Downloads HTML
        ↓
Browser Downloads CSS
        ↓
Browser Downloads JavaScript
        ↓
JavaScript Engine Executes Code
        ↓
User Interacts with Webpage
        ↓
JavaScript Responds to Actions

Server-Side JavaScript

JavaScript can also run outside a web browser. Node.js is a popular JavaScript runtime that allows developers to execute JavaScript on servers and computers.

Server-side JavaScript can process requests, communicate with databases, authenticate users, manage files, create APIs, and perform backend application logic.

Server-Side Flow
Browser
   ↓ Request
Server
   ↓
JavaScript Application
   ↓
Database / API / Files
   ↓
Response
   ↓
Browser

JavaScript in the Browser

Modern web browsers contain a JavaScript engine. The engine reads JavaScript source code, processes it, and executes the instructions.

Because the JavaScript engine is already included in the browser, you do not need to install JavaScript separately to begin writing browser-based programs.

example.js
// Your first JavaScript code
console.log("Hello, World!");

// Variables
let name = "JavaScript";
const year = 1995;

// Function
function greet(user) {
    return `Hello, ${user}!`;
}

console.log(greet(name));
Console Output

This example introduces several JavaScript concepts. The console.log() method displays output, variables store values, constants store values that should not be reassigned, and functions organize reusable logic. Each of these concepts will be covered in detail in later lessons.

JavaScript in a Webpage

JavaScript can be added directly inside an HTML document using the <script> element or stored in a separate JavaScript file.

Internal JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Example</title>
</head>
<body>

    <h1>My First JavaScript Page</h1>

    <script>
        console.log('JavaScript is running!');
    </script>

</body>
</html>
Console Output

For larger applications, JavaScript is normally stored in a separate file and connected to the HTML document.

HTML File
<script src="script.js"></script>
script.js
console.log('External JavaScript file loaded!');
Console Output

Example 1: First JavaScript Program

The console.log() method is commonly used to display information in the browser console. It is especially useful while learning and debugging JavaScript.

JavaScript
console.log('Hello, JavaScript!');
Output
Open the Browser Console
  • Open the webpage in your browser.
  • Press F12 or open Developer Tools.
  • Select the Console tab.
  • The output of console.log() will appear there.

Example 2: Changing Webpage Content

JavaScript can access an HTML element and change its content while the webpage is running.

HTML & JavaScript
<h2 id="title">Original Title</h2>

<button onclick="changeTitle()">
    Change Title
</button>

<script>
    function changeTitle() {
        document.getElementById('title').textContent =
            'Title Changed by JavaScript!';
    }
</script>
Before Clicking
After Clicking the Button

Example 3: Performing Calculations

JavaScript can store values, perform calculations, and display the result.

JavaScript
const price = 500;
const quantity = 3;

const total = price * quantity;

console.log('Total Price:', total);
Output

JavaScript stores the price and quantity, multiplies them, stores the result in another constant, and displays the final value.

How JavaScript Executes

When JavaScript code is loaded, the JavaScript engine reads and executes the instructions. By default, statements are generally executed from top to bottom.

Execution Order
console.log('First');

console.log('Second');

console.log('Third');
Output
Basic Execution Flow
JavaScript Source Code
        ↓
JavaScript Engine
        ↓
Code Processing
        ↓
Instructions Execute
        ↓
Output / Application Behavior
Coming in Future Lessons
  • Lesson 3 explains the JavaScript Engine in detail.
  • Lesson 4 explains how JavaScript works internally.
  • Later lessons explain execution order, scope, hoisting, events, and errors.

Features of JavaScript

Beginner-Friendly

JavaScript has a relatively simple starting syntax and can run directly inside a web browser.

Fast Execution

Modern JavaScript engines optimize code and execute applications efficiently.

Dynamic

JavaScript can work with values and application structures that change while the program is running.

Event-Driven

JavaScript can respond to clicks, keyboard input, form submissions, timers, and many other events.

Cross-Platform

JavaScript works across operating systems and modern web browsers.

Versatile

JavaScript can be used for frontend, backend, mobile, desktop, games, automation, and many other applications.

Real-World Applications

JavaScript is used in almost every category of modern web application.

E-Commerce

Shopping carts, product filters, search, checkout validation, and dynamic product pages.

Chat Applications

Real-time messages, typing indicators, notifications, and online status updates.

Dashboards

Interactive charts, reports, filters, live statistics, and data visualization.

Streaming Platforms

Video controls, recommendations, search, playlists, and interactive interfaces.

Maps

Interactive locations, markers, routes, zooming, and live geographic information.

Games

Browser games, animations, keyboard controls, scoring systems, and game logic.

Advantages of JavaScript

  • Runs directly inside modern web browsers.
  • Does not require complex setup for basic learning.
  • Creates interactive and dynamic webpages.
  • Works across different operating systems.
  • Can be used for both frontend and backend development.
  • Has a very large developer community.
  • Provides a massive ecosystem of libraries and frameworks.
  • Supports web, mobile, desktop, server, and game development.
  • Works naturally with HTML and CSS.
  • Is one of the most widely used programming languages.

Common Beginner Mistakes

Avoid These Mistakes
  • Thinking JavaScript and Java are the same language.
  • Learning frameworks before understanding JavaScript fundamentals.
  • Copying code without understanding how it works.
  • Ignoring browser console errors.
  • Trying to memorize every method instead of understanding concepts.
  • Skipping practice after reading a lesson.
  • Writing large programs before mastering basic concepts.

Best Practices

  • Write every code example yourself.
  • Use meaningful variable and function names.
  • Practice with small programs after each concept.
  • Read browser console errors carefully.
  • Use consistent code formatting and indentation.
  • Understand the logic before trying to memorize syntax.
  • Modify examples and observe how the output changes.
  • Learn JavaScript fundamentals before moving to frameworks.

Frequently Asked Questions

Is JavaScript the same as Java?

No. JavaScript and Java are completely different programming languages. Their names are similar, but they have different syntax, execution models, and use cases.

Do I need HTML and CSS before learning JavaScript?

Basic HTML and CSS knowledge is strongly recommended for frontend JavaScript because JavaScript frequently interacts with webpage elements and styles.

Can JavaScript run without a browser?

Yes. JavaScript can run outside browsers using runtime environments such as Node.js.

Is JavaScript only used for websites?

No. JavaScript is also used for backend servers, mobile applications, desktop applications, browser extensions, games, automation tools, and many other types of software.

Is JavaScript difficult for beginners?

JavaScript is beginner-friendly at the basic level. Advanced concepts require practice, but learning topics sequentially makes the process much easier.

Do I need to install JavaScript?

No installation is required for basic browser-based JavaScript. Modern web browsers already contain a JavaScript engine.

What should I learn after Core JavaScript?

After mastering Core JavaScript, you can continue with advanced JavaScript, TypeScript, DOM projects, Node.js, or frontend technologies such as React, Angular, Vue, and Next.js.

Key Takeaways

  • JavaScript is a programming language used to add logic and interactivity to applications.
  • HTML creates structure, CSS creates design, and JavaScript creates behavior.
  • JavaScript can respond to user actions and dynamically update webpages.
  • JavaScript originally ran inside browsers but can now run in many environments.
  • Client-side JavaScript runs in the browser.
  • Server-side JavaScript can run using environments such as Node.js.
  • JavaScript can manipulate webpage content, process data, validate forms, and communicate with APIs.
  • Modern applications use JavaScript across frontend, backend, mobile, desktop, and other platforms.
  • The browser console is an important tool for learning and debugging JavaScript.
  • Strong JavaScript fundamentals are essential before learning modern JavaScript frameworks.

Summary

JavaScript is the programming language that adds behavior, logic, and interactivity to modern websites and applications. It works together with HTML and CSS to create complete web experiences.

JavaScript can respond to user actions, perform calculations, modify webpage content, validate forms, process data, communicate with servers, and build complete applications.

In this lesson, you learned what JavaScript is, why it is needed, why it is worth learning, how it works with HTML and CSS, where JavaScript can run, and how basic JavaScript programs produce output.

Lesson 1 Completed
  • You understand the purpose of JavaScript.
  • You know the roles of HTML, CSS, and JavaScript.
  • You understand client-side and server-side JavaScript.
  • You have seen how JavaScript is added to a webpage.
  • You have written your first JavaScript programs.
  • You are ready to learn the history and evolution of JavaScript.
Next Lesson →

JavaScript History