JavaScript Fundamentals
Learn the essential concepts of JavaScript for web development.
JavaScript is a versatile programming language primarily used for creating interactive elements on websites. If you want to build modern web applications, JavaScript is an essential skill to learn.
Setting Up Your Environment
You don’t need to install anything special to start with JavaScript. All you need is:
- A text editor (like VS Code, Sublime Text, or even Notepad)
- A web browser (Chrome, Firefox, Edge, etc.)
Create an HTML file with a JavaScript section:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Basics</title>
</head>
<body>
<h1>My First JavaScript Page</h1>
<script>
// Your JavaScript code will go here
console.log("Hello, World!");
</script>
</body>
</html>
JavaScript Variables
In JavaScript, you can declare variables using var
, let
, or const
.
// Using var (older way, function-scoped)
var name = "John";
// Using let (block-scoped, can be reassigned)
let age = 25;
age = 26; // This is allowed
// Using const (block-scoped, cannot be reassigned)
const PI = 3.14159;
// PI = 3; // This would cause an error
Data Types
JavaScript has several built-in data types:
// Number
let age = 25;
let price = 19.99;
// String
let firstName = "John";
let message = "Hello!";
// Boolean
let isActive = true;
let isComplete = false;
// Array
let fruits = ["apple", "banana", "orange"];
// Object
let person = {
name: "John",
age: 30,
city: "New York",
};
// Undefined
let undefinedVar;
// Null
let emptyValue = null;
Functions
Functions allow you to reuse code and make your programs modular.
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const multiply = function (a, b) {
return a * b;
};
// Arrow function (ES6+)
const add = (a, b) => a + b;
// Using functions
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(multiply(4, 5)); // Output: 20
console.log(add(2, 3)); // Output: 5
Conditional Statements
Control the flow of your program with conditional statements.
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
// Ternary operator
let age = 19;
let canVote = age >= 18 ? "Yes" : "No";
console.log(`Can vote: ${canVote}`);
Loops
JavaScript provides several ways to loop through data.
// For loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// While loop
let count = 0;
while (count < 3) {
console.log(`Count: ${count}`);
count++;
}
// For...of loop (for arrays)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// For...in loop (for objects)
const person = { name: "John", age: 30, city: "New York" };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
DOM Manipulation
JavaScript’s ability to manipulate the Document Object Model (DOM) is what makes web pages interactive.
// Selecting elements
const heading = document.querySelector("h1");
const paragraphs = document.querySelectorAll("p");
const button = document.getElementById("myButton");
// Modifying elements
heading.textContent = "Updated Heading";
heading.style.color = "blue";
// Creating and adding elements
const newParagraph = document.createElement("p");
newParagraph.textContent = "I was created with JavaScript!";
document.body.appendChild(newParagraph);
// Event handling
button.addEventListener("click", function () {
alert("Button clicked!");
});
B[Test in Browser]
B --> C{Works as expected?}
C -->|No| A
C -->|Yes| D[Refine & Optimize]
D --> E[Deploy]
“ —>
AJAX and Fetching Data
Modern JavaScript uses the Fetch API to request data from servers.
// Basic fetch request
fetch("https://api.example.com/data")
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
// Using async/await (modern approach)
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
console.log("Success:", data);
} catch (error) {
console.error("Error:", error);
}
}
fetchData();
Next Steps
Now that you have learned the basics of JavaScript, here are some suggested next steps:
- Learn about modern JavaScript frameworks (React, Vue, Angular)
- Explore server-side JavaScript with Node.js
- Deepen your understanding of asynchronous programming
- Study JavaScript design patterns and best practices
Conclusion
JavaScript is a powerful language that continues to evolve. The fundamentals covered in this tutorial provide a solid foundation, but there’s much more to learn as you progress in your web development journey.