Remsey Mailjard

JavaScript Glossary for Beginners

5 min read4 comments
image
https://codersfree.com/posts/que-es-javascript-principales-usos

JavaScript Glossary for Beginners

JavaScript is a scripting language widely used to make web pages interactive. In this guide, we'll cover some key terms that every beginner should be aware of.

Variables

At the core of every program are variables. In JavaScript, variables are used to store data values. The `var`, `let`, and `const` keywords are typically used to declare variables.


var oldWay = "I'm a variable from the old way!";
let newWay = "I'm a modern variable!";
const unchangeable = "I cannot be changed!";


// Individual details
let firstname = "Remsey"; // String variable for first name
let lastname = 'Mailjard'; // String variable for last name
let age = 34;  // Number variable for age

// Boolean variables indicating various states/attributes
let isHappy = true; 
let isRich = false;
let isAdult = true;
let isMarried = false;
let hasChildren = false;
let hasAdog = true;

// Array containing various colors
let colors = ["Red", "Blue", "Green"]; 

// Null and undefined variable examples
let calledAFriend = null;  // Variable declared with no value
let calledAfriend;  // Variable left undefined

// Using the Date object to store a birthdate
let DateOfBirth = new Date(1989,2,6);

// A constant URL string
const githubURL = "http://www.github.com/remseymailjard";

// Object representing a teacher with various properties
let teacher = {
    firstName: "Remsey",
    lastName: "Mailjard",
    age: 34,
    hasADog: false,
    hobbies: ["working out", "chilling with friends", "reading", "programming"],  // Array of hobbies
    scoreOnAssesment: [10,20,30],  // Array of scores
    DateOfBirth: new Date(1989,2,6)  // Birthdate
};

// Object representing a student with a subset of properties
let student = {
    firstName: "Justine",
    lastname: "Elbuhel"
};

// Basic arithmetic operation
let numberA = 5;
let numberB = 10;
let result = numberA + numberB;  // Sum of two numbers

// Logging values and strings to console
console.log(result);  // Logs the result of the arithmetic operation
console.log("The result is " + result);  // String concatenation
console.log(`The result is ${result}`);  // Using template literals for string interpolation
console.log(`My name is ${firstname} ${lastname}`);  // String interpolation with variables
console.log(`The student's name is: ${student.firstName} ${student.lastname}`);  // Accessing object properties

// Constants related to mathematical and time-based values
const PI = 3.14;  // Mathematical constant for pi
const Month_in_a_year = 12;  // Number of months in a year

console.log(Month_in_a_year);  // Logging constant to console

Functions

Functions are blocks of reusable code. They can take inputs, process them, and then return an output. Functions are defined using the `function` keyword.


function greet(name) {
    return "Hello, " + name + "!";
}
console.log(greet("Alice"));  // Outputs: Hello, Alice!

// A function to calculate the area of a rectangle
function calculateArea(length, width) {
    return length * width;
}
console.log(calculateArea(10, 5));  // Outputs: 50

// A function to determine if a number is even or odd
function isEven(number) {
    return number % 2 === 0;
}
console.log(isEven(4));  // Outputs: true
console.log(isEven(7));  // Outputs: false

// A function that returns an array of all even numbers from an input array
function filterEvenNumbers(numbers) {
    return numbers.filter(num => num % 2 === 0);
}
console.log(filterEvenNumbers([1, 2, 3, 4, 5, 6]));  // Outputs: [2, 4, 6]

// A function that calculates the total price after tax
function calculateTotal(price, taxRate = 0.1) {
    return price + (price * taxRate);
}
console.log(calculateTotal(100));        // Outputs: 110
console.log(calculateTotal(100, 0.2));   // Outputs: 120

Arrays

Arrays are used to store multiple values in a single variable. In JavaScript, arrays can hold multiple data types and are created using square brackets `[]`.


let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);  // Outputs: apple

let people = ["John", "Jane", "Doe"];
console.log(people[1]);  // Outputs: Jane

let hobbies = ["reading", "hiking", "swimming", "painting"];
console.log(hobbies[2]);  // Outputs: swimming

let personDetails = [
    { name: "Alice", age: 25, hobby: "gaming" },
    { name: "Bob", age: 30, hobby: "fishing" }
];
console.log(personDetails[0].name);  // Outputs: Alice
console.log(personDetails[1].hobby);  // Outputs: fishing

Objects

Objects are collections of key-value pairs. They can hold multiple data types, including other objects. Objects are created using curly braces `{}`.


let car = {
    brand: "Toyota",
    model: "Camry",
    year: 2020
};
console.log(car.model);  // Outputs: Camry

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    hobbies: ["reading", "cycling"]
};
console.log(person.firstName);  // Outputs: John
console.log(person.hobbies[0]);  // Outputs: reading

let book = {
    title: "To Kill a Mockingbird",
    author: {
        firstName: "Harper",
        lastName: "Lee"
    },
    publishedYear: 1960
};
console.log(book.author.firstName);  // Outputs: Harper

let movie = {
    title: "Inception",
    director: "Christopher Nolan",
    year: 2010,
    actors: ["Leonardo DiCaprio", "Ellen Page"]
};
console.log(movie.actors[1]);  // Outputs: Ellen Page

Loops

Loops are used to repeatedly run a block of code. JavaScript offers several types of loops including `for`, `while`, and `do...while`.


for (let i = 0; i < 3; i++) {
	console.log(i);  // Outputs: 0, 1, 2
}

// Looping through the 'fruits' array
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);  // Outputs each fruit sequentially
}

// Looping through the 'people' array
let people = ["John", "Jane", "Doe"];
for (let person of people) {
    console.log(person);  // Outputs each person's name sequentially
}

// Looping through 'hobbies' using a while loop
let hobbies = ["reading", "hiking", "swimming", "painting"];
let j = 0;
while (j < hobbies.length) {
    console.log(hobbies[j]);
    j++;
}

// Looping through 'personDetails' array to print name and hobby
let personDetails = [
    { name: "Alice", age: 25, hobby: "gaming" },
    { name: "Bob", age: 30, hobby: "fishing" }
];
for (let detail of personDetails) {
    console.log(`${detail.name} likes ${detail.hobby}`);
}

Events

Events are actions that can be detected by JavaScript, like a button being clicked or a page loading. JavaScript can respond to these events with a block of code.


// Responding to a button click
document.getElementById("myButton").addEventListener("click", function() {
	alert("Button was clicked!");
});

// Executing code when the page has fully loaded
window.addEventListener("load", function() {
    console.log("Page has loaded!");
});

// Logging the change of an input field
document.getElementById("myInput").addEventListener("change", function() {
    console.log("Input changed to:", this.value);
});

// Detecting when the mouse hovers over an element
document.getElementById("hoverElement").addEventListener("mouseover", function() {
    console.log("Mouse is hovering over the element.");
});

// Reacting to a keyboard key being pressed while inside an input field
document.getElementById("keyInput").addEventListener("keydown", function(event) {
    console.log(`Key pressed: ${event.key}`);
});

// Responding to the resizing of the window
window.addEventListener("resize", function() {
    console.log("Window has been resized!");
});

DOM Manipulation

The Document Object Model (DOM) represents the structure of an HTML document. With JavaScript, you can change the content, structure, and style of the DOM.


// Changing the content of an element
document.getElementById("myText").innerHTML = "New text content!";

// Changing an element's style
document.getElementById("highlighted").style.backgroundColor = "yellow";

// Adding a new element
let newParagraph = document.createElement("p");
newParagraph.innerHTML = "This is a new paragraph!";
document.body.appendChild(newParagraph);

// Removing an element
let elementToRemove = document.getElementById("toBeRemoved");
elementToRemove.parentNode.removeChild(elementToRemove);

// Changing the source of an image
document.getElementById("myImage").src = "path/to/new/image.jpg";

// Handling form input
let inputValue = document.getElementById("myInputField").value;

// Adding a class to an element
document.getElementById("myDiv").classList.add("newClass");

// Removing a class from an element
document.getElementById("myDiv").classList.remove("oldClass");

// Toggling a class (adds the class if it doesn't exist, removes it if it does)
document.getElementById("myDiv").classList.toggle("toggleClass");

// Setting an attribute to an element
document.getElementById("myLink").setAttribute("href", "https://www.example.com");

// Getting an attribute value from an element
let linkValue = document.getElementById("myLink").getAttribute("href");

Conditions and Decisions

JavaScript supports conditional statements like `if`, `else if`, and `else`, allowing us to make decisions in code based on certain conditions.


let weather = "sunny";
if (weather === "rainy") {
    console.log("Bring an umbrella!");
} else {
    console.log("Enjoy the day!");
}
// Outputs: Enjoy the day!

let temperature = 25;
if (temperature < 0) {
    console.log("It's freezing outside!");
} else if (temperature < 10) {
    console.log("It's cold outside.");
} else if (temperature < 20) {
    console.log("It's cool outside.");
} else {
    console.log("It's warm outside.");
}
// Outputs: It's warm outside.

let grade = 85;
if (grade >= 90) {
    console.log("You got an A!");
} else if (grade >= 80) {
    console.log("You got a B.");
} else if (grade >= 70) {
    console.log("You got a C.");
} else if (grade >= 60) {
    console.log("You got a D.");
} else {
    console.log("You got an F.");
}
// Outputs: You got a B.

let isMember = true;
let discount = isMember ? 10 : 5;
console.log(`You get a ${discount}% discount.`);
// Outputs: You get a 10% discount.


What's listed above is just a snapshot of JavaScript terms. For a more comprehensive list, refer to the official JavaScript guide on MDN.

Kies kleur