JavaScript Programming
This guide is designed to help you build a foundational understanding of JavaScript. It covers basic syntax, core concepts, and practical examples to get you started with writing and running your own code.
1. Introduction to JavaScript
JavaScript (JS) is a lightweight, interpreted programming language. While it is best known as the scripting language for web pages, it is also widely used in non-browser environments, such as Node.js for backend development.
JavaScript allows you to add interactivity, handle data, and build complex features on websites, turning static HTML/CSS pages into dynamic applications.
2. Setting Up Your Environment
You do not need a complex setup to start writing JavaScript. You can run code directly in your web browser.
Option A: The Browser Console (Quickest)
1. Open your web browser (e.g., Chrome, Firefox, Edge).
2. Right-click anywhere on a page and select Inspect (or press F12).
3. Click on the Console tab.
4. Type console.log("Hello, World!"); and press Enter.
Option B: HTML and a Text Editor (Recommended)
To write reusable code, use a text editor like VS Code.
1. Create a folder on your computer.
2. Inside the folder, create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Practice</title>
</head>
<body>
<h1>Open the console to see the output.</h1>
<script src="script.js"></script>
</body>
</html>
3. Create a script.js file in the same folder:
console.log("JavaScript is successfully linked!");
4. Open index.html in your browser and check the developer console to see the output.
3. Variables and Data Types
Variables are containers used to store data values. In modern JavaScript, we declare variables using let and const.
Declaring Variables
-
let: Used for variables whose values are expected to change. -
const: Used for variables whose values should remain constant (cannot be reassigned). - Avoid
var, as it is an older keyword with scoping behaviors that can lead to bugs.
let age = 25; // Value can change
age = 26; // Allowed
const birthYear = 1998; // Value cannot change
// birthYear = 1999; // This will throw an error
Data Types
JavaScript variables can hold different types of data:
// 1. Number (both integers and decimals)
let score = 95;
let pi = 3.14159;
// 2. String (text surrounded by single, double, or backticks)
let name = "Alex";
let greeting = `Hello, ${name}`; // Template literal (embeds variables)
// 3. Boolean (true or false)
let isOnline = true;
let hasPaid = false;
// 4. Undefined (a variable that has been declared but not assigned a value)
let response;
console.log(response); // Output: undefined
// 5. Null (explicitly represents the absence of a value)
let emptyValue = null;
4. Operators
Operators are used to perform operations on variables and values.
Arithmetic Operators
let x = 10;
let y = 3;
console.log(x + y); // Addition: 13
console.log(x - y); // Subtraction: 7
console.log(x * y); // Multiplication: 30
console.log(x / y); // Division: 3.3333...
console.log(x % y); // Remainder (Modulo): 1
console.log(x ** y); // Exponentiation (10 to the power of 3): 1000
Comparison Operators
These compare values and return a boolean (true or false).
let a = 10;
let b = "10";
console.log(a == b); // True: compares value only (performs type conversion)
console.log(a === b); // False: compares value and type (strict comparison - recommended)
console.log(a !== b); // True: strict inequality
console.log(a > 5); // True: greater than
Logical Operators
Used to determine the logic between variables or values.
let hasDriverLicense = true;
let isSober = false;
// AND (&&): returns true if both conditions are true
console.log(hasDriverLicense && isSober); // false
// OR (||): returns true if at least one condition is true
console.log(hasDriverLicense || isSober); // true
// NOT (!): reverses the boolean value
console.log(!hasDriverLicense); // false
5. Control Flow
Control flow allows your program to make decisions and repeat actions.
Conditionals (if, else if, else)
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
Loops
Loops allow you to run a block of code multiple times.
1. for Loop (Used when you know how many times you want to loop)
// Loop runs 5 times, incrementing 'i' from 0 to 4
for (let i = 0; i < 5; i++) {
console.log("Iteration number: " + i);
}
2. while Loop (Runs as long as a specified condition is true)
let count = 0;
while (count < 3) {
console.log("Count is: " + count);
count++;
}
6. Functions
A function is a reusable block of code designed to perform a particular task.
Function Declaration
function greet(user) {
return "Hello, " + user + "!";
}
// Calling the function
let message = greet("Sarah");
console.log(message); // Output: Hello, Sarah!
Function Expression
You can also assign functions to variables.
const add = function(num1, num2) {
return num1 + num2;
};
console.log(add(5, 7)); // Output: 12
Arrow Functions (Modern ES6+ Syntax)
Arrow functions provide a shorter syntax for writing functions.
const multiply = (a, b) => a * b;
console.log(multiply(4, 3)); // Output: 12
7. Arrays and Objects
These data structures allow you to store collections of data.
Arrays (Ordered Lists)
Arrays are list-like objects used to store multiple values in a single variable.
let fruits = ["Apple", "Banana", "Orange"];
// Accessing items by index (starts at 0)
console.log(fruits[0]); // Apple
// Modifying an item
fruits[1] = "Mango";
// Adding items to the end
fruits.push("Grape");
// Checking the array length
console.log(fruits.length); // 4
Objects (Key-Value Pairs)
Objects allow you to store collections of data represented as keys (properties) and values.
let user = {
firstName: "John",
lastName: "Doe",
age: 30,
isSubscribed: true
};
// Accessing properties (Dot notation)
console.log(user.firstName); // John
// Accessing properties (Bracket notation)
console.log(user["age"]); // 30
// Modifying or adding a property
user.age = 31;
user.country = "Canada";
console.log(user);
8. The Document Object Model (DOM)
The DOM is the programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.
Selecting Elements
// Selecting an element by ID
const title = document.getElementById("main-title");
// Selecting elements by CSS selectors
const buttons = document.querySelectorAll(".btn");
Modifying Elements
// Changing text content
title.textContent = "Welcome to My New Site";
// Changing inline CSS styles
title.style.color = "blue";
Event Listeners
You can make elements respond to user actions like clicks, keyboard inputs, or mouse movements.
<!-- Example HTML -->
<button id="alert-btn">Click Me</button>
// Example JS
const myButton = document.getElementById("alert-btn");
myButton.addEventListener("click", function() {
alert("Button was clicked!");
});
9. Introduction to Asynchronous JavaScript
In JavaScript, some operations (like fetching data from an API or waiting for a timer) take time. Instead of freezing the page, JS handles these tasks asynchronously.
Promises
A Promise represents an operation that hasn't completed yet but is expected in the future.
const fetchData = new Promise((resolve, reject) => {
let success = true; // Simulating a server response
setTimeout(() => {
if (success) {
resolve("Data retrieved successfully.");
} else {
reject("Failed to fetch data.");
}
}, 2000); // Waits 2 seconds
});
fetchData
.then(result => console.log(result))
.catch(error => console.error(error));
Async / Await (Modern Approach)
async and await make asynchronous code look and behave more like synchronous code, making it easier to read and maintain.
// A mock function that returns a Promise
function delayResponse() {
return new Promise(resolve => setTimeout(() => resolve("Hello from the API"), 1500));
}
async function getInformation() {
console.log("Loading...");
// The await keyword pauses execution until the promise resolves
const response = await delayResponse();
console.log(response);
}
getInformation();
The guide was created in June 2026.