<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Whoissosick</title>
    <description>The latest articles on Forem by Whoissosick (@0netheball).</description>
    <link>https://forem.com/0netheball</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3586769%2F10cf5439-0896-4042-814c-e005c241afb9.jpeg</url>
      <title>Forem: Whoissosick</title>
      <link>https://forem.com/0netheball</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/0netheball"/>
    <language>en</language>
    <item>
      <title>How Do Event Bubbling, and Event Delegation Work?</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Fri, 05 Dec 2025 07:04:10 +0000</pubDate>
      <link>https://forem.com/0netheball/how-do-event-bubbling-and-event-delegation-work-2ckj</link>
      <guid>https://forem.com/0netheball/how-do-event-bubbling-and-event-delegation-work-2ckj</guid>
      <description>&lt;p&gt;Event bubbling, or propagation, refers to how an event "bubbles up" to parent objects when triggered. For example, consider this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The p element here would be considered the parent of the span element.&lt;/p&gt;

&lt;p&gt;When you click on the span element, like you are instructed to, the span element becomes the target of a click event. That event, however, also bubbles up to the parent – the p element can receive and consume that event as needed.&lt;/p&gt;

&lt;p&gt;But what does this actually mean? Well, you could attach an event listener to the p element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p = document.querySelector("p");
p.addEventListener("click", (event) =&amp;gt; {
  console.log(event.target);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, when you click on the span element you will see the text Click me~! logged to the console.&lt;/p&gt;

&lt;p&gt;Just to be sure how things are working&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p = document.querySelector("p");
const span = document.querySelector("span");
p.addEventListener("click", (event) =&amp;gt; {
  console.log("P listener: ");
  console.log(event.target);
});
span.addEventListener("click", (event) =&amp;gt; {
  console.log("Span listener: ");
  console.log(event.target);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To give you an idea of how the event bubbles up, here's what you'll see in the console after clicking the span element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Span listener: "
&amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
"P listener: "
&amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's see what happens when you prevent the propagation of an event with stopPropagation(). We'll call it in our span's event listener:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p = document.querySelector("p");
const span = document.querySelector("span");
p.addEventListener("click", (event) =&amp;gt; {
  console.log("P listener: ");
  console.log(event.target);
});
span.addEventListener("click", (event) =&amp;gt; {
  console.log("Span listener: ");
  console.log(event.target);
  event.stopPropagation();
});

"Span listener: "
&amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This time, we don't see our p listener trigger. The event never fires for the p element, because we told it to stop propagation while it was being processed for the child span element.&lt;/p&gt;

&lt;p&gt;Event delegation can be thought of as the opposite. It's the process of taking a captured event, and delegating it to another element.&lt;/p&gt;

&lt;p&gt;Going back to our code, let's update it so clicking on a span element changes it to red:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p = document.querySelector("p");
const span = document.querySelector("span");
p.addEventListener("click", (event) =&amp;gt; {});
span.addEventListener("click", (event) =&amp;gt; {
  event.target.style.color = "red";
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But what if you have twenty span elements? Or maybe you use JavaScript to create more span elements on the fly?&lt;/p&gt;

&lt;p&gt;Rather than having to attach an event listener to every single span element, you can actually use the listener on the p element for all of them. In other words, you can delegate the handling of the span clicks to the parent p element.&lt;/p&gt;

&lt;p&gt;Our code might now look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p = document.querySelector("p");
p.addEventListener("click", (event) =&amp;gt; {
  event.target.style.color = "red";
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice how we no longer have any listener attached to the span element at all. You have properly delegated the event handling to the p element. But does it work?&lt;/p&gt;

&lt;p&gt;Let's generate a few extra span elements and see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;p&amp;gt;
  &amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
  &amp;lt;span&amp;gt;Click me~!&amp;lt;/span&amp;gt;
&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, each time we click on a span, that element's text will become red.&lt;/p&gt;

&lt;p&gt;And just like that, with a single event listener we've properly allowed a click event to bubble up from span elements to the parent p, and delegated the logic for that click event to the p element.&lt;/p&gt;

&lt;p&gt;Event propagation and delegation can be a complex topic, especially as you get into heavily nested elements like tables. You are encouraged to explore this further and experiment with some of the code we've written here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function instrumentCards(instrumentCategory) {
  const instruments =
    instrumentCategory === "all"
      ? instrumentsArr
      : instrumentsArr.filter(
          ({ category }) =&amp;gt; category === instrumentCategory
        );

  return instruments
    .map(({ instrument, price }) =&amp;gt; {
      return `
          &amp;lt;div class="card"&amp;gt;
            &amp;lt;h2&amp;gt;${instrument}&amp;lt;/h2&amp;gt;
            &amp;lt;p&amp;gt;$${price}&amp;lt;/p&amp;gt;
          &amp;lt;/div&amp;gt;
        `;
    }).join("");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Higher Order Functions Review</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Fri, 05 Dec 2025 04:47:11 +0000</pubDate>
      <link>https://forem.com/0netheball/higher-order-functions-review-4546</link>
      <guid>https://forem.com/0netheball/higher-order-functions-review-4546</guid>
      <description>&lt;h2&gt;
  
  
  Callback Functions and the forEach Method
&lt;/h2&gt;

&lt;p&gt;Definition: In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after the main function has finished its execution.&lt;br&gt;
forEach() Method: This method is used to iterate over each element in an array and perform an operation on each element. The callback function in forEach can take up to three arguments: the current element, the index of the current element, and the array that forEach was called upon.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];

// Result: 2 4 6 8 10
numbers.forEach((number) =&amp;gt; {
  console.log(number * 2);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Higher Order Functions&lt;br&gt;
Definition: A higher order function takes one or more functions for the arguments and returns a function or value for the result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function operateOnArray(arr, operation) {
  const result = [];
  for (let i = 0; i &amp;lt; arr.length; i++) {
    result.push(operation(arr[i]));
  }
  return result;
}

function double(x) {
  return x * 2;
}

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = operateOnArray(numbers, double);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;map() Method: This method is used to create a new array by applying a given function to each element of the original array. The callback function can accept up to three arguments: the current element, the index of the current element, and the array that map was called upon.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map((num) =&amp;gt; num * 2);

console.log(numbers); // [1, 2, 3, 4, 5]
console.log(doubled); // [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;filter() Method: This method is used to create a new array with elements that pass a specified test, making it useful for selectively extracting items based on criteria. Just like the map method, the callback function for the filter method accepts the same three arguments: the current element being processed, the index, and the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((num) =&amp;gt; num % 2 === 0);

console.log(evenNumbers); // [2, 4, 6, 8, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;reduce() Method: This method is used to process an array and condense it into a single value. This single value can be a number, a string, an object, or even another array. The reduce() method works by applying a function to each element in the array, in order, passing the result of each calculation on to the next. This function is often called the reducer function. The reducer function takes two main parameters: an accumulator and the current value. The accumulator is where you store the running result of your operations, and the current value is the array element being processed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(
  (accumulator, currentValue) =&amp;gt; accumulator + currentValue,
  0
);

console.log(sum); // 15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Method Chaining&lt;br&gt;
Definition: Method chaining is a programming technique that allows you to call multiple methods on the same object in a single line of code. This technique can make your code more readable and concise, especially when performing a series of operations on the same object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const result = "  Hello, World!  "
  .trim()
  .toLowerCase()
  .replace("world", "JavaScript");

console.log(result); // "hello, JavaScript!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Working with the sort Method&lt;br&gt;
Definition: The sort method is used to sort the elements of an array and return a reference to the sorted array. No copy is made in this case because the elements are sorted in place.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
If you need to sort numbers, then you will need to pass in a compare
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you need to sort numbers, then you will need to pass in a compare function. The sort method converts the elements to strings and then compares their sequences of UTF-16 code units values. UTF-16 code units are the numeric values that represent the characters in the string. Examples of UTF-16 code units are the numbers 65, 66, and 67 which represent the characters "A", "B", and "C" respectively. So the number 200 appears before the number 3 in an array, because the string "200" comes before the string "3" when comparing their UTF-16 code units.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [414, 200, 5, 10, 3];

numbers.sort((a, b) =&amp;gt; a - b);

console.log(numbers); // [3, 5, 10, 200, 414]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The parameters a and b are the two elements being compared. The compare function should return a negative value if a should come before b, a positive value if a should come after b, and zero if a and b are equal.&lt;/p&gt;

&lt;p&gt;Working with the every and some Methods&lt;br&gt;
every() Method: This method tests whether all elements in an array pass a test implemented by a provided function. The every() method returns true if the provided function returns true for all elements in the array. If any element fails the test, the method immediately returns false and stops checking the remaining elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [2, 4, 6, 8, 10];
const hasAllEvenNumbers = numbers.every((num) =&amp;gt; num % 2 === 0);

console.log(hasAllEvenNumbers); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;some() Method: This method checks if at least one element passes the test. The some() method returns true as soon as it finds an element that passes the test. If no elements pass the test, it returns false.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 3, 5, 7, 8, 9];
const hasSomeEvenNumbers = numbers.some((num) =&amp;gt; num % 2 === 0);

console.log(hasSomeEvenNumbers); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Working with the DOM, Click Events, and Web APIs</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Tue, 02 Dec 2025 04:19:11 +0000</pubDate>
      <link>https://forem.com/0netheball/working-with-the-dom-click-events-and-web-apis-4e7d</link>
      <guid>https://forem.com/0netheball/working-with-the-dom-click-events-and-web-apis-4e7d</guid>
      <description>&lt;h2&gt;
  
  
  What Is an API, and What Are Web APIs?
&lt;/h2&gt;

&lt;p&gt;These types of APIs are often divided into two main categories: browser APIs and third-party APIs.&lt;/p&gt;

&lt;p&gt;Browser APIs expose data from the browser. As a web developer, you can access and manipulate this data using JavaScript.&lt;/p&gt;

&lt;p&gt;They also provide access to various functionalities, such as manipulating the structure of the website, handling events, working with storage, and communicating with the network.&lt;/p&gt;

&lt;p&gt;Some examples of commonly used Browser APIs include:&lt;/p&gt;

&lt;p&gt;The DOM API, which you can use to manipulate HTML elements, their styles, and attributes. You will learn much more about the DOM in the coming lessons. It’s a core concept in web development.&lt;/p&gt;

&lt;p&gt;The Storage API, to store data locally on the user’s device.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Is the requestAnimationFrame() API, and How Can It Be Used to Set Up an Animation Loop?
&lt;/h2&gt;

&lt;p&gt;To use the requestAnimationFrame() method, all you need to do is to call it and pass a callback function into it: requestAnimationFrame(callback);&lt;/p&gt;

&lt;p&gt;Calling requestAnimationFrame() must first occur inside a function that handles the animation, such as animate(), along with a function to update the animation, traditionally called update():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function animate() {
 // Update the animation...
 // for example, move an element, change a style, and more.
 update();
 // Request the next frame
 requestAnimationFrame(animate);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The update() function is where the magic happens. Inside it, you get to change whatever you want to animate. For example, updating a style or changing the position of an element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function update() {
 element.style.transform = `translateX(${position}px)`;
 position += 2;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What finally kicks off the animation is calling requestAnimationFrame() and passing in the animate function, this time outside the animate function: requestAnimationFrame(animate);&lt;/p&gt;

&lt;h2&gt;
  
  
  What Is the Web Animations API, and How Does It Relate to CSS Animation Properties?
&lt;/h2&gt;

&lt;p&gt;When to use:  When you need animations to respond to user interactions like clicks, scrolls, or allow dynamic control such as pausing or reversing.&lt;/p&gt;

&lt;p&gt;The Web Animations API (WAAPI) allows you to create and control animations directly within JavaScript.&lt;/p&gt;

&lt;p&gt;At the core of WAAPI is the Animation constructor, which provides several instance methods and properties that allow you to dynamically animate elements. A significant method in the Animation constructor is animate(). It allows you to create an animation by specifying keyframes and options like duration, direction, easing, and iterations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const square = document.querySelector("#square");

const animation = square.animate(
  [{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }],
  {
    duration: 2000, // makes animation lasts 2 seconds
    iterations: Infinity, // loops indefinitely
    direction: "alternate", // moves back and forth
    easing: "ease-in-out" // smooth easing
  }
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const square = document.querySelector("#square");
const playBtn = document.querySelector("#playBtn");
const pauseBtn = document.querySelector("#pauseBtn");

const animation = square.animate(
  [{ transform: "translateX(0px)" }, { transform: "translateX(200px)" }],
  {
    duration: 5000, // Animation lasts 5 seconds
    // iterations: Infinity, // Loops indefinitely
    direction: "alternate", // Moves back and forth
    easing: "ease-in-out" // Smooth easing function
  }
);

// Set the onfinish property to log a message when the animation ends
animation.onfinish = () =&amp;gt; {
  console.log("Animation finished!");
};

// Play the animation when the "Play" button is clicked
playBtn.addEventListener("click", () =&amp;gt; {
  animation.play();
  console.log("You start the animation");
});

// Pause the animation when the "Pause" button is clicked
pauseBtn.addEventListener("click", () =&amp;gt; {
  animation.pause();
  console.log("You pause the animation");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Is the Canvas API, and How Does It Work?
&lt;/h2&gt;

&lt;p&gt;The Canvas API is a powerful tool that lets you manipulate graphics right inside your JavaScript file. Everything begins with a canvas element in HTML. This element serves as a drawing surface that you can manipulate using the instance methods and properties of the Canvas API.&lt;/p&gt;

&lt;p&gt;First, you need to create a canvas element in your HTML file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;canvas id="my-canvas"&amp;gt;&amp;lt;/canvas&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The canvas element is represented by the HTMLCanvasElement interface, which provides methods and properties for manipulating it. Additionally, you can use methods and properties from other interfaces in the Canvas API.&lt;/p&gt;

&lt;p&gt;You can give your canvas a width and height inside the HTML:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;canvas id="my-canvas" width="400" height="400"&amp;gt;&amp;lt;/canvas&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or you can use the width and height properties of the HTMLCanvasElement interface:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const canvas = document.getElementById("my-canvas");
canvas.width = 400;
canvas.height = 400;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For now, you can't see anything on the screen yet. After creating your canvas element, the next thing to do is to get access to the drawing context of the canvas with the getContext() method of the HTMLCanvasElement interface. &lt;/p&gt;

&lt;p&gt;The most common context is 2d, which allows you to draw in two dimensions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const canvas = document.getElementById("my-canvas");
const ctx = canvas.getContext('2d');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you log the ctx variable to the console, you'll see the methods and properties of CanvasRenderingContext2D that you can use to create shapes, colors, lines, and more, along with their default values:&lt;/p&gt;

&lt;p&gt;The Canvas API provides several methods and properties for drawing shapes, lines, and text. One of those is the fillStyle property, which you can combine with the fillRect() method to draw a rectangle or square:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;canvas id="my-canvas" width="400" height="400"&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
const canvas = document.getElementById("my-canvas");

const ctx = canvas.getContext("2d");

// Set the background color
ctx.fillStyle = "crimson";

// Draw a rectangle
ctx.fillRect(1, 1, 150, 100);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;fillRect takes 4 number values which represent the x axis, y axis, width, and height, respectively.&lt;/p&gt;

&lt;p&gt;There's something on the screen now. You can also draw text or even create an animation. Here's a canvas to represent text:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;canvas id="my-text-canvas" width="300" height="70"&amp;gt;&amp;lt;/canvas&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To finally draw the text, pass the text into the fillText() method as the first argument, followed by the values for the x and y axis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;canvas id="my-text-canvas" width="300" height="70"&amp;gt;&amp;lt;/canvas&amp;gt;
    &amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
const textCanvas = document.getElementById("my-text-canvas");

const textCanvasCtx = textCanvas.getContext("2d");

// Set font family and size
textCanvasCtx.font = "30px Arial";

// Set text color
textCanvasCtx.fillStyle = "crimson";

// Draw the text
textCanvasCtx.fillText("Hello HTML Canvas!", 1, 50);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result in the browser will be the red text Hello HTML Canvas!.&lt;/p&gt;

&lt;p&gt;These's much more you can do with the Canvas API. For example, you can combine it with requestAnimationFrame to create custom animations, visualizations, games, and more.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Do You Open and Close Dialog Elements Using JavaScript?
&lt;/h2&gt;

&lt;p&gt;Dialogs let you display important information or actions to users. With HTML's built-in dialog element, you can easily create these dialogs (both modal and non-modal dialogs) in your web apps.&lt;/p&gt;

&lt;p&gt;A modal dialog is a type of dialog that forces the user to interact with it before they can access the rest of the application or webpage. It effectively blocks interaction with other content until the user completes an action, such as closing the dialog or submitting a form.&lt;/p&gt;

&lt;p&gt;When you want to make sure the user focuses on a specific action or message of a modal, you can open the modal dialog using the showModal() method. This will add a backdrop to the other items on the page and disable them. This is ideal for modals that display forms, confirmations, and critical information that requires user action. &lt;/p&gt;

&lt;p&gt;Here's the HTML for the modal dialog:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dialog id="my-modal"&amp;gt;
  &amp;lt;p&amp;gt;This is a modal dialog.&amp;lt;/p&amp;gt;
&amp;lt;/dialog&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For now, you can't see anything on the page because the modal is closed on the initial render. You can automatically open the modal by using the showModal() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dialog id="modal"&amp;gt;
  &amp;lt;p&amp;gt;This is a modal dialog.&amp;lt;/p&amp;gt;
&amp;lt;/dialog&amp;gt;
&amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
const dialog = document.getElementById("modal");
dialog.showModal();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result in the browser will show a modal with the text This is a modal dialog.&lt;/p&gt;

&lt;p&gt;It's best to give control to the user. To achieve this, you can add a click event listener to a button and use the showModal() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dialog id="modal"&amp;gt;
  &amp;lt;p&amp;gt;This is a modal dialog.&amp;lt;/p&amp;gt;
&amp;lt;/dialog&amp;gt;
&amp;lt;button id="open-modal-btn"&amp;gt;Open Modal Dialog&amp;lt;/button&amp;gt;
&amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
const dialog = document.getElementById("modal");
const openButton = document.getElementById("open-modal-btn");

openButton.addEventListener("click", () =&amp;gt; {
  dialog.showModal();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you needed to show a dialog while still allowing interaction with content outside of the dialog, then you can use the show() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dialog id="modal"&amp;gt;
  &amp;lt;p&amp;gt;This is a modal dialog.&amp;lt;/p&amp;gt;
&amp;lt;/dialog&amp;gt;
&amp;lt;button id="open-modal-btn"&amp;gt;Open Modal Dialog&amp;lt;/button&amp;gt;
&amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
const dialog = document.getElementById("modal");
const openButton = document.getElementById("open-modal-btn");

openButton.addEventListener("click", () =&amp;gt; {
  dialog.show();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To close a modal, you can add a button to the modal inside the dialog element and use the close() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;closeButton.addEventListener("click", () =&amp;gt; {
  dialog.close();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>api</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Callback functions</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Thu, 27 Nov 2025 09:16:31 +0000</pubDate>
      <link>https://forem.com/0netheball/callback-functions-1hmo</link>
      <guid>https://forem.com/0netheball/callback-functions-1hmo</guid>
      <description>&lt;h2&gt;
  
  
  What Is a Callback Function, and How Does It Work with the forEach Method?
&lt;/h2&gt;

&lt;p&gt;Imagine you have a function that performs a task, and you want to do something after that task is complete. Instead of writing all the code in one big function, you can pass a second function (the callback) to be executed when the first function is done.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index, array) =&amp;gt; {
  console.log(`Element ${number} is at index ${index} in array ${array}`);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Is Method Chaining, and How Does It Work?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const result = "  Hello, World!  "
  .trim()
  .toLowerCase()
  .replace("world", "JavaScript");

console.log(result); // "hello, JavaScript!"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const transactions = [
  { amount: 100, type: "credit" },
  { amount: 20, type: "cash" },
  { amount: 150, type: "credit" },
  { amount: 50, type: "cash" },
  { amount: 75, type: "credit" }
];

const totalCreditWithBonus = transactions
  .filter((transaction) =&amp;gt; transaction.type === "credit")
  .map((transaction) =&amp;gt; transaction.amount * 1.1)
  .reduce((sum, amount) =&amp;gt; sum + amount, 0);

console.log(totalCreditWithBonus); // 357.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How Does the Sort Method Work?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Do the every() and some() Methods Work?
&lt;/h2&gt;

&lt;p&gt;The every() method returns true if the provided function returns true for all elements in the array. If any element fails the test, the method immediately returns false and stops checking the remaining elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [2, 4, 6, 8, 10];
const hasAllEvenNumbers = numbers.every((num) =&amp;gt; num % 2 === 0);

console.log(hasAllEvenNumbers); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While every() checks if all elements pass a test, some() checks if at least one element passes the test. The some() method returns true as soon as it finds an element that passes the test. If no elements pass the test, it returns false.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 3, 5, 7, 8, 9];
const hasSomeEvenNumbers = numbers.some((num) =&amp;gt; num % 2 === 0);

console.log(hasSomeEvenNumbers); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Foundation JS</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Sun, 09 Nov 2025 20:26:48 +0000</pubDate>
      <link>https://forem.com/0netheball/foundation-js-5df3</link>
      <guid>https://forem.com/0netheball/foundation-js-5df3</guid>
      <description>&lt;h2&gt;
  
  
  toString() Method
&lt;/h2&gt;

&lt;p&gt;It's a method you can use for numbers, booleans, arrays, and objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const num = 10;
console.log(num.toString()); // "10"

const arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"

const person = {
  name: "John",
  age: 30,
  isStudent: true
};

console.log(person.toString()); // "[object Object]"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Is the Number Constructor, and How Does It Work for Type Coercion?
&lt;/h2&gt;

&lt;p&gt;The Number() constructor is used to create a number object. The number object contains a few helpful properties and methods like the isNaN and the toFixed method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myNum = new Number("34");
console.log(typeof myNum); // "object" 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example we pass in a string literal to the Number() constructor and the return type is of type object instead of a string.&lt;/p&gt;

&lt;p&gt;When the Number() constructor is called as a function without the new keyword, then the return value will be the primitive number type. Most of the time you will be using the Number() constructor to convert other data types to the number data type. Here's an example of converting a string to a number:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myNum = Number("100");
console.log(myNum); // 100

console.log(typeof myNum); // number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is helpful when you are getting input from the user and you need to convert that string input to a number so you can perform mathematical calculations.&lt;/p&gt;

&lt;p&gt;If you try to call the Number() constructor through an empty string then the result will be the number 0:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const num = Number("");
console.log(num); // 0

const num = Number("random");
console.log(num); // NaN

const boolTrue = Number(true);
const boolFalse = Number(false);
console.log(boolTrue); // 1
console.log(boolFalse); // 0

const undefinedNum = Number(undefined);
const nullNum = Number(null);
console.log(undefinedNum); // NaN
console.log(nullNum); // 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When working with arrays there are a few things to consider.&lt;/p&gt;

&lt;p&gt;An empty array will return 0. An array with a single number will return that number. An array with multiple numbers returns NaN. And an array with string(s) will also return NaN.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const emptyArr = Number([]);
const arrOneNum = Number([7]);
const arrMultiNum = Number([7, 36, 12]);
const arrStr = Number(["str1"]);
const arrMultiStr = Number(["str1", "str2"]);

console.log(emptyArr); // 0
console.log(arrOneNum); // 7
console.log(arrMultiNum); // NaN
console.log(arrStr); // NaN
console.log(arrMultiStr); // NaN
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When working with objects, the result is always NaN.&lt;/p&gt;

&lt;h2&gt;
  
  
  Common Practices for Naming Variables and Functions?
&lt;/h2&gt;

&lt;p&gt;For boolean variables, it's a common practice to use prefixes such as is, has, or can. This immediately tells the reader that the variable is a boolean:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let isLoading = true;
let hasPermission = false;
let canEdit = true;

function getUserData(){
  /* ... */
}

function isValidEmail(email) {
  /* For functions that return a boolean often called predicates */
}

function getProductDetails(productId) {
  /* retrieve data */
}

function handleClick(){
  /* For event handler functions */
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Can You Create an Empty Array of Fixed Length?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Array() constructor &amp;amp; Array.from()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const emptyArray = new Array(5);
console.log(emptyArray.length); // 5
console.log(emptyArray); // [undefined, undefined, undefined, undefined, undefined]

const fixedLengthArray = Array.from({ length: 5 });
console.log(fixedLengthArray.length); // 5

// [undefined, undefined, undefined, undefined, undefined]
console.log(fixedLengthArray);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to create an array of specific length and fill it with a default value, you can use the Array.fill() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const filledArray = new Array(3).fill(0);
console.log(filledArray); // [0, 0, 0]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Are Linters and Formatters, and How Can They Help You with Code Consistency?
&lt;/h2&gt;

&lt;p&gt;Linters = A linter is a static code analysis tool that flags programming errors, bugs, stylistic errors, and suspicious constructs (ESLint). &lt;/p&gt;

&lt;p&gt;Formatters = ensure a consistent code style across an entire project or team regardless of individual developer preferences (Prettier).&lt;/p&gt;

&lt;h2&gt;
  
  
  What Is Memory Management, and How Does It Work in JavaScript?
&lt;/h2&gt;

&lt;p&gt;JavaScript however uses automatic memory management. This means that JavaScript (more specifically the JavaScript engine in your web browser) takes care of memory allocation and deallocation for you. You don't have to explicitly free memory in your code. This automatic process is often called garbage collection.&lt;/p&gt;

&lt;p&gt;Closure = функция, которая "помнит" переменные из внешней области видимости&lt;br&gt;
Управление памятью = garbage collector не может удалить то, на что ещё есть ссылки&lt;/p&gt;
&lt;h2&gt;
  
  
  What Are Closures, and How Do They Work?
&lt;/h2&gt;

&lt;p&gt;Closure is a function that has access to variables in its outer enclosing lexical scope, even after the outer function has returned.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunction(x) {
    let y = 10;
    function innerFunction(){
        console.log(x + y);
    }
    return innerFunction;
}

let closure = outerFunction(5);
console.log(closure()); // 15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, outerFunction takes a parameter x and defines a local variable y. It then defines an innerFunction that uses both x and y. Finally it returns innerFunction. When we call outerFunction(5) it returns innerFunction which we assign to the variable closure. When we later call closure() it still has access to x and y from outerFunction even though outerFunction has already finished executing. This is the essence of a closure.&lt;/p&gt;

&lt;p&gt;Closures are particularly useful for creating private variables and functions. Consider this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createCounter() {
    let count = 0;
    return function () {
        count++;
        return count;
    };
}

let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, createCounter returns a function that increments and returns a count variable. The count variable is not directly accessible from outside createCounter, but the returned function (our closure) has access to it. Each time we call counter(), it increments and returns the count.&lt;/p&gt;

&lt;p&gt;Closures can also capture multiple variables from their outer scope. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function multiply(x) {
    return function (y) {
        return x * y;
    };
}

let double = multiply(2);
console.log(double(5)); // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One important thing to note about closures is that they capture variables, by reference not by value. This means if the value of a captured variable changes, the closure will see the new value. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createIncrementer() {
    let count = 0;
    return function () {
        count++;
        console.log(count);
    };
}

let increment = createIncrementer();
increment(); // 1
increment(); // 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each time we call increment its working with the same count variable, not a copy of it's initial value.&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Loops [JS]</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Thu, 06 Nov 2025 06:52:09 +0000</pubDate>
      <link>https://forem.com/0netheball/loops-js-3fga</link>
      <guid>https://forem.com/0netheball/loops-js-3fga</guid>
      <description>&lt;p&gt;The basic syntax for f "for" loop&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; 5; i++) {
  console.log(i);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Does the For...of Loop Work, and When Should You Use It?
&lt;/h2&gt;

&lt;p&gt;A for...of loop is used when you need to loop over values from an iterable. Examples of iterables would be arrays, and strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (variable of iterable) {
  // code block to be executed
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this first example we have an array of numbers and we want to loop over each number and log it to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];

for (const num of numbers) {
  console.log(num);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have created a variable called num that will represent the current number in the array. For iteration 1, num will be 1, for iteration 2, num will be 2, and so on.&lt;/p&gt;

&lt;p&gt;Here is another example where we have a string and we want to loop over each character and log it to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const str = 'WalterWhite';

for (let char of str) {
  console.log(char);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have created a variable called char that will represent the current character in the string.&lt;/p&gt;

&lt;p&gt;It is important to note that you can use let, or const when declaring the variable in a for...of loop.&lt;/p&gt;

&lt;p&gt;If you are going to use const though, make sure that the value of the variable does not change inside the loop. If it does, you will get an error.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1, 2, 3, 4, 5];

for (const num of numbers) {
  console.log(num);
  num = num + 1; // This will cause an error
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's take a look at one last example dealing with an array of objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const people = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Jim', age: 40 }
];

for (const person of people) {
  console.log(`${person.name} is ${person.age} years old`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;for...of loops are really useful when you need to loop over values from an iterable like an array or a string. &lt;/p&gt;

&lt;h2&gt;
  
  
  What Is the For...in Loop, and When Should You Use It?
&lt;/h2&gt;

&lt;p&gt;A for...in loop is best used when you need to loop over the properties of an object. This loop will iterate over all enumerable properties of an object, including inherited properties and non-numeric properties.&lt;/p&gt;

&lt;p&gt;An inherited property is a property that is inherited from the object's prototype chain. A non-numeric property is a property that is not a number or a string that can be converted to a number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruit = {
  name: 'apple',
  color: 'red',
  price: 0.99
};

for (const prop in fruit) {
  console.log(fruit[prop]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The prop variable represents the current property of the object. fruit[prop] is used to access the value of each property.&lt;/p&gt;

&lt;p&gt;For the first iteration, prop will be name. For the second iteration, prop will be color, and so on.&lt;/p&gt;

&lt;p&gt;The results logged to the console will be apple, red, and 0.99.&lt;/p&gt;

&lt;p&gt;In this second example, we have a nested object and we want to loop over each property and log the value to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA'
  }
};

function isObject(obj) {
  return typeof obj === 'object' &amp;amp;&amp;amp; !Array.isArray(obj) &amp;amp;&amp;amp; obj !== null;
}

for (const prop in person) {
  if (isObject(person[prop])) {
    for (const nestedProp in person[prop]) {
      console.log(person[prop][nestedProp]);
    }
  } else {
    console.log(person[prop]);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have a custom function isObject that checks if the value is an object.&lt;/p&gt;

&lt;p&gt;The Array.isArray method is used to check if the value is an array. By placing the logical NOT operator (!) in front of the method, we are checking if the value is not an array.&lt;/p&gt;

&lt;p&gt;The reason why we can't just use typeof equals 'object' is because arrays are also considered objects in JavaScript. We want to exclude arrays from the check.&lt;/p&gt;

&lt;p&gt;Also, due to a historical bug in JavaScript, typeof null returns 'object'. So we want to also exclude null values from the check.&lt;/p&gt;

&lt;p&gt;If the condition is true, we nest another for...in loop that will loop over the properties of the nested object and log the value to the console.&lt;/p&gt;

&lt;p&gt;The nestedProp variable represents the current property of the nested object.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Is a While Loop, and How Does It Differ from the Do...while Loop?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;while (condition) {
  // code block to be executed
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;while loops are useful when you do not know how many times you need to run the block of code. Here is an example of using a while loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let counter = 0;
while(counter &amp;lt; 5) {
  console.log(counter);
  counter++;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another loop similar to the while loop would be the do...while loop. Here is the basic syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;do {
  // code block to be executed
} while (condition);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One key difference between a do...while loop and a while loop is that the do...while loop will execute the block of code at least once before checking the condition.&lt;/p&gt;

&lt;p&gt;If the condition is true, the block of code will continue to execute. If the condition is false, the block of code will stop executing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let counter = 0;
do {
  console.log(counter);
  counter++;
} while (counter &amp;lt; 5); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have a variable called counter that is initialized to 0. The do...while loop will log the value of counter to the console and then increment counter by 1. After executing the block of code, it checks if the value of counter is less than 5. If it is, the loop will continue to run. If not, the loop will stop.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are the Break and Continue Statements Used for in Loops?
&lt;/h2&gt;

&lt;p&gt;A break statement is used to exit a loop early, while a continue statement is used to skip the current iteration of a loop and move to the next one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The break statement is useful when you want to exit a loop early based on a certain condition. For example, if you are searching for a specific value in an array, you can use a break statement to exit the loop once you find the value.&lt;/p&gt;

&lt;p&gt;Sometimes you may want to skip a particular iteration of a loop without exiting the loop entirely. This is where the continue statement comes in. Here is an example of using a continue statement in a for loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; 10; i++) {
  if (i === 5) {
    continue;
  }
  console.log(i);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output of this code will print the numbers 0, 1, 2, 3, 4, 6, 7, 8, and 9. The number 5 is skipped because of the continue statement.&lt;/p&gt;

&lt;p&gt;Another thing you can do with both the break and continue statements is to use labels to specify which loop you want to break or continue.&lt;/p&gt;

&lt;p&gt;This is useful when you have nested loops and you want to control the flow of the outer loop from within the inner loop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;outerLoop: for (let i = 0; i &amp;lt; 3; i++) {
  innerLoop: for (let j = 0; j &amp;lt; 3; j++) {
    if (i === 1 &amp;amp;&amp;amp; j === 1) {
      break outerLoop;
    }
    console.log(`i: ${i}, j: ${j}`);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we have an outer for loop labeled outerLoop and an inner for loop labeled innerLoop.&lt;/p&gt;

&lt;p&gt;When i is equal to 1 and j is equal to 1, we use the break statement with the outerLoop label to exit the outer loop early. This will exit both the inner and outer loops.&lt;/p&gt;

&lt;p&gt;The output of this code will log the following to the console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"i: 0, j: 0"
"i: 0, j: 1"
"i: 0, j: 2"
"i: 1, j: 0"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Object [JS]</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Mon, 03 Nov 2025 11:38:50 +0000</pubDate>
      <link>https://forem.com/0netheball/object-js-aga</link>
      <guid>https://forem.com/0netheball/object-js-aga</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const exampleObject = {
  propertyName: value;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These pieces of information are called properties, and they consist of a name (or key) and a value.&lt;/p&gt;

&lt;p&gt;There are two main ways to access object properties in JavaScript: dot notation and bracket notation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(person.name);  // Alice
console.log(person["name"]); // Alice
console.log(oddObject["1stProperty"]);  // Hello
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Can You Remove Properties from an Object?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;delete&lt;/strong&gt; operator&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: "Alice",
  age: 30,
  job: "Engineer"
};

delete person.job;

console.log(person.job); // undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another way to remove properties is by using destructuring assignment with rest parameters. This approach doesn't actually delete the property, but it creates a new object without the specified properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: "Bob",
  age: 25,
  job: "Designer",
  city: "New York"
};

const { job, city, ...remainingProperties } = person;

// { name: "Bob", age: 25 }
console.log(remainingProperties);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we use destructuring to extract job and city from the person object, and collect the remaining properties into a new object called remainingProperties. This creates a new object without the job and city properties.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Check If an Object Has a Property?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;hasOwnProperty() method and in operator&lt;/strong&gt; returns boolean&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: "Alice",
  age: 30
};

console.log(person.hasOwnProperty("name")); // true
console.log(person.hasOwnProperty("job")); // false

const person = {
  name: "Bob",
  age: 25
};
console.log("name" in person);  // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const car = {
  brand: "Toyota",
  model: "Corolla",
  year: 2020
};

console.log(car.brand !== undefined); // true
console.log(car.color !== undefined); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, we check if car.brand and car.color are not undefined. This works because accessing a non-existent property on an object returns undefined. However, this method can give false negatives if a property explicitly has the value undefined.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Do You Work with Accessing Properties from Nested Objects and Arrays in Objects?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: "Alice",
  age: 30,
  contact: {
    email: "alice@example.com",
    phone: {
      home: "123-456-7890",
      work: "098-765-4321"
    }
  }
};

console.log(person.contact.phone.work); // "098-765-4321"
console.log(person['contact']['phone']['work']); // "098-765-4321"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let’s take a look at how we can access data where one of the object properties has the value of an array. Here is a modified person object that includes an array of addresses:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
  name: "Alice",
  age: 30,
  addresses: [
    { type: "home", street: "123 Main St", city: "Anytown" },
    { type: "work", street: "456 Market St", city: "Workville" }
  ]
};

console.log(person.addresses[1].city); // "Workville"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Is the Difference Between Primitive and Non-Primitive Data Types?
&lt;/h2&gt;

&lt;p&gt;Primitive data types are the simplest form of data in JavaScript. They include numbers, strings, booleans, null, undefined, and symbols. These types are called "primitive" because they represent single values and are not objects.&lt;/p&gt;

&lt;p&gt;Primitive values are immutable, which means once they are created, their value cannot be changed. However, you can reassign a new value to the variable. Here's an example of working with primitive data types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;et num1 = 5;
let num2 = num1;
num1 = 10;

console.log(num2); // 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When you create a variable with a non-primitive value, what's stored in the variable is actually a reference to the location in memory where the object is stored, not the object itself. This leads to some important differences in behavior. Here's an example with non-primitive types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalPerson = { name: "John", age: 30 };
const copiedPerson = originalPerson;

originalPerson.age = 31;

console.log(copiedPerson.age); // 31
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is known as shallow copying by reference. &lt;/p&gt;

&lt;h2&gt;
  
  
  What Is the Difference Between Functions and Object Methods?
&lt;/h2&gt;

&lt;p&gt;Object methods, on the other hand, are functions that are associated with an object. They are defined as properties of an object and can access and manipulate the object's data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {
    name: "Bob",
    age: 30,
    sayHello: function() {
        return "Hello, my name is " + this.name;
    }
};

console.log(person.sayHello()); // "Hello, my name is Bob"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A difference between functions and methods is how they are invoked. Functions are called by their name, while methods are called using dot notation on the object they belong to. For example, we call the greet function as greet("Alice"), but we call the sayHello method as person.sayHello().&lt;/p&gt;

&lt;h2&gt;
  
  
  What Is JSON, and How Do You Access Values Using Bracket and Dot Notation?
&lt;/h2&gt;

&lt;p&gt;JSON stands for JavaScript Object Notation. Since JSON is language-independent, you can easily send JSON data from a Java application to a Python application, or from a JavaScript application to a C# application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "Alice",
  "age": 30,
  "isStudent": false,
  "list of courses": ["Mathematics", "Physics", "Computer Science"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each key must be wrapped in double quotes, otherwise you will get an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Do JSON.parse() and JSON.stringify() Work?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
  name: "John",
  age: 30,
  isAdmin: true
};

const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"John","age":30,"isAdmin":true}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The JSON.stringify() method also accepts an optional parameter called a replacer, which can be a function or an array. Here is an example of using an array for the optional replacer parameter:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};

// result: {"firstName":"Jessica","country":"USA"}
console.log(JSON.stringify(developerObj, ["firstName", "country"]));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replacer as function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const product = {
    name: "Телефон",
    price: 1000,
    currency: "USD",
    createdAt: new Date('2023-01-15')
};

const productJSON = JSON.stringify(product, function(key, value) {
    // Преобразуем даты в читаемый формат
    if (value instanceof Date) {
        return value.toISOString().split('T')[0]; // "2023-01-15"
    }

    // Исключаем поле currency
    if (key === 'currency') {
        return undefined; // исключаем из результата
    }

    return value; // все остальное оставляем как есть
});

console.log(productJSON);
// {"name":"Телефон","price":1000,"createdAt":"2023-01-15"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another optional parameter for the JSON.stringify() method would be the spacer parameter. This allows you to control the spacing for the stringified result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};

console.log(JSON.stringify(developerObj, null, 2));

/* result
{
  "firstName": "Jessica",
  "isAwesome": true,
  "isMusician": true,
  "country": "USA"
}
*/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Is the Optional Chaining Operator, and How Does It Work?
&lt;/h2&gt;

&lt;p&gt;The optional chaining operator is most useful when you're not sure if a property or method exists. It helps prevent errors and makes your code more robust.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
  name: "John",
  profile: {
    email: "john@example.com",
    address: {
      street: "123 Main St",
      city: "Somewhere"
    }
  }
};

console.log(user.profile?.address?.street); // "123 Main St"
console.log(user.profile?.phone?.number);   // undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Working with arrays [JS]</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Fri, 31 Oct 2025 12:06:05 +0000</pubDate>
      <link>https://forem.com/0netheball/function-in-javascript-2m3e</link>
      <guid>https://forem.com/0netheball/function-in-javascript-2m3e</guid>
      <description>&lt;h2&gt;
  
  
  Function methods
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;.pop()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The pop() method removes the last element from an array and returns that element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "orange"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;.unshift()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Adds one or more elements to the beginning of an array and returns its new length. It works similarly to push().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [2, 3];
let newLength = numbers.unshift(1);
console.log(numbers); // [1, 2, 3]
console.log(newLength); // 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;.shift()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Removes the first element from an array and returns that element. It's similar to pop().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let colors = ["red", "green", "blue"];
let firstColor = colors.shift();
console.log(colors); // ["green", "blue"]
console.log(firstColor); // "red"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  One-Dimensional and Two-Dimensional Arrays
&lt;/h2&gt;

&lt;p&gt;A one-dimensional array, often called an array, is like a single row of boxes.&lt;/p&gt;

&lt;p&gt;Two-dimensional array is essentially an array of arrays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let chessboard = [
    ["R", "N", "B", "Q", "K", "B", "N", "R"],
    ["P", "P", "P", "P", "P", "P", "P", "P"],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    [" ", " ", " ", " ", " ", " ", " ", " "],
    ["p", "p", "p", "p", "p", "p", "p", "p"],
    ["r", "n", "b", "q", "k", "b", "n", "r"]
];

console.log(chessboard[0][3]); // Outputs: "Q"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Array Destructuring
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange"];

let [first, second, third] = fruits;

console.log(first);  // "apple"
console.log(second); // "banana"
console.log(third);  // "orange"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Array destructuring also allows you to skip elements you're not interested in by using commas. For instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let colors = ["red", "green", "blue", "yellow"];
let [firstColor, , thirdColor] = colors;

console.log(firstColor); // Output: "red"
console.log(thirdColor); // Output: "blue"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another powerful feature of array destructuring is the ability to use default values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2];
let [a, b, c = 3] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's discuss the rest syntax, denoted by three dots (...). It allows you to capture the remaining elements of an array that haven’t been destructured into a new array.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The rest syntax must be the last element in the destructuring pattern.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let [first, second, ...rest] = fruits;

console.log(first);  // "apple"
console.log(second); // "banana"
console.log(rest);   // ["orange", "mango", "kiwi"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Can You Use String and Array Methods to Reverse a String?
&lt;/h2&gt;

&lt;p&gt;Steps&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Splitting the string into an array of characters.&lt;/li&gt;
&lt;li&gt;Reversing the array.&lt;/li&gt;
&lt;li&gt;Joining the characters back into a string.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first step in reversing a string is to convert it into an array of individual characters. We can do this using the split() method.&lt;br&gt;
*An empty string (""), which splits the string into individual characters.&lt;br&gt;
*A single space (" "), which splits the string wherever spaces occur.&lt;br&gt;
*A dash ("-"), which splits the string at each dash.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "hello";
let charArray = str.split("");
console.log(charArray); // ["h", "e", "l", "l", "o"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reverse() method is an array method that reverses an array in place. This means it modifies the original array rather than creating a new one.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let charArray = ["h", "e", "l", "l", "o"];
charArray.reverse();
console.log(charArray); // ["o", "l", "l", "e", "h"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can accomplish this using the join() method. The join() method creates and returns a new string by concatenating all of the elements in an array, separated by a specified separator string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let reversedArray = ["o", "l", "l", "e", "h"];
let reversedString = reversedArray.join("");
console.log(reversedString); // "olleh"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember that strings in JavaScript are immutable, which means you can't directly reverse a string by modifying it. That's why we need to convert it to an array, reverse the array, and then convert it back to a string. This combination of string and array methods provides a powerful and flexible way to manipulate strings in JavaScript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "coding";
let reversed = str.split("").reverse().join("");
console.log(reversed);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Do You Get the Index for an Element in an Array Using the indexOf Method?
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange", "banana"];
let index = fruits.indexOf("banana");
console.log(index); // 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the element you're searching for is not found in the array, indexOf() returns -1.&lt;/p&gt;

&lt;p&gt;If you want to start looking for an item after a specific index number, then you can pass a second argument like in this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let colors = ["red", "green", "blue", "yellow", "green"];
let index = colors.indexOf("green", 3);
console.log(index); // 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the search does not start from the start of an array, rather it starts from the index number 3 which is yellow and gets the output of 4.&lt;/p&gt;

&lt;p&gt;In order to find the proper object in an array use findIndex() method&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const userIndex = users.findIndex(user =&amp;gt; user.name === 'Dave');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Do You Add and Remove Elements from the Middle of an Array?
&lt;/h2&gt;

&lt;p&gt;**&lt;em&gt;.splice()&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The return value for the splice() method will be an array of the items removed from the array. If nothing was removed, then an empty array will be returned.  This method will mutate the original array, modifying it in place rather than creating a new array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;array.splice(startIndex, itemsToRemove, item1, item2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;startIndex specifies the index at which to begin modifying the array, while itemsToRemove is an optional parameter indicating how many elements to remove. If itemsToRemove is omitted, splice() will remove all elements from startIndex to the end of the array. The subsequent parameters (item1, item2, and so on) are the elements to be added to the array, beginning at the start index.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let removed = fruits.splice(2, 2);

console.log(fruits);  // ["apple", "banana", "kiwi"]
console.log(removed); // ["orange", "mango"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, splice(2, 2) starts at index 2 and removes 2 elements.&lt;/p&gt;

&lt;p&gt;Now, let's look at how to add elements to the middle of an array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let colors = ["red", "green", "blue"];
colors.splice(1, 0, "yellow", "purple");

console.log(colors); // ["red", "yellow", "purple", "green", "blue"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, splice(1, 0, "yellow", "purple") starts at index 1, removes 0 elements, and inserts yellow and purple. The second parameter (0) means no elements are removed before insertion. You can also use splice() to simultaneously remove and add elements:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2, 6, 7, 8);

console.log(numbers); // [1, 6, 7, 8, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, splice(1, 2, 6, 7, 8) starts at index 1, removes 2 elements (2 and 3), and inserts 6, 7, and 8. &lt;/p&gt;

&lt;p&gt;One common use case for splice() is to remove a single element from an array when you know its index:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange", "mango"];
let indexToRemove = fruits.indexOf("orange");
if (indexToRemove !== -1) {
    fruits.splice(indexToRemove, 1);
}

console.log(fruits); // ["apple", "banana", "mango"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can also use splice() to clear an array by removing all elements:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let array = [1, 2, 3, 4, 5];
array.splice(0);

console.log(array); // []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How Can You Check if an Array Contains a Certain Value?
&lt;/h2&gt;

&lt;p&gt;In JavaScript, the includes() method is a simple and efficient way to check if an array contains a specific value. This method returns a boolean value: true if the array contains the specified element, and false otherwise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let fruits = ["apple", "banana", "orange", "mango"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape"));  // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The includes() method can also accept an optional second parameter that specifies the position in the array to start the search. This is useful if you want to check for an element's presence in a specific part of the array. Here's how you can use this feature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [10, 20, 30, 40, 50, 30, 60];
console.log(numbers.includes(30, 3)); // true
console.log(numbers.includes(30, 4)); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's worth noting that includes() uses the strict equality comparison (===), which means it can distinguish between different types. For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mixedArray = [1, "2", 3, "4", 5];
console.log(mixedArray.includes(2));  // false
console.log(mixedArray.includes("2")); // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the number 2 and the string "2" are considered different data types. So, the first console.log will return false, while the second console.log will return true.&lt;/p&gt;

&lt;p&gt;What Is a Shallow Copy of an Array, and What Are Some Ways to Create These Copies?&lt;/p&gt;

&lt;p&gt;If the array only contains primitive values like numbers or strings, the new array is completely separate. But if the array contains other arrays inside it, both the original and the copy have references to the same inner arrays. This means that if you change something inside a shared inner array, you will see that change in both arrays.&lt;/p&gt;

&lt;p&gt;There are several methods for creating shallow copies of arrays, and we'll explore some of the most common ones: concat(), slice(), and the spread operator.&lt;/p&gt;

&lt;p&gt;Let's start with the concat() method. This method creates a new array by merging two or more arrays. When used with a single array, it effectively creates a shallow copy. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalArray = [1, 2, 3];
const copyArray = [].concat(originalArray);

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are using the concat() method to concatenate an empty array to the originalArray. This will create a new array that is a shallow copy of originalArray.&lt;/p&gt;

&lt;p&gt;The copyArray contains the same elements as originalArray, but it is a different array object, which is why the strict equality check (===) returns false.&lt;/p&gt;

&lt;p&gt;Another method to create a shallow copy is the slice() method. When called without arguments, slice() returns a shallow copy of the entire array. Here's how it works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalArray = [1, 2, 3];
const copyArray = originalArray.slice();

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, originalArray.slice() creates a new array that is a shallow copy of originalArray. Again, the copyArray contains the same elements but is a different array object.&lt;/p&gt;

&lt;p&gt;The spread operator (...), introduced in ES6, provides another concise way to create shallow copies of arrays. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const originalArray = [1, 2, 3];
const copyArray = [...originalArray];

console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The spread operator (...) spreads the elements of originalArray into a new array, effectively creating a shallow copy. It's important to note that all these methods create new array objects, which means you can modify the copy without affecting the original array. &lt;/p&gt;

</description>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to use JWTokens properly</title>
      <dc:creator>Whoissosick</dc:creator>
      <pubDate>Wed, 29 Oct 2025 08:16:39 +0000</pubDate>
      <link>https://forem.com/0netheball/how-to-use-jwtokens-properly-21cg</link>
      <guid>https://forem.com/0netheball/how-to-use-jwtokens-properly-21cg</guid>
      <description>&lt;h2&gt;
  
  
  User registration
&lt;/h2&gt;

&lt;p&gt;First thing first we need to register a user&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Destucturing the received username &amp;amp; password from request. &lt;/li&gt;
&lt;li&gt;Check for duplicate username in the db&lt;/li&gt;
&lt;li&gt;Encrypt the password using encrypt package&lt;/li&gt;
&lt;li&gt;Create and save new user into db&lt;/li&gt;
&lt;li&gt;Send proper status and make error handling
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { username, password } = req.body; 
  if (!username || !password) return res.status(400).json({ "message": 'Username and password are required.'});

  const duplicate = await User.findOne({ username: username }).exec();
  if (duplicate) return res.sendStatus(409); // Conflict

  try {
    // encrypt the password 
    const hashedPassword = await bcrypt.hash(password, 10); 

    // create and store the new user
    const result = await User.create({ 
      "username": username, 
      "password": hashedPassword 
    }); 

    res.status(201).json({ 'success': `New user ${username} created`});
  } catch (err) {
    res.status(500).json({ "message": err.message });
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  User authorization
&lt;/h2&gt;

&lt;p&gt;After we registrate user, we also need to get username/password from request.body and cookies (content from it) &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find user by username in db
1.1 If user is not found =&amp;gt; 401 | Unathorized &lt;/li&gt;
&lt;li&gt;Compare password using bcrypt package&lt;/li&gt;
&lt;li&gt;Create AT (Access Token) &amp;amp; RT (Refresh Token). Tokens contains (payload, SECRET, options). &lt;/li&gt;
&lt;li&gt;If user came in without RT inside cookies, array of RTs stays unchanged, if cookies contains something we save array without that RT. (This supports multiple devices). &lt;/li&gt;
&lt;li&gt;Clear all cookie before we give new tokens &lt;/li&gt;
&lt;li&gt;Update array of tokens inside db&lt;/li&gt;
&lt;li&gt;User gets AT &amp;amp; RT
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const cookies = req.cookies; 
  const { username, password } = req.body;
  if (!username || !password) return res.status(400).json({ "message": 'Username and password are required' });

  const foundUser = await User.findOne({ username: username }).exec();
  if (!foundUser) return res.sendStatus(401);

  const matchPassword = await bcrypt.compare(password, foundUser.password);
  if (matchPassword) {
    const roles = Object.values(foundUser.roles);

    const accessToken = jwt.sign(
      {
        "UserInfo": {
          "username": foundUser.username,
          "roles": roles
        }
      },
      process.env.ACCESS_TOKEN_SECRET,
      { expiresIn: '30s' }
    );
    const newRefreshToken = jwt.sign(
      { "username": foundUser.username },
      process.env.REFRESH_TOKEN_SECRET,
      { expiresIn: '1d' }
    );

    const newRefreshTokenArray = 
      !cookies?.jwt
        ? foundUser.refreshToken
        : foundUser.refreshToken.filter(rt =&amp;gt; rt !== cookies.jwt);
    if (cookies?.jwt) {
      res.clearCookie('jwt', { httpOnly: true, sameSite: 'None', secure: true });
    }

    foundUser.refreshToken = [...newRefreshTokenArray, newRefreshToken];
    const result = await foundUser.save();

    res.cookie('jwt', newRefreshToken, { httpOnly: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 });
    res.json({ accessToken });
  } else {
    res.sendStatus(401);
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Update AT by RT
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Clear user cookie&lt;/li&gt;
&lt;li&gt;Find user by RT in db &lt;/li&gt;
&lt;li&gt;If user is not found in db, user is hacked. We intentionally clear array of tokens. &lt;/li&gt;
&lt;li&gt;Create new array without received RT from cookie&lt;/li&gt;
&lt;li&gt;Verify RT and give new tokens, then save it into db&lt;/li&gt;
&lt;li&gt;Send cookie and result
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cookies = req.cookies;
  if (!cookies?.jwt) return res.sendStatus(401);

  const refreshToken = cookies.jwt;
  res.clearCookie('jwt', { httpOnly: true, sameSite: 'None', secure: true });

  const foundUser = await User.findOne({ refreshToken: refreshToken }).exec();

  if (!foundUser) {
    jwt.verify(
      refreshToken,
      process.env.REFRESH_TOKEN_SECRET,
      async (err, decoded) =&amp;gt; {
        if (err) return res.sendStatus(403);
        const hackedUser = await User.findOne({ username: decoded.username }).exec();
        hackedUser.refreshToken = [];
        const result = await hackedUser.save();
        console.log(result);
      }
    );
    return res.sendStatus(403) // Forbidden
  };

  const newRefreshTokenArray = foundUser.refreshToken.filter(rt =&amp;gt; rt !== refreshToken);

  jwt.verify(
    refreshToken,
    process.env.REFRESH_TOKEN_SECRET,
    async (err, decoded) =&amp;gt; {
      if (err) { // if RT has been expired 
        foundUser.refreshToken = [...newRefreshTokenArray];
        const result = await foundUser.save();
        return res.sendStatus(403);
      }
      if (err || foundUser.username !== decoded.username) return res.sendStatus(403);

      const roles = Object.values(foundUser.roles);

      const accessToken = jwt.sign(
        {
          "UserInfo": {
            "username": decoded.username,
            "roles": roles
          }
        },
        process.env.ACCESS_TOKEN_SECRET,
        { expiresIn: '30s' },
      );

      const newRefreshToken = jwt.sign(
        { "username": foundUser.username },
        process.env.REFRESH_TOKEN_SECRET,
        { expiresIn: '1d' }
      );

      foundUser.refreshToken = [...newRefreshTokenArray, newRefreshToken];
      const result = await foundUser.save();

      res.cookie('jwt', newRefreshToken, { httpOnly: true, sameSite: 'None', maxAge: 24 * 60 * 60 * 1000 });
      res.json({ accessToken });
    }
  );
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  User logout
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Get RT from cookies &lt;/li&gt;
&lt;li&gt;Find user by RT inside db. (if user is not found, clear cookie)&lt;/li&gt;
&lt;li&gt;Delete RT in db&lt;/li&gt;
&lt;li&gt;Clear cookie
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const cookies = req.cookies; 
  if (!cookies?.jwt) return res.sendStatus(204); 

  const refreshToken = cookies.jwt; 

  const foundUser = await User.findOne({refreshToken: refreshToken}).exec(); 
  if (!foundUser) {
    res.clearCookie('jwt', { 
      httpOnly: true, 
      sameSite: 'None', 
      secure: true 
    });
    return res.sendStatus(204);
  }

  foundUser.refreshToken = foundUser.refreshToken.filter(rt =&amp;gt; rt !== refreshToken);
  const result = await foundUser.save();
  console.log(result);

  res.clearCookie('jwt', { httpOnly: true, sameSite: 'None', secure: true }); // secure: true - only serves on https (it's on production)
  res.sendStatus(204);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>node</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>security</category>
    </item>
  </channel>
</rss>
