JavaScript Essentials
Introduction
JavaScript is the programming language of the web, enabling interactive and dynamic content. In this tutorial, you'll learn essential JavaScript concepts and modern best practices.
What you'll learn
- Core JavaScript concepts and syntax
- DOM manipulation and event handling
- Working with functions, arrays, and objects
- Asynchronous programming with Promises
- Modern ES6+ features
JavaScript Basics
Let's start with the fundamental concepts of JavaScript:
// Variables and Data Types
let name = 'John'; // String
const age = 25; // Number
let isStudent = true; // Boolean
let skills = ['HTML', 'CSS']; // Array
let person = { // Object
name: 'John',
age: 25
};
// Template Literals
console.log(`${name} is ${age} years old`);
// Conditional Statements
if (age >= 18) {
console.log('Adult');
} else {
console.log('Minor');
}
// Loops
for (let skill of skills) {
console.log(`Skilled in: ${skill}`);
}
Note: Use const
by default, and let
when you need to reassign values. Avoid using var
.
DOM Manipulation
The Document Object Model (DOM) allows JavaScript to interact with HTML elements:
// Selecting Elements
const title = document.querySelector('h1');
const buttons = document.querySelectorAll('.btn');
// Modifying Elements
title.textContent = 'New Title';
title.classList.add('active');
title.style.color = 'blue';
// Creating Elements
const div = document.createElement('div');
div.className = 'container';
div.innerHTML = `
New Section
Some content here...
`;
document.body.appendChild(div);
Events
Events allow you to respond to user interactions:
// Event Listeners
const button = document.querySelector('#submitBtn');
button.addEventListener('click', function(event) {
event.preventDefault();
console.log('Button clicked!');
});
// Event Delegation
document.querySelector('nav').addEventListener('click', function(event) {
if (event.target.matches('.nav-link')) {
console.log('Navigation item clicked:', event.target.textContent);
}
});
Functions & Scope
Functions are fundamental building blocks in JavaScript:
// Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow Function
const multiply = (a, b) => a * b;
// Higher-Order Functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
// Closures
function counter() {
let count = 0;
return {
increment: () => ++count,
getCount: () => count
};
}
Arrays & Objects
Modern JavaScript provides powerful methods for working with arrays and objects:
// Array Methods
const fruits = ['apple', 'banana', 'orange'];
fruits.push('grape');
fruits.map(fruit => fruit.toUpperCase());
fruits.filter(fruit => fruit.length > 5);
fruits.find(fruit => fruit === 'banana');
// Object Methods
const user = {
name: 'John',
age: 25,
skills: ['JavaScript', 'React']
};
const { name, age } = user; // Destructuring
const newUser = {
...user, // Spread operator
location: 'New York'
};
Asynchronous JavaScript
Handle asynchronous operations with Promises and async/await:
// Promises
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/Await
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
Practice Project
Let's create a simple todo list application:
<!-- HTML Structure -->
<div class="todo-app">
<input type="text" id="todoInput" placeholder="Add new task">
<button id="addTodo">Add</button>
<ul id="todoList"></ul>
</div>
// JavaScript Implementation
class TodoApp {
constructor() {
this.todos = [];
this.input = document.querySelector('#todoInput');
this.list = document.querySelector('#todoList');
this.addButton = document.querySelector('#addTodo');
this.addButton.addEventListener('click', () => this.addTodo());
}
addTodo() {
const text = this.input.value.trim();
if (text) {
this.todos.push({
id: Date.now(),
text,
completed: false
});
this.input.value = '';
this.render();
}
}
toggleTodo(id) {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
this.render();
}
}
render() {
this.list.innerHTML = this.todos
.map(todo => `
<li class="${todo.completed ? 'completed' : ''}">
<input type="checkbox"
${todo.completed ? 'checked' : ''}
onclick="todoApp.toggleTodo(${todo.id})">
<span>${todo.text}</span>
</li>
`).join('');
}
}
const todoApp = new TodoApp();
/* CSS Styling */
.todo-app {
max-width: 400px;
margin: 20px auto;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.completed span {
text-decoration: line-through;
color: #999;
}