What Is JavaScript?
JavaScript is a programming language commonly used to make websites interactive and dynamic. It allows developers to respond to user actions, update webpage content, validate forms, communicate with online services, and build many types of applications.
HTML creates the structure of a webpage, CSS controls its presentation, and JavaScript adds behavior and interaction. Together, these technologies form an important foundation for front-end web development.
JavaScript can make a button display a message when a user clicks it.
What You Will Learn
HTML, CSS, and JavaScript
| Technology | Main Purpose |
|---|---|
| HTML | Creates webpage structure and content. |
| CSS | Controls colors, spacing, layout, and appearance. |
| JavaScript | Adds behavior, logic, and interaction. |
For example, HTML creates a button, CSS styles it, and JavaScript can define what happens when the user clicks it.
Where Does JavaScript Run?
JavaScript runs in modern web browsers such as Chrome, Firefox, Edge, and Safari. Browser JavaScript can work with webpage elements, respond to events, and use browser features that are available to the page.
JavaScript can also run outside a browser through environments such as Node.js. This allows developers to use JavaScript for server-side applications, command-line tools, and other software.
Other environments and frameworks can use JavaScript to help build mobile and desktop applications.
Your First JavaScript Code
One way to add JavaScript to an HTML page is with the <script> element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My First JavaScript Page</title>
</head>
<body>
<h1>Hello World</h1>
<script>
alert("Hello World!");
</script>
</body>
</html>
When the browser runs this page, the alert() function displays a message dialog. Alerts are useful for simple demonstrations, but they can interrupt the user, so they are not ideal for every situation.
Using console.log()
Developers often use console.log() to display information in the browser's developer console while testing or debugging code.
console.log("Hello World!");
let score = 10;
console.log(score);
The console is useful for inspecting values and understanding what a program is doing. On a computer, you can usually open developer tools from the browser menu. Some mobile browsers have more limited developer tools.
JavaScript Variables
Variables hold values that a program can use.
let name = "Ahmed";
let age = 25;
const country = "Nigeria";
console.log(name);
console.log(age);
console.log(country);
letdeclares a variable that can be reassigned.constdeclares a binding that cannot be reassigned.varis an older declaration keyword that beginners may encounter in existing code.
A const variable that holds an object or array can still have its contents changed. The binding itself cannot be reassigned.
const fruits = ["Apple", "Orange"];
fruits.push("Banana");
console.log(fruits);
JavaScript Data Types
JavaScript supports several types of values.
| Type | Example |
|---|---|
| String | "Hello" |
| Number | 25 or 3.14 |
| Boolean | true or false |
| Undefined | A declared variable without an assigned value |
| Null | null, representing an intentional absence of a value |
| Array | ["Apple", "Orange"] |
| Object | { name: "Ahmed" } |
| BigInt | 12345678901234567890n |
| Symbol | Symbol("id") |
JavaScript is dynamically typed, meaning a variable can be assigned values of different types during its lifetime.
let value = 10;
value = "Hello";
console.log(value);
JavaScript Operators
Operators perform calculations, comparisons, and logical operations.
let a = 10;
let b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
Comparison operators include ===, !==, >, <, >=, and <=.
Logical operators include && (AND), || (OR), and ! (NOT).
Use === for strict equality in most comparisons. It compares values without automatically converting between different types.
JavaScript Conditions
Conditions allow a program to make decisions.
let age = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Under 18");
}
You can use else if to check more than one condition.
let score = 75;
if (score >= 80) {
console.log("Excellent");
} else if (score >= 50) {
console.log("Passed");
} else {
console.log("Try again");
}
JavaScript Switch Statement
A switch statement can be useful when comparing one expression with several possible values.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Friday":
console.log("Almost the weekend");
break;
default:
console.log("Another day");
}
The break statement prevents execution from continuing into the next case in this example.
JavaScript Loops
Loops repeat instructions. They are useful for counting, processing lists, and performing repetitive tasks.
For Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
This prints the numbers from 1 to 5.
While Loop
let number = 1;
while (number <= 5) {
console.log(number);
number++;
}
For...of Loop
A for...of loop is useful for iterating over values in an array.
const fruits = ["Apple", "Orange", "Banana"];
for (const fruit of fruits) {
console.log(fruit);
}
while. Otherwise, the program may continue indefinitely.
JavaScript Functions
A function is a reusable block of code that performs a task.
function greet() {
console.log("Hello!");
}
greet();
The function is declared first and then called using its name followed by parentheses.
Functions With Parameters
Parameters allow functions to receive information.
function greet(name) {
console.log("Hello, " + name);
}
greet("Ahmed");
greet("Aisha");
The values supplied when calling the function are called arguments.
Returning Values From Functions
A function can return a value for the rest of the program to use.
function add(a, b) {
return a + b;
}
const result = add(10, 5);
console.log(result); // 15
Arrow Functions
Arrow functions provide a shorter way to write many function expressions.
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 3)); // 12
For a single expression, an arrow function can return the expression's result implicitly.
const square = number => number * number;
console.log(square(5)); // 25
JavaScript Arrays
Arrays store ordered collections of values.
const fruits = [
"Apple",
"Orange",
"Banana"
];
console.log(fruits[0]); // Apple
fruits.push("Mango");
console.log(fruits.length); // 4
Array indexes start at zero. Common array methods include push(), pop(), includes(), map(), and filter().
JavaScript Objects
Objects store related information in properties, usually as key-value pairs.
const person = {
name: "Ahmed",
age: 25,
country: "Nigeria"
};
console.log(person.name);
console.log(person.age);
You can access a property using dot notation or bracket notation.
console.log(person["country"]);
JavaScript and Strings
Strings represent text. You can combine strings, inspect their length, and use methods to work with their contents.
const name = "Ahmed";
console.log(name.length);
console.log(name.toUpperCase());
console.log("Hello, " + name);
Template literals make it convenient to insert values into strings.
const age = 25;
console.log(`I am ${age} years old.`);
JavaScript and HTML
JavaScript can access and change HTML elements through the Document Object Model (DOM).
<h1 id="title">Hello</h1>
<script>
document.getElementById("title").textContent =
"Welcome to TechLearn Hub";
</script>
The script finds the heading by its ID and changes its text.
What Is the DOM?
The Document Object Model represents an HTML document as objects that JavaScript can access and manipulate.
Using the DOM, JavaScript can:
- Change text and HTML attributes.
- Update CSS classes and styles.
- Create and remove elements.
- Respond to user events.
- Read input values.
- Update a page without reloading the entire document in many cases.
JavaScript Events
Events happen when users or the browser interact with a webpage. Examples include clicking a button, typing into an input, submitting a form, or loading a page.
Here is a simple button example using an event listener:
<button id="helloButton">Click Me</button>
<script>
document
.getElementById("helloButton")
.addEventListener("click", function () {
alert("Hello!");
});
</script>
The event listener runs the function when the button is clicked. For larger projects, this approach helps keep behavior separate from HTML markup.
Changing CSS With JavaScript
JavaScript can change the style of an HTML element. Often, adding or removing a CSS class is easier to maintain than changing many individual style properties.
<p id="message">Hello World</p>
<script>
document.getElementById("message").style.color = "blue";
</script>
This example changes the paragraph's text color to blue.
JavaScript Input
JavaScript can read information entered by users.
<input id="name" placeholder="Enter your name">
<button id="submitButton">Submit</button>
<p id="output"></p>
<script>
document
.getElementById("submitButton")
.addEventListener("click", function () {
const name = document.getElementById("name").value.trim();
const output = document.getElementById("output");
if (name === "") {
output.textContent = "Please enter your name.";
} else {
output.textContent = "Hello, " + name;
}
});
</script>
This example checks whether the input is empty and displays a message. It uses textContent to display user-provided text safely as text rather than interpreting it as HTML.
JavaScript and Forms
JavaScript can check form information before a form is submitted. For example, it can check whether a required field has been filled in or whether an email address has a suitable format.
Client-side validation improves the user experience, but it can be bypassed. Applications that use a backend must also validate data on the server and protect sensitive operations there.
JavaScript and Asynchronous Code
Some operations, such as retrieving information from a server, take time. JavaScript supports asynchronous programming so a program can handle these operations without blocking normal page interaction.
Common tools include Promises, async functions, and await.
async function loadMessage() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos/1"
);
if (!response.ok) {
throw new Error("The request failed.");
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Could not load data:", error.message);
}
}
loadMessage();
This example uses a public demonstration API. Real APIs may require a different URL, authentication, permissions, or specific request parameters. The remote service must also be reachable and allow the request from the webpage's origin.
JavaScript and Web APIs
JavaScript can communicate with APIs to retrieve or send information. An API defines how one piece of software communicates with another.
For example, a webpage can request information from a weather service, a sports service, or a backend server.
fetch("https://example.com/api/data")
.then(response => {
if (!response.ok) {
throw new Error("Request failed");
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error("Error:", error.message);
});
The address above is a placeholder. Replace it with a real API endpoint before expecting useful data. Some APIs also require an API key or other authentication.
JavaScript and JSON
JSON stands for JavaScript Object Notation. It is a text format used to exchange structured data between applications.
{
"name": "Ahmed",
"age": 25,
"country": "Nigeria"
}
JavaScript provides JSON.parse() to turn valid JSON text into a JavaScript value and JSON.stringify() to convert supported JavaScript values into JSON text.
const jsonText = '{"name":"Ahmed","age":25}';
const person = JSON.parse(jsonText);
console.log(person.name);
const newJsonText = JSON.stringify(person);
console.log(newJsonText);
JavaScript Error Handling
Programs can encounter errors. JavaScript provides try and catch to handle exceptions from operations that may fail.
try {
const data = JSON.parse('{"name":"Ahmed"}');
console.log(data.name);
} catch (error) {
console.error("Could not read the JSON data.");
}
In this example, the JSON text is valid. If you change it to invalid JSON, the catch block handles the parsing error.
Use browser developer tools and meaningful error messages to help identify problems during development.
JavaScript Modules
Modules help developers split a large program into smaller files. A module can export functions or values that another module imports.
For example, a file named math.js can contain:
export function add(a, b) {
return a + b;
}
Another file can import and use that function:
import { add } from "./math.js";
console.log(add(2, 3));
Browser projects using JavaScript modules generally need to be served through a local or web server rather than opened directly using a file:// URL. The exact setup depends on the development environment.
JavaScript Frameworks and Libraries
Libraries and frameworks provide reusable tools that can make application development more efficient.
- React: A library for building user interfaces.
- Vue: A framework for building user interfaces.
- Angular: A web application framework.
- Svelte: A tool for building user interfaces.
- Node.js: A JavaScript runtime used outside the browser, including for server-side applications.
Beginners should first understand basic JavaScript concepts before relying heavily on frameworks.
JavaScript in Mobile and Desktop Apps
JavaScript is not limited to websites. Some development tools allow developers to use JavaScript and related web technologies when building mobile and desktop applications.
- React Native: Used to build mobile application interfaces with JavaScript and React.
- Electron: Used to build desktop applications with web technologies.
- Progressive Web Apps: Web applications that can offer selected app-like capabilities in supported browsers.
Each approach has its own capabilities, limitations, and platform requirements.
JavaScript for Games
JavaScript can be used to create browser games. Developers can combine JavaScript with HTML and CSS, and use Canvas or WebGL for graphics and interactive experiences.
- Number-guessing game
- Quiz game
- Memory-matching game
- Clicker game
- Simple 2D puzzle game
Common JavaScript Beginner Mistakes
- Forgetting closing brackets, braces, or parentheses.
- Misspelling variable or function names.
- Confusing
=with comparison operators such as===. - Trying to access a DOM element before it exists.
- Ignoring error messages in the browser console.
- Copying code without understanding what it does.
- Putting private API keys in frontend code.
- Trying to learn too many frameworks before learning the basics.
- Not practising with small projects.
How to Learn JavaScript
A beginner can follow this learning path:
- Learn how to include JavaScript in an HTML page.
- Study variables and data types.
- Practise operators and expressions.
- Learn conditions and decision-making.
- Practise loops.
- Learn functions and return values.
- Study arrays and objects.
- Learn DOM manipulation.
- Practise event handling.
- Learn JSON and APIs.
- Understand asynchronous code and error handling.
- Build small projects before moving to larger applications.
Beginner JavaScript Projects
These projects let you practise several concepts together:
- Digital clock: Practise dates and updating webpage content.
- Calculator: Practise functions, operators, and input handling.
- Number-guessing game: Practise conditions and random numbers.
- Quiz game: Practise arrays, objects, and scoring.
- To-do list: Practise DOM manipulation and events.
- Counter app: Practise variables and button events.
- Weather application: Practise APIs and asynchronous code.
- Notes app: Practise forms and, optionally, browser storage.
- Random quote generator: Practise arrays and selecting values.
- Browser game: Practise game logic, keyboard input, and animation.
Start with one small project, get it working, and then add improvements gradually.
Frequently Asked Questions
Is JavaScript difficult to learn?
JavaScript has many concepts, but beginners can learn it gradually by starting with simple examples and practising regularly.
Do I need HTML and CSS before JavaScript?
Basic HTML and CSS knowledge is helpful because JavaScript often interacts with webpages created using those technologies. You can learn all three together step by step.
Can JavaScript be used without HTML?
Yes. JavaScript can run outside the browser in environments such as Node.js, where it can be used for server-side applications and command-line tools.
Can JavaScript be used to create games?
Yes. JavaScript can be used for many types of browser games, including 2D games and some 3D experiences.
Can JavaScript be used to create mobile apps?
Yes. Technologies such as React Native can use JavaScript to build mobile applications.
What is the difference between Java and JavaScript?
Java and JavaScript are different programming languages. They have different language designs, runtimes, ecosystems, and common uses.
What should I learn after JavaScript?
Depending on your goals, you can study advanced JavaScript, TypeScript, frontend frameworks, backend development, databases, APIs, or mobile application development.
Can JavaScript access private information on a user's device?
Webpage JavaScript runs under browser security restrictions. Access to device features and data depends on browser permissions, APIs, and the user's actions. Websites should request only the access they need.
Conclusion
JavaScript is an important programming language used to add interaction and functionality to websites and applications. It can also be used outside the browser with suitable tools and runtimes.
Start with variables, data types, conditions, functions, and loops. Then move to arrays, objects, DOM manipulation, events, APIs, and small practical projects.
Create a small HTML page with a button. Use JavaScript to respond to a click, then improve the page by reading user input and displaying a result.
Further Learning Resources
These resources provide additional explanations and documentation:
- MDN Web Docs: JavaScript — language guides and reference material.
- MDN Learn Web Development — structured learning material for web development.
- The Modern JavaScript Tutorial — explanations and practical examples.
This guide is educational material for beginners. Browser features, APIs, and development tools may change, so consult current documentation when building real applications.