Introducing JavaScript
JavaScript is "THE" programming language essential for web development.
It allows you to create responsive web applications by manipulating the Document Object Model (DOM), (which is the structure and content of a web page).
In this guide, I will outline the fundamentals of JavaScript, including variables, functions, arrow functions, arrays, callback functions, objects, properties, keys, values, and methods, and how they relate to the DOM.
Variables
In JavaScript, variables are used to store and manage data.
They act as containers that can hold different types of information, such as numbers, strings, or objects. Variables are declared using the var
, let
, or const
keyword and their values can be changed or updated during the execution of a program, but in different ways:
var
: Variables declared withvar
are function-scoped, which means they are only accessible within the function where they are defined.let
: Variables declared withlet
are block-scoped, making them accessible only within the block (curly braces) in which they are defined. This is the preferred way to declare variables.const
: These are also block-scoped, but their values cannot be reassigned after initializing. It should be used for values that are constant.var x = 5; let y = 6; const z = 7;
Functions
Functions in JavaScript are blocks of reusable code that can be executed when called. They allow you to encapsulate logic and perform specific tasks, or instructions. Functions are defined using the function
keyword followed by a name, a list of parameters enclosed in parentheses, and the function body enclosed in curly braces.
function myFunction(){
let y = 6;
const z = 7;
console.log(y + z); // Output: 13
}
Arrow Functions
Arrow functions are an alternative way to declare functions, are more concise, and are often used for short, simple syntax functions.
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
Arrays
Arrays are used to store collections of data. They are like variables but can hold elements of different types, including numbers, strings, objects, and even other arrays. Arrays are declared using square brackets []
.
You can manipulate arrays by adding or removing elements, iterating through them, and performing various operations like sorting and filtering, using different types of already programmed array methods.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output: apple
console.log(fruits.length); // Output: 3
Callback Functions
Callback functions are functions that are passed as arguments to other functions and executed later on, often when an asynchronous operation is completed. They are a fundamental concept in JavaScript, especially when dealing with events and asynchronous operations.
Here's a simple example of a callback function:
function performOperation(x, y, callback) {
const result = x + y;
callback(result); // Call the callback function with the result
}
function displayResult(result) {
console.log("The result is:", result);
}
performOperation(5, 3, displayResult);
Objects
Objects are elements defined by key-value pairs, where keys are strings and values can be of any data type, including other objects or functions. Objects are defined using curly braces {}
.
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function () {
console.log(`Hello, ${this.firstName} ${this.lastName}!`);
},
};
console.log(person.firstName); // Output: John
person.greet(); // Output: Hello, John Doe!
Properties: In the context of objects, properties are the key-value pairs that define the object's characteristics or attributes. For example,
firstName
,lastName
, andage
are properties in theperson
object from the previous example.Keys: Keys are the names associated with object properties. In the
person
object,firstName
,lastName
, andage
are keys.Values: Values are the data associated with object properties. In the
person
object, "John," "Doe," and 30 are values.Methods: Methods are functions defined as properties of an object. In the
person
object,greet
is a method.
Relating ALL THIS to the DOM
The DOM is a hierarchical representation of an HTML document, that works like a tree. It consists of elements (nodes) that you can manipulate. Here's how the JavaScript fundamentals connect to the DOM:
Variables: You can use variables to store references to DOM elements you want to interact with. For example:
const heading = document.querySelector("h1");
Here,
heading
now will refer to the first<h1>
element in the DOM.Functions: Functions can be used to encapsulate actions you want to perform on the DOM. For instance, you can create a function to change the text of an HTML element:
function changeText() { heading.textContent = "New Heading Text"; }
Then, you can call this function to change the text when an event occurs.
Arrow Functions: Arrow functions are often used in event handling. For instance:
button.addEventListener("click", () => { heading.textContent = "Button Clicked!"; });
Here, we use an arrow function as the event handler for a button click.
Arrays: You can use arrays to store collections of DOM elements. For example, if you want to select all the paragraphs on a page:
const paragraphs = document.querySelectorAll("p");
Callback Functions: Callback functions are commonly used with asynchronous operations in web development. When an event occurs or data is fetched from a server, you can execute callback functions to update the DOM accordingly.
fetchDataFromServer((data) => { // Update the DOM with the fetched data updateDOM(data); });
Objects: Objects can represent complex structures in the DOM. For instance, you can create an object