Skip to content

Javascript Basics

Let’s start with the basics!

Variables can be declared with let, const, or var. Use const by default for values that won’t change, and let for those that will. Try to avoid var due to its scoping behavior, which can lead to bugs and a slight increase in memory usage.

In JavaScript, if statements are used to run code conditionally based on whether a condition evaluates to true or false. Below are examples of single-line, multi-line, and ternary if statements, along with else if and else cases.

A single-line if statement is used when you only have one statement to execute. It does not require curly braces.

if (condition) console.log('Condition is true!');

This is useful when you want to keep the code compact, but be cautious when expanding the logic later on.

let age = 18;
if (age >= 18) console.log('You are an adult!');

A multi-line if statement is used when there are multiple lines of code to execute, or when it is preferred to always use curly braces, even for a single line. This ensures that future modifications won’t accidentally break the logic.

if (condition) {
// Code to run if condition is true
console.log('Condition is true!');
performAnotherAction();
}

Multi-line statements are often more readable, especially in larger codebases.

let score = 80;
if (score > 50) {
console.log('Pass');
console.log('You scored above average!');
}

The ternary operator provides a shorthand way to write an if-else statement on a single line. It’s great for simple conditions and concise code.

let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // Outputs 'Adult'

There’s no strict preference for function syntax. You can use:

  • Function expressions
  • Arrow functions
  • Function declarations

However, there are some patterns to follow:

Files storing functions should use lowercase and camelCase naming, for example:

  • index.js
  • myCollectionOfFunctions.js

All functions that receive parameters should accept them as an object. Here’s an example:

Files where you store the functions should follow the naming convention of being lowercase and camelCase, such as index.js or myCollectionOfFunctions.js.

In this guide, we follow a consistent approach for defining and calling functions by passing parameters as objects. This helps with code readability and scalability, especially when functions grow or require more parameters.

// Function call
yourFunction({ a: element, b: 30 });
// Function definition using object destructuring
function yourFunction({ a, b }) {
console.log(a);
console.log(b);
// Function body
}
// Function definition using the payload object directly
function yourFunction(payload) {
console.log(payload.a, payload.b);
// Function body
}

Passing parameters as an object allows for:

  • Improved code readability
  • Flexibility when expanding functions with more parameters
  • Easier function calls, as the order of parameters becomes irrelevant

All functions, no matter how clear or simple they may seem, must include documentation. This is critical because not all developers are at the same level of expertise. Documentation ensures that anyone, regardless of their experience, can understand the purpose and usage of each function. While AI tools can assist with generating code, human-readable documentation is necessary to maintain clarity and assist other team members who may be unfamiliar with certain practices.

The for loop in JavaScript is one of the most commonly used loops. It repeats a block of code a specific number of times, making it useful when you know how many iterations you need.

for (initialization; condition; increment) {
// Code to execute
}
for (let i = 0; i < 5; i++) {
console.log(i);
}

While the traditional for loop is still useful, modern JavaScript often prefers using .forEach(), especially when working with arrays or NodeLists (like elements selected from the DOM). This is because .forEach() provides a cleaner and more readable syntax, and is designed specifically for iterating through arrays or collections.

Example: Using .forEach() with querySelectorAll

Section titled “Example: Using .forEach() with querySelectorAll”
document.querySelectorAll('.js--item').forEach((element, index, array) => {
// Code to execute for each element
console.log(`Element ${index}:`, element);
});

This method is ideal when you want to iterate over a collection of elements selected from the DOM and perform actions on each one.

.find() is used to find the first element in an array (or NodeList) that satisfies a condition. Unlike .forEach(), which iterates over every element, .find() stops as soon as it finds a matching element.

const numbers = [10, 20, 30, 40];
const foundNumber = numbers.find(num => num > 25);
console.log(foundNumber); // Output: 30

.map() is used to transform each element in an array and returns a new array with the transformed values. It does not modify the original array.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled);

All JavaScript classes must include the following structure.

  • Start filenames with an uppercase letter.
  • Classes must be exported as default to simplify imports.

All classes must include a constructor, and the constructor should follow a specific pattern:

  • Include a constructor in every class.
  • DOM elements should be named with the prefix “js—” to distinguish them for JavaScript functionality.
  • init Method: Handles initialization logic like setting states or values.
  • events Method: Exclusively adds eventListeners to maintain separation between initialization and interaction.
// Usage example
new ExpandendButton({
element: document.querySelector('.js--TriggerButton'),
maxTime: 20
});
// Class definition
class ExpandendButton {
constructor({ element, maxTime }) {
this.DOM = {
element: element, // Storing the DOM element
};
this.max = maxTime; // Storing the maxTime parameter
this.init(); // Initializing the class
this.events(); // Setting up event listeners
}
// The init method is for initialization logic
init() {
// Initialization code, for example:
console.log('ExpandendButton initialized with maxTime:', this.max);
}
// The events method is for setting up event listeners only
events() {
this.DOM.element.addEventListener('click', () => {
this.handleClick();
});
}
// Example method for handling click events
handleClick() {
console.log('Button clicked!');
}
}
// Exporting the class as default
export default ExpandendButton;