JavaScript Fundamentals
A comprehensive guide to understanding the core concepts of JavaScript, the language that powers the modern web.
Start LearningVariables and Data Types
Variables are containers for storing data values. In JavaScript, you can declare variables using var, let, or const.
Variable Declaration
const age = 30; // Number constant
var isStudent = true; // Boolean variable
let hobbies = [“reading”, “coding”]; // Array
let person = { // Object
firstName: “Jane”,
lastName: “Doe”
};
Data Types
JavaScript has dynamic types, meaning the same variable can be used to hold different data types:
Try it yourself:
Change the value and see the data type:
Functions
Functions are one of the fundamental building blocks in JavaScript. A function is a set of statements that performs a task or calculates a value.
Function Declaration
function greet(name) {
return “Hello, “ + name + “!”;
}
// Function expression
const square = function(x) {
return x * x;
};
// Arrow function (ES6)
const multiply = (a, b) => a * b;
Function Demo:
Enter two numbers to calculate their product:
Objects
Objects are collections of key-value pairs. In JavaScript, objects are used to store various keyed collections and more complex entities.
Object Creation and Access
const car = {
brand: “Toyota”,
model: “Camry”,
year: 2020,
start: function() {
console.log(“Engine started”);
}
};
// Accessing properties
console.log(car.brand); // “Toyota”
console.log(car[“model”]); // “Camry”
car.start(); // “Engine started”
Object Demo:
Create a simple person object:
Arrays
Arrays are used to store multiple values in a single variable. They are a special type of object that can hold multiple values at once.
Array Methods
let fruits = [“Apple”, “Banana”, “Orange”];
// Common array methods
fruits.push(“Mango”); // Adds to the end
fruits.pop(); // Removes from the end
fruits.shift(); // Removes from the front
fruits.unshift(“Strawberry”); // Adds to the front
// Iterating over arrays
fruits.forEach(function(fruit) {
console.log(fruit);
});
Array Demo:
Add items to the shopping list:
DOM Manipulation
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document and allows JavaScript to manipulate its content and style.
Common DOM Methods
const element = document.getElementById(“myId”);
const elements = document.querySelectorAll(“.myClass”);
// Changing content
element.textContent = “New text”;
element.innerHTML = “<strong>Bold text</strong>”;
// Changing styles
element.style.color = “red”;
element.classList.add(“new-class”);
DOM Demo:
Change the style of this text:
