Understand and Use JavaScript's .forEach() vs. jQuery's .each()

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

There are two functions to deal with an array on the client-side – JavaScript's .forEach() and jQuery's .each(). Here, I will teach you how to use both of these methods with some sample code.

Your knowledge of JavaScript and jQuery is incomplete if you don't know how to loop with .forEach() and .each() methods. This tutorial helps you to quickly master JavaScript .forEach() & jQuery .each() in 2 minute time.

There are two methods to deal with an array on client-side – JavaScript .forEach() and jQuery .each(). Here, I will teach you how to use both of these methods in different scenarios.

Defination of these 2 methods

a. JavaScript .forEach() Method

The .forEach() method of JavaScript executes a given function once for each element of the array.

For example -

var arr = ['a', 'b', 'c'];    
arr.forEach(function(element) {  
    console.log(element);  
});  

The above JavaScript code will print – ‘a’, ‘b’, & ‘c’ in the console window.

b. jQuery .each() Method

jQuery has it’s own method called jQuery Each method and it is used to loop over arrays, array of object and matched elements of the DOM. See the below code:

var arr = ['a', 'b', 'c'];  
$.each(arr , function (index, value){  
  console.log(arr);   
});  

The above jQuery code will print – ‘a’, ‘b’, & ‘c’ in the console window.

Looping through DOM elements

a. JavaScript .forEach() Method

Suppose you want to extract all the anchor tags from the web page, and then loop through each of them. In that case first you have to get all the anchors using document.getElementsByTagName("a") and then convert it into an array. This is because JavaScript .forEach() method loops only through an array.

See the below code:

var links = document.getElementsByTagName("a");    
var Arr = Array.from(links);    
Arr.forEach(someFunction);    
    
function someFunction(currentValue) {    
    console.log(currentValue);    
}    

I used Array.from() method to convert to an array.

b. jQuery .each() Method

In case of .each() method you simply loop through all the anchor tags, like shown in the below code, as jQuery Each method can loop through arrays, array of objects and matched element of the DOM. So you don’t have to do the conversion to an array like JavaScript .forEach() method.

See the below code:

$("a").each(function (index, value) {   
  console.log($(this).attr("href"));   
});  

Clearly you can see in this case the lines of codes are very less than compared to .forEach() method of JavaScript.

Which one you should choose?

Case 1: DOM Manipulations

When working with DOM elements the jQuery Each method has a great advantage because it removes a lot of code lines. So prefer this method during DOM manipulations.

Case 2: Website is using jQuery from before

If your website is already using jQuery then you should use jQuery Each method because this will bring code consistency in your project.

In all other cases use JavaScript .forEach() method.

Conclusion

Both of these above methods are very good and they make the codes easy to understand. I would recommend every web developer to know both of these methods.

Thank you for reading.

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? jQuery vs vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? Find out in this video!

JavaScript ES6 Classes

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

Classes are a fundamental part of object oriented programming (OOP). They define “blueprints” for real-world object modeling and organize code into logical, reusable parts. Classes share many similarities with regular objects. They have their own constructor functions, properties, and methods. In this tutorial, we’ll demonstrate how to create and work with ES6 classes.

Creating a class

You can create a class using the class keyword:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }

}



let person = new Person("Sam", 30)



person.name

//returns 'Sam'



person.age

//returns 30

Notice how we define our Person class with a constructor() function taking two arguments name and age. Using the this keyword, we set the name and age properties based on the provided arguments. Remember that the constructor function is called whenever we create a new instance of the Person class.

Similar to objects, we can read class properties using dot notation so that person.name returns Sam.

Defining properties and methods

You can define properties and methods for a class the same way you do for regular objects:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



let person = new Person('Tim', 40)



person.sayName()

//logs 'My name is Tim'



person.location = 'London'



person.location

//returns 'London'

Notice how we define a sayName() function within our Person class definition. Once we create a new instance of Person, we can call the method via person.sayName().

You can also add properties and methods on the fly. You’ll notice that while the location property isn’t defined in our constructor function, we can still dynamically add it later on for the person instance. Remember that if we created a new instance of Person, it would not have a location property because that property is not defined in the class definition. Only properties and methods that we explicitly define will be shared by all instances of the class.

Static functions

You can use the static keyword to make class methods static. A static method acts on the class itself, not on instances of the class:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



Person.describe()

//logs 'This is a person.'

Notice how static methods operate on the class itself and not an instance of the class. We didn’t have to create a new Person to call the static method.

Static methods are useful for common or shared class functionality. In this case, the describe() method is used to describe what the Person class is. It will apply to every instance of Person. This is why we make it a static method.

Class Inheritance

Inheritance allows you to create new classes based off existing ones. These new classes “inherit” the methods and properties of their parent. They can also override or extend the parent:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }


  static describe(){

    console.log("This is a person.")

  }


  sayName() {

    console.log("My name is " + this.name)

  }

}



class Programmer extends Person {

  sayName(){

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



averageJoe.sayName()


//logs 'My name is Todd'


programmer.sayName()


//logs 'My name is Sam and I am a programmer!'

Using the extends keyword, we can create a new class sharing the same characteristics as Person. Notice how we override the sayName() method with a new definition for the Programmer class. Apart from overriding this method, everything else remains the same for both Person and Programmer.

Using super

The super keyword allows a child class to invoke parent class properties and methods.

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}





class Programmer extends Person {

  sayName(){

    super.sayName()

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



programmer.sayName()



//logs 'My name is Sam'

//logs 'My name is Sam and I am a programmer!'

Notice how we call super.sayName() in the Programmer implementation of sayName(). While this invokes the parent implementation of super.sayName(), the name property still references the Programmer class.

Conclusion

Classes facilitate object oriented programming in JavaScript. While regular objects provide similar functionality, classes provide the extra advantage of inheritance and static methods.

Linked Lists in JavaScript With ES6

Linked Lists in JavaScript With ES6

Linked Lists in JavaScript with ES6.This series is about data structure implementation in JavaScript using the ES6 specification.. Let's see how to make a singly linked list in Javascript… ... list in Javascript. We'll be using ES6 syntax throughout.

This is a continuation of a previous piece where we digested all surrounding concepts, pros and cons, Big O time complexity, real use cases, linked-list mainly operations, and all that kind of theory. If you have not read it yet, I recommend you read it first.

This series is about data structure implementation in JavaScript using the ES6 specification.

The aim of this second piece is to walk through the implementation of a linked list. Actually, the two pieces enclose a linked list itself since the prior piece is pointing to this one.

The Node Class

In the next code, we’re going to define our Node class with its constructor. Remember, the node is the basic building block to store the data and the next pointer.

This class will have to handle the node creation. Every time the class is instantiated, the constructor has the responsibility to initialize the two properties: data and next.


Node Class

Now the challenge is to create the next four nodes (just nodes creation, not how to connect them).


Linked List

Basically, we have to instantiate the Node class four times in order to create the four nodes.


Creating Nodes

At this point, we don’t care about the second parameter. Why? Because at this moment, we’re just learning how to create the node without having to worry about how they’ll be connecting together.

How Can We Connect the Nodes?

In the prior code, we just created nodes independently. Now is time to learn how to connect them to form the linked list.


Connecting nodes

We have defined the Node class. Next is to define a new class that will handle the nextpointer property and the main operations in the linked list. Let’s create the LinkedList class.


Linked List Class

In the above code, we have just defined a class called LinkedList with its constructor. This has the work of initializing the headproperty, to store the first node,and size, to keep track of the size of the linked list.

Next is to offer the ability to insert to the head, to the tail, or at any random position in the list.

Inserting Into the Head


Inserting to head

We have just created a simple method to add nodes to the head of the linked list. We are passing down to it the dataparameter and setting a value for the this.head property creating a new instance of the Node class.

Let’s do some tests of its implementation so far and see the results.

The output will be:


Linked list output

Inserting at the Tail

We just learned how to add nodes to the head. It’s time to know how to add nodes to the tail.


Inserting at the tail

In the aboveinsertToTail function, we are passing down the data parameter, and then we created a new instance of the Node class. After that, we are checking if the head is empty. If so, the head itself will be set to the new node we have just after created. Otherwise, set the tail with the head and then loop through the linked list to find the tail and update the tail’s next pointer.

Inserting at Random Position

Finally, we are going to see how to insert a new node in the linked list at a given random position. For this, we have to traverse the list until we find the desired position.

Inserting at a given random position

Now we are going to test this function using the next tests.

The output will be as below. As you can see, at the given index, the node (600) was added at the second index of the list.

The Whole Code

class Node {
  constructor(data, next = null) {
    this.data = data;
    this.next = next;
  }
}

//Let's create four nodes
let node1 = new Node(5);
let node2 = new Node(10);
let node3 = new Node(20);
let node4 = new Node(1);

//connecting nodes
node1.next = node2;
node2.next = node3;
node3.next = node4;

//LinkedList Class
class LinkedList {
  constructor() {
    this.head = null; //first node of the Linked List
    this.size = 0; //Track size of the linked list
  }
  //Insert to head
  insertToHead(data) {
    this.head = new Node(data, this.head);
    this.size++;
  }

  //Insert into the tail
  insertToTail(data) {
    const node = new Node(data);
    let tail = null;
    //if empty, make it head
    if (!this.head) {
      this.head = node;
    } else {
      tail = this.head;
      while (tail.next) {
        tail = tail.next;
      }
      tail.next = node;
    }
    this.size++;
  }

  //Insert at random position
  insertAt(data, index) {
    //if it's empty
    if (!this.head) {
      this.head = new Node(data);
      return;
    }
    //if it needs add to the front of the list
    if (index === 0) {
      this.insertToHead(data); //reuse insertToHead function
      return;
    }
    let node = new Node(data);
    let current, previous;
    let count = 0;
    // current will be first
    current = this.head;
    while (count < index) {
      previous = current;
      count++;
      current = current.next;
    }
    node.next = current;
    previous.next = node;
    this.size++;
  }
}

const linkedList = new LinkedList();
linkedList.insertToHead(100);
linkedList.insertToHead(200);
linkedList.insertToHead(300);
linkedList.insertToTail(400);
linkedList.insertAt(600, 2);

console.table(linkedList);

LinkedList.js

I hope you have gained more knowledge about data structure and especially with Linked list. That’s all for now.

Thanks for reading!