<?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>DEV Community: Mary Okosun</title>
    <description>The latest articles on DEV Community by Mary Okosun (@marienoir).</description>
    <link>https://dev.to/marienoir</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%2F803973%2F0c3cadf9-8cbe-4440-b923-b86945c9b901.jpeg</url>
      <title>DEV Community: Mary Okosun</title>
      <link>https://dev.to/marienoir</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/marienoir"/>
    <language>en</language>
    <item>
      <title>Understanding Relationships in TypeORM</title>
      <dc:creator>Mary Okosun</dc:creator>
      <pubDate>Fri, 13 Jan 2023 09:17:52 +0000</pubDate>
      <link>https://dev.to/marienoir/understanding-relationships-in-typeorm-4873</link>
      <guid>https://dev.to/marienoir/understanding-relationships-in-typeorm-4873</guid>
      <description>&lt;h2&gt;
  
  
  What is TypeORM?
&lt;/h2&gt;

&lt;p&gt;Understanding how relationships works in database management is a concept that is important as a software engineer.&lt;br&gt;
In this article, we would learn what typeORM is, how relationships work in typeORM and the importance of relationships in database management.&lt;/p&gt;

&lt;p&gt;If we are creating a typescript application and need a database for backend services, we will need an ORM (Object Relational Mapper) to connect our application to the database. &lt;br&gt;
&lt;strong&gt;Object&lt;/strong&gt; denotes the model in your application, &lt;strong&gt;Relational&lt;/strong&gt; denotes the relationship between tables in a Relational Database Management System(RDMS), and &lt;strong&gt;Mapping&lt;/strong&gt; denotes the act of connecting the model and our tables.&lt;/p&gt;

&lt;p&gt;TypeORM is a TypeScript ORM (object-relational mapper) library that simplifies the integration of your TypeScript application with a relational database. MySQL, SQLite, Postgres, MS SQL Server, and a variety of other relational databases are supported by this library.&lt;/p&gt;
&lt;h2&gt;
  
  
  Relationships in TypeORM
&lt;/h2&gt;

&lt;p&gt;In TypeORM, relationships exist between tables in the database. When one of the tables has a foreign key that references the primary key of the other table, a relationship exists. This feature enhances the power and efficiency with which relational databases store information.&lt;/p&gt;

&lt;p&gt;TypeORM enables entities to be related to one another and, as a result, to database tables.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Entities are building blocks of a database.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In TypeORM, an Entity is a class that defines a collection of fields or columns as well as database operations. It is made up of columns and relationships.&lt;/p&gt;

&lt;p&gt;In general, relationships can be divided into four types.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;One-to-one relationship&lt;/li&gt;
&lt;li&gt;One-to-many relationship&lt;/li&gt;
&lt;li&gt;Many-to-one relationship&lt;/li&gt;
&lt;li&gt;Many-to-many relationship&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  One-to-one relationship
&lt;/h2&gt;

&lt;p&gt;When an instance of one table, say Table A, contains an instance of another table, say Table B, a one-to-one relationship is formed. For instance, we could use a user's post on a website. The requirement here is that a user can only make one post.&lt;/p&gt;

&lt;p&gt;We'd need two tables here: User table and Post table. The &lt;strong&gt;User&lt;/strong&gt; table will contain the user's information, and the &lt;strong&gt;Post&lt;/strong&gt; table will contain the post information as well as the user information who made the post on the site.&lt;/p&gt;

&lt;p&gt;To accomplish this, we'll need two entities: User entity and Post entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//User.entity.ts
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity() 
export class User {
   @PrimaryGeneratedColumn() 
   id: number; 

   @Column() 
   name: string; 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9nrf6ox2rkwst8sbd4gk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9nrf6ox2rkwst8sbd4gk.png" alt="One-to-one relationship" width="596" height="46"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The User entity has an &lt;code&gt;id&lt;/code&gt; column which is a primarily generated column with an auto-increment value that is automatically generated. It also has a &lt;code&gt;name&lt;/code&gt; column that is string-based.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Post.entity.ts
import {Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn} from "typeorm"; 
import {User} from "./User.entity"; 

@Entity() 
export class Post { 
   @PrimaryGeneratedColumn() 
   id: number; 

   @Column() 
   post: string; 

   @OneToOne(type =&amp;gt; User) 
   @JoinColumn() 
   user: User;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwk9of0wsknlb9m78umka.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwk9of0wsknlb9m78umka.png" alt="One-to-one relationship" width="724" height="48"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Post entity has an &lt;code&gt;id&lt;/code&gt; which is a primarily generated column and a string typed column called &lt;code&gt;post&lt;/code&gt;. &lt;br&gt;
It has a third column that is joined to the User entity via the &lt;code&gt;@JoinColumn&lt;/code&gt; decorator.&lt;br&gt;
A one-to-one relationship with the type directed to the User entity is established in this column.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;@JoinColumn&lt;/code&gt; specifies which side of the relation contains the join column with a foreign key. It allows you to customise the names of the join column and the referenced column.&lt;/p&gt;

&lt;p&gt;When we use &lt;code&gt;@JoinColumn&lt;/code&gt; on a column, the database creates a column by default named &lt;em&gt;propertyName + referencedColumnName&lt;/em&gt;. In the example used above, the property name is &lt;strong&gt;user&lt;/strong&gt; while the referenced column name is by default &lt;strong&gt;id&lt;/strong&gt; of the User entity, therefore a new column called &lt;code&gt;userId&lt;/code&gt; is created as shown in the result above.&lt;/p&gt;

&lt;p&gt;However, the column name can be explicitly set instead of the default naming convention by using&lt;br&gt;
 &lt;code&gt;@JoinColumn({  name: "user_post_id" })&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Post.entity.ts 
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  OneToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './User.entity';

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  post: string;

  @OneToOne((type) =&amp;gt; User)
  @JoinColumn({  name: "user_post_id" })
  user: User;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code snippet above, the &lt;code&gt;@JoinColumn&lt;/code&gt; had a name property added, therefore the new column created will be &lt;code&gt;user_post_id&lt;/code&gt;instead of the default name of &lt;code&gt;userId&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fify17wfk6ry7o1k684zn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fify17wfk6ry7o1k684zn.png" alt="@JoinColumn" width="800" height="46"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;@JoinColumn&lt;/code&gt; always refers to the primary column of the related entity by default.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If we want to create a relationship with other columns of the related entity, we can do so as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//User.entity.ts 
import { Entity, PrimaryColumn, Column } from 'typeorm';

@Entity()
export class User {
  @Column()
  id: number;

  @PrimaryColumn()
  name: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This entity is quite different from the one created above in that the &lt;code&gt;name&lt;/code&gt; is the primary column and not the &lt;code&gt;id&lt;/code&gt; column. This is necessary because we intend to reference &lt;code&gt;name&lt;/code&gt; column in the &lt;code&gt;JoinColumn&lt;/code&gt; for Post entity below and it has been earlier stated that the &lt;code&gt;@JoinColumn&lt;/code&gt; can only reference a primary column.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Post.entity.ts 
import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  OneToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './User.entity;

@Entity()
export class Post {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  post: string;

  @OneToOne((type) =&amp;gt; User)
  @JoinColumn({ referencedColumnName: 'name' })
  user: User;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fergmcib94juulpkxs8kk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fergmcib94juulpkxs8kk.png" alt="@JoinColumn" width="620" height="46"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  One-to-many relationship
&lt;/h2&gt;

&lt;p&gt;When one row in one table, say Table A, is linked to multiple rows in another table, say Table B, but only one row in Table B is linked to one row in Table A, a one-to-many relationship is formed.&lt;/p&gt;

&lt;p&gt;In the case of a Customer and an account entity, a customer can own multiple accounts, whereas an account can only be owned by one customer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Customer.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Account } from './Account.entity;

@Entity()
export class Customer {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(() =&amp;gt; Account, (account) =&amp;gt; account.customer)
  account: Account[];
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9uyd5ou5yx6mjhjf2k87.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9uyd5ou5yx6mjhjf2k87.png" alt="One-to-many relationship" width="450" height="54"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Customer entity has a name column and has a one-to-many relationship because one customer can have many account. We added &lt;code&gt;@OneToMany&lt;/code&gt; to the account property in the customer entity and specified Account as the target relation type.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It is important to note that the &lt;code&gt;@JoinColumn&lt;/code&gt; can be omitted in a many-to-one or one-to-many relationship.&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Account.entity.ts
import { Entity, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Customer } from './Customer.model';

@Entity()
export class Account {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() =&amp;gt; Customer, (customer) =&amp;gt; customer.account)
  customer: string;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0adi882302tipegh7hi8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0adi882302tipegh7hi8.png" alt="One-to-many relationship" width="422" height="48"&gt;&lt;/a&gt;&lt;br&gt;
The Account entity has a many-to-one relationship because multiple accounts could belong to one customer.&lt;br&gt;
We added &lt;code&gt;@ManyToOne&lt;/code&gt; to the customer property in the Account entity and specified Customer as the target relation type.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;@ManyToOne&lt;/code&gt; cannot exist without &lt;code&gt;@OneToMany&lt;/code&gt;as it is required if &lt;code&gt;@OneToMany&lt;/code&gt;needs to be used.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Many-to-one relationship
&lt;/h2&gt;

&lt;p&gt;This relationship is similar to a one-to-many relationship but from a different perspective.&lt;/p&gt;

&lt;p&gt;When multiple rows in one table are linked to a single row in another table, a many-to-one relationship is formed.&lt;/p&gt;

&lt;p&gt;Looking at a Customer and an Account entity, where a customer can own many accounts in a one-to-many relationship, it is also true that multiple accounts can belong to a single customer in a many-to-one relationship.&lt;/p&gt;

&lt;p&gt;Multiple entries in the account table can belong to the same row in the customer table.&lt;br&gt;
An example is quite similar to the one-to-many relationship explained above.&lt;/p&gt;
&lt;h2&gt;
  
  
  Many-to-many relationship
&lt;/h2&gt;

&lt;p&gt;When multiple rows in one table are linked to multiple rows in another table, a many-to-many relationship is formed.&lt;/p&gt;

&lt;p&gt;In a Customer and Product entity, for example, a customer can buy more than one product, and a product can be bought by more than one customer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Product.entity.ts 
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class Product {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnihrmqr0vjkv37hiibdl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnihrmqr0vjkv37hiibdl.png" alt="Many-to-many relationship" width="596" height="46"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Customer.entity.ts 
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"
import { Product } from "./Product.entity"

@Entity()
export class Customer {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() =&amp;gt; Product)
    @JoinTable()
    product: Product[]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The Customer and the Product entity are quite similar except the Many-to-many relationship built on the product column of the Customer table. This table is joined with the Product table using a &lt;code&gt;@JoinTable&lt;/code&gt; decorator. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;@JoinTable&lt;/code&gt; should be added to one of the entities, typically the owning entity.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Due to this decorator, a new table will be created with the default name as &lt;em&gt;table_tableProperty_referencedTable&lt;/em&gt;. &lt;br&gt;
In our example, this table will be created as &lt;code&gt;customer_product_product&lt;/code&gt;. In this new table, there are two columns which are &lt;code&gt;customerId&lt;/code&gt; and &lt;code&gt;productId&lt;/code&gt;. &lt;br&gt;
Data stored in this table are entries of a customer id and multiple products bought by such customer and also entries of product id and customers who bought them.&lt;br&gt;
&lt;strong&gt;Result&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpzlswttvhknj9vl24ecf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpzlswttvhknj9vl24ecf.png" alt="Many-to-many relationship" width="526" height="52"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Why is this knowledge important?
&lt;/h2&gt;

&lt;p&gt;Understanding how relationships work in database management is an important concept for a software engineer to understand. The significance of this knowledge cannot be overstated, as relationships are the logic that underpins business rules. Databases are generally about table interaction, and by understanding how the interaction/relationships work, you can begin to make more meaningful business designs as a developer. It aids in the avoidance of many schema errors in database design, as well as the reduction of future limitations in the enhancement of business features.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we learned how relationships work and the different types of database relationships in typeORM. We also briefly discussed why understanding relationships is important in database management.&lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>webdev</category>
      <category>opensource</category>
    </item>
    <item>
      <title>What exactly is 'this'? Understanding JavaScript's Call(), Bind(), and Apply() methods.</title>
      <dc:creator>Mary Okosun</dc:creator>
      <pubDate>Fri, 03 Jun 2022 14:08:13 +0000</pubDate>
      <link>https://dev.to/marienoir/what-exactly-is-this-understanding-javascripts-call-bind-and-apply-methods-a7p</link>
      <guid>https://dev.to/marienoir/what-exactly-is-this-understanding-javascripts-call-bind-and-apply-methods-a7p</guid>
      <description>&lt;p&gt;A commonly used keyword in some programming languages is &lt;code&gt;this&lt;/code&gt;. This term allows you to refer to an object from within it. One of the more perplexing aspects of Javascript is that &lt;code&gt;this&lt;/code&gt; value varies based on the context in which it is invoked.&lt;/p&gt;

&lt;p&gt;It refers to the &lt;strong&gt;global scope&lt;/strong&gt; by default, but it refers to the function when invoked within it. We'll learn about the &lt;code&gt;this&lt;/code&gt; keyword, as well as why and when to utilize &lt;strong&gt;call&lt;/strong&gt; , &lt;strong&gt;bind&lt;/strong&gt; , and &lt;strong&gt;apply&lt;/strong&gt; in JavaScript, in this article.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The value of this is assigned when a method or function is called. And NOT where it is defined!&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myLanguages = {
  firstLanguage:"Javascript",
  secondLanguage: "Python",
  language() {
    return `I code in ${this.firstLanguage} and ${this.secondLanguage}`;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the method &lt;code&gt;language()&lt;/code&gt; has access to the properties of its object &lt;code&gt;myLanguages&lt;/code&gt;, and therefore the &lt;code&gt;this&lt;/code&gt; is function-scoped in this situation. In this scenario, &lt;code&gt;myLanguages.language()&lt;/code&gt; would return as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myLanguages.language(); //I code in Javascript and Python

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In another scenario, let us assign the method to the variable &lt;code&gt;globalScope&lt;/code&gt;. If we try to console this variable, we can see that the &lt;code&gt;this&lt;/code&gt; is no longer accessible within the &lt;code&gt;myLanguages&lt;/code&gt; object; instead, it is now global scoped and it is now pointing to the window object and it would return an &lt;code&gt;undefined&lt;/code&gt; because &lt;code&gt;firstLanguage&lt;/code&gt; and &lt;code&gt;secondLangauge&lt;/code&gt; are not available globally.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const globalScope = myLanguages.language
console.log(globalScope()) //I code in undefined and undefined

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;However, if we set a &lt;code&gt;firstLanguage&lt;/code&gt; and &lt;code&gt;secondLangauge&lt;/code&gt; property to the window object, we can now access both properties globally using the method of the &lt;code&gt;myLanguages&lt;/code&gt; object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.firstLanguage = "Laravel";
window.secondLanguage = "Golang";
console.log(globalScope()) //I code in Laravel and Golang

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So again, to reiterate, the value of &lt;code&gt;this&lt;/code&gt; is assigned only when a method or function is called, not when it is defined. Although the &lt;code&gt;this&lt;/code&gt; keyword was specified within the scope of the function, its value was allocated at the point where it was invoked in our example.&lt;/p&gt;

&lt;p&gt;Now that we have a fundamental knowledge of how the &lt;code&gt;this&lt;/code&gt; concept works, we can now delve into the call, bind, and apply methods as these concepts would help solve the issue of &lt;code&gt;this&lt;/code&gt; scope.&lt;/p&gt;

&lt;p&gt;Using these predefined methods, we can assign the value of &lt;code&gt;this&lt;/code&gt; to whatever we want as they can be used to set the &lt;code&gt;this&lt;/code&gt; keyword independent of how a function is called.&lt;/p&gt;

&lt;h3&gt;
  
  
  Call()
&lt;/h3&gt;

&lt;p&gt;This is a method that is predefined in JavaScript. It's used to call or invoke a method that takes the owner object as an argument. An object can use a method that belongs to another object by using the &lt;code&gt;call()&lt;/code&gt; function. You can write a method once and then call it from another object without having to rewrite the method.&lt;/p&gt;

&lt;p&gt;The format for a call() method can be seen as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object.function.call(this.Args)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example below, we have two objects &lt;code&gt;relation1&lt;/code&gt; and &lt;code&gt;relation2&lt;/code&gt; that can access the method &lt;code&gt;faveRelation&lt;/code&gt; and we utilize the &lt;code&gt;call()&lt;/code&gt; method with the owner object as its argument to scope &lt;code&gt;this&lt;/code&gt; to be particular for each 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 person = {
 faveRelation() {
 return `${this.name} is my favourite ${this.relation}`;
 }
}
const relation1 = {
 name:"Jamie",
 relation: "uncle"
}
const relation2 = {
 name:"Austin",
 relation: "nephew"
}
person.faveRelation.call(relation1); //Jamie is my favourite uncle
person.faveRelation.call(relation2); //Austin is my favourite nephew

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;call()&lt;/code&gt; method accepts arguments as well. These arguments are comma-separated. They will be passed to the function call.&lt;/p&gt;

&lt;p&gt;The format for a call() method with arguments can be seen as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object.function.call(this.Args, argument1, argument2, ...)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code below is similar to what we had before, except it now includes method arguments.&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 = {
 faveRelation(city, country) {
 return `${this.name} is my favourite ${this.relation} and he lives in ${city},${country}`;
 }
}
const relation1 = {
 name:"Jamie",
 relation: "uncle"
}
const relation2 = {
 name:"Austin",
 relation: "nephew"
}
person.faveRelation.call(relation1, "Lagos", "Nigeria"); //Jamie is my favourite uncle and he lives in Lagos,Nigeria
person.faveRelation.call(relation2, "Benin-city", "Nigeria"); //Austin is my favourite nephew and he lives in Benin-city,Nigeria

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Apply() Method
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;apply()&lt;/code&gt; method is similar to the &lt;code&gt;call()&lt;/code&gt; method. The distinction is that the &lt;code&gt;call()&lt;/code&gt; method takes individual parameters, whereas the &lt;code&gt;apply()&lt;/code&gt; method takes an array of arguments. A &lt;code&gt;TypeError&lt;/code&gt; will occur if this is not done.&lt;/p&gt;

&lt;p&gt;The format for an apply() method with arguments can be seen as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Object.function.call(this.Args, [argument1, argument2, ...])

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;The apply() method is very handy if you want to use an array instead of an argument list.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you had an array of numbers, say [1, 2, 3], and you want to determine the largest number, you could use this method. You'd utilize the &lt;code&gt;apply()&lt;/code&gt; method with the array of integers as an argument, using the &lt;code&gt;Math&lt;/code&gt; object and the &lt;code&gt;max&lt;/code&gt; method. Because we don't have an object to refer to, the &lt;strong&gt;null&lt;/strong&gt; keyword is used.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;null&lt;/strong&gt; value is used in JavaScript to represent the intentional absence of any object value.&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(Math.max.apply(null,1,2,3)) // TypeError
console.log(Math.max.apply(null,[1,2,3])) // 3

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the example below, let us see how the &lt;code&gt;apply()&lt;/code&gt; method is used.&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 = {
 faveRelation: function(city, country) {
 return `${this.name} is my favourite ${this.relation} and he lives in ${city},${country}`;
 }
}
const relation1 = {
 name:"Jamie",
 relation: "uncle"
}
const relation2 = {
 name:"Austin",
 relation: "nephew"
}
person.faveRelation.apply(relation1, ["Lagos", "Nigeria"]); //Jamie is my favourite uncle and he lives in Lagos,Nigeria
person.faveRelation.apply(relation2, ["Benin-city", "Nigeria"]); //Austin is my favourite nephew and he lives in Benin-city,Nigeria

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Bind() method
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;bind()&lt;/code&gt; method, unlike the &lt;code&gt;call()&lt;/code&gt; and &lt;code&gt;apply()&lt;/code&gt; methods, does not instantly execute the function. It simply returns a new version of the function whose &lt;code&gt;this&lt;/code&gt; sets to argument &lt;code&gt;thisArg&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;The format for a bind() method can be seen as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bound = Object.function.bind(thisArgs);
bound()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example below, we called the &lt;code&gt;bind()&lt;/code&gt; method of the &lt;code&gt;person.faveRelation()&lt;/code&gt; method and pass in the &lt;code&gt;relation1&lt;/code&gt; as its argument. The &lt;code&gt;boundFavePerson()&lt;/code&gt; function is then called.&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 = {
 faveRelation: function() {
 return `${this.name} is my favourite ${this.relation}`;
 },
 favAnimal: function(hobby, animal) {
 return `${this.name} enjoys ${hobby} and loves ${animal}`;
 }
}
const relation1 = {
 name:"Jamie",
 relation: "uncle"
}
const relation2 = {
 name:"Austin",
 relation: "nephew"
}
const boundFavePerson = person.faveRelation.bind(relation1); 
console.log(boundFavePerson()); //Jamie is my favourite uncle

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can call the &lt;code&gt;bind()&lt;/code&gt; method by passing the arguments directly or passing the arguments in the bound function itself.&lt;/p&gt;

&lt;p&gt;You can either pass the arguments directly to the &lt;code&gt;bind()&lt;/code&gt; method (Method1) or pass the arguments to the &lt;code&gt;bound&lt;/code&gt; function itself (Method2).&lt;/p&gt;

&lt;p&gt;The format for a bind() method with arguments can be seen as :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Method1
const bound = Object.function.bind(thisArgs, argument1, argument2);
bound()

//Method2
const bound = Object.function.bind(thisArgs);
bound(argument1, argument2)


//Arguments passed directly
const boundPerson = person.favAnimal.bind(relation1, "surfing", "dogs"); 
console.log(boundPerson()); //Jamie enjoys surfing and loves dogs.

//Arguments passed in the bound function itself
const boundPerson1 = person.favAnimal.bind(relation2); 
console.log(boundPerson1("reading", "cats")); //Austin enjoys reading and loves cats

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;From this article, we have learned:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;How the &lt;code&gt;this&lt;/code&gt; keyword is scoped in Javascript.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When a method or function is invoked, the value of &lt;code&gt;this&lt;/code&gt; is assigned, not when it is defined.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We also learned how to set the &lt;code&gt;this&lt;/code&gt; keyword regardless of how a function is invoked using the call, bind, and apply methods.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you found this article useful, please share it with your network, and if you have any comments, please drop them! I'd be delighted to help 🙂&lt;/p&gt;

&lt;h3&gt;
  
  
  References
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.javascripttutorial.net/javascript-this/"&gt;https://www.javascripttutorial.net/javascript-this/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://betterprogramming.pub/understanding-the-this-keyword-in-javascript-cb76d4c7c5e8?gi=6ff6675c03cf"&gt;https://betterprogramming.pub/understanding-the-this-keyword-in-javascript-cb76d4c7c5e8?gi=6ff6675c03cf&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://betterprogramming.pub/when-to-use-bind-call-and-apply-in-javascript-1ae9d7fa66d5"&gt;https://betterprogramming.pub/when-to-use-bind-call-and-apply-in-javascript-1ae9d7fa66d5&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb"&gt;https://medium.com/@omergoldberg/javascript-call-apply-and-bind-e5c27301f7bb&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Scheduling Tasks In Node.js With Node Cron</title>
      <dc:creator>Mary Okosun</dc:creator>
      <pubDate>Mon, 09 May 2022 10:51:23 +0000</pubDate>
      <link>https://dev.to/marienoir/scheduling-tasks-in-nodejs-with-node-cron-3225</link>
      <guid>https://dev.to/marienoir/scheduling-tasks-in-nodejs-with-node-cron-3225</guid>
      <description>&lt;h3&gt;
  
  
  INTRODUCTION
&lt;/h3&gt;

&lt;p&gt;The essence of technology is to make productiveness faster and easier. Have you ever wanted to automate some tasks on your application? Then this tutorial is for you.&lt;/p&gt;

&lt;p&gt;In this article, you would learn how to automate scheduling emails in your node.js application using node-cron.&lt;/p&gt;

&lt;p&gt;Even if you are not interested in scheduling a job in node.js, you may still find the knowledge of the cron syntax from this article very useful, so stick around👌&lt;/p&gt;

&lt;h3&gt;
  
  
  PREREQUISITES
&lt;/h3&gt;

&lt;p&gt;This tutorial is a hands-on demonstration of how you can automate scheduled emails. Before proceeding, ensure you have the Javascript runtime environment &lt;a href="https://nodejs.org/en/download/"&gt;Node.js&lt;/a&gt; on your local computer.&lt;/p&gt;

&lt;h3&gt;
  
  
  WHAT IS SCHEDULING AND WHY NODE-CRON?
&lt;/h3&gt;

&lt;p&gt;According to Oxford Dictionary, &lt;strong&gt;Scheduling&lt;/strong&gt; refers to &lt;em&gt;plan&lt;/em&gt; an activity at a &lt;em&gt;specific date&lt;/em&gt; or &lt;em&gt;time&lt;/em&gt; in the &lt;em&gt;future&lt;/em&gt;. This tutorial is based on the words that are being highlighted.&lt;/p&gt;

&lt;p&gt;In node.js, we can plan(referred to as &lt;em&gt;function&lt;/em&gt;) an activity(referred to as &lt;em&gt;job&lt;/em&gt;) to run at a specific date or time(referred to as &lt;em&gt;expression&lt;/em&gt;) in the future. This is paramount as you cannot schedule a task to run at a past time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node cron&lt;/strong&gt; is an npm package used to schedule jobs that runs at specific time or date intervals. Instances of jobs that can be scheduled include logging at intervals, backing up a database, and sending out scheduled emails and email notifications. Node-cron is based on &lt;code&gt;cron&lt;/code&gt;, the time-based job scheduler in Unix-like systems.&lt;/p&gt;

&lt;p&gt;There are several npm packages that handle scheduling in node.js, such as &lt;code&gt;node-schedule&lt;/code&gt;, &lt;code&gt;node-cron&lt;/code&gt; , &lt;code&gt;Agenda&lt;/code&gt;, &lt;code&gt;Bree&lt;/code&gt;, &lt;code&gt;Cron&lt;/code&gt;, and &lt;code&gt;Bull&lt;/code&gt;, but for the purpose of this tutorial, we would be working with &lt;code&gt;node-cron&lt;/code&gt; because it is quite mature and stable. It is also preferable because we are making a simple job scheduling.&lt;/p&gt;

&lt;h3&gt;
  
  
  PROJECT SETUP
&lt;/h3&gt;

&lt;p&gt;To get started, we need to go to our terminal and create a project directory using the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir email-node-cron

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can then move into the created directory using the &lt;code&gt;cd&lt;/code&gt; command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd email-node-cron

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need to create a new file &lt;em&gt;index.js&lt;/em&gt; in the &lt;em&gt;email-node-cron&lt;/em&gt; directory&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch index.js

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The following command initializes the project and creates a &lt;code&gt;package.json&lt;/code&gt; file in the root folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;-y&lt;/code&gt; suffix is a shortened form of the &lt;code&gt;-yes&lt;/code&gt; flag. It is used to accept the prompts that come from &lt;code&gt;npm init&lt;/code&gt; automatically. It will populate all the options automatically with the default &lt;code&gt;npm init&lt;/code&gt; values.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Install dependencies&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As stated earlier, &lt;code&gt;node-cron&lt;/code&gt; is an npm package, so we need to install it as a package dependency in our project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install node-cron

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We also need to install the &lt;code&gt;nodemailer&lt;/code&gt; and &lt;code&gt;dotenv&lt;/code&gt; package dependency. &lt;strong&gt;Nodemailer&lt;/strong&gt; is an npm package that allows you to send emails.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dotenv&lt;/strong&gt; is a zero-dependency module that loads environment variables from a &lt;code&gt;.env&lt;/code&gt; file into &lt;code&gt;process.env&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install nodemailer
npm install dotenv

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After setting up our project and installing dependencies, our folder structure should be like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bADTRdli--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1651660573201/MQcejh9x-.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bADTRdli--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1651660573201/MQcejh9x-.png" alt="Screenshot 2022-05-04 at 11.30.23 AM.png" width="596" height="312"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  SCHEDULING AN EMAIL AUTOMATION JOB
&lt;/h3&gt;

&lt;p&gt;Let us start writing codes for our job and the code snippet below requires the &lt;code&gt;node-cron&lt;/code&gt; package in our index.js file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// index.js
const cron = require('node-cron');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To schedule a task, the node cron package has a &lt;code&gt;schedule&lt;/code&gt; method that takes in three arguments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cronJob = cron.schedule(expression, function, options)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The first argument known as &lt;strong&gt;cron expression&lt;/strong&gt; specifies the date and time at which the job should execute.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The second argument specifies the &lt;strong&gt;function&lt;/strong&gt; that executes at intervals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The third argument is an &lt;strong&gt;optional configuration&lt;/strong&gt; of the node cron job.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;NODE CRON EXPRESSION&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The cron expression which is the first argument is a string that specifies the date and time interval of a job. It comes in the format &lt;code&gt;* * * * * *&lt;/code&gt;. Each &lt;code&gt;*&lt;/code&gt; is a field and the representation of each field with the values is illustrated in the image below.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;seconds&lt;/code&gt; field is an optional field and can be omitted when writing an expression.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QyTR0Ji---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1651661958134/w3zS4YhpN.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QyTR0Ji---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1651661958134/w3zS4YhpN.png" alt="Screenshot 2022-05-04 at 11.58.58 AM.png" width="880" height="391"&gt;&lt;/a&gt;There are various ways to populate a cron expression, but, in this tutorial, we would be populating the cron expression with single integer values.&lt;/p&gt;

&lt;p&gt;For instance, if we want to send an email to our subscribers every Thursday at 9:50:10 AM, our expression would be like &lt;code&gt;10 50 9 * * 4&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This would run the &lt;code&gt;node-cron&lt;/code&gt; job at the tenth second of the fiftieth minute of the ninth hour. Since we did not specify a value for the day of the month and month field, it interprets &lt;code&gt;*&lt;/code&gt; to mean every month. But we specified the fourth day of the week, thus this job would run every Thursday at 9:50:10 AM.&lt;/p&gt;

&lt;p&gt;Can we attempt writing a cron expression for sending an email to our subscribers on the 15th of every month at 2:30 pm? 😊&lt;/p&gt;




&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;NODE CRON FUNCTION&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The function is the second argument of the schedule method and it specifies the function that should execute. In our case, the function would be sending emails to our subscribers.&lt;/p&gt;

&lt;p&gt;Here, we would require the &lt;code&gt;nodemailer&lt;/code&gt; package and then create a mail transporter &lt;code&gt;transporter&lt;/code&gt; that sets the username and password of our email account.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It is considered a good software development practice to always store credentials in an environment variable (.env) file.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So let us create a .env file in the root folder&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;touch .env

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the following code snippets to add your credentials to the &lt;code&gt;.env&lt;/code&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//.env file
EMAIL=youremailaddress@gmail.com
PASSWORD=youremailpassword

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You need to configure the &lt;code&gt;index.js&lt;/code&gt; file so that it can have access to your &lt;code&gt;.env&lt;/code&gt; file variables.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const nodemailer = require('nodemailer');
const dotenv = require('dotenv');

// .env configuration
dotenv.config()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the index.js file, the code snippet above requires the dependencies &lt;code&gt;nodemailer&lt;/code&gt; and &lt;code&gt;dotenv&lt;/code&gt; installed earlier. It is then configured using the &lt;code&gt;.config()&lt;/code&gt; method. In order to use &lt;code&gt;nodemailer&lt;/code&gt;, we are expected to do the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a Transporter object &lt;code&gt;transporter&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// creates a mail transporter here
let transporter = nodemailer.createTransport({
   service: "gmail",
   auth: {
      user: process.env.EMAIL,
      pass: process.env.PASSWORD,
   },
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create an object &lt;code&gt;MailOptions&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mailOptions = {
      from: 'EMAIL NODE CRON APP',
      to: process.env.EMAIL,
      subject: "Scheduled Email",
      html: `&amp;lt;p&amp;gt;Hello there,&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt; You have an email scheduled from &amp;lt;b&amp;gt;EMAIL NODE CRON APP&amp;lt;/b&amp;gt; &amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;Keep learning👌👌&amp;lt;/p&amp;gt;
      Kind regards, &amp;lt;br&amp;gt;
      &amp;lt;h4&amp;gt; EMAIL NODE CRON APP&amp;lt;/h4&amp;gt;`
   };

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Use the &lt;code&gt;sendMail&lt;/code&gt; method on the object &lt;code&gt;transporter&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;transporter.sendMail(mailOptions, (error, info) =&amp;gt; {
      if (error) {
         console.log("Email error application", error.message);
      } else {
         console.log(`${new Date().toLocaleString()} - Email sent successfully:` + info.response);
      }
   });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the index.js file, we have the function that needs to execute to send emails to our subscribers. We would take a quick look at the optional argument before we set up our cron job properly.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;NODE CRON OPTION&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The option is the third argument of the cron schedule method and it is an optional configuration for the job scheduling. It is an object that contains the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;scheduled&lt;/strong&gt; : This is a boolean to set if the created task is scheduled. The default value is set to &lt;code&gt;true&lt;/code&gt;. When_scheduled_is set to true, the job runs automatically when the cron expression is fulfilled, however when set to false, you need to invoke a &lt;code&gt;start()&lt;/code&gt;method to the job object like this &lt;code&gt;job.start()&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;timezone&lt;/strong&gt; : This is the timezone that is used for job scheduling. The default timezone is that of the system used in scheduling the cron job. You can check out &lt;a href="https://momentjs.com/timezone/"&gt;moment-timezone&lt;/a&gt; for valid timezone values. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An instance of this is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ 
scheduled: false, 
timezone: Asia/Tokyo
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we have a pretty good understanding of what each argument means and how they are important in creating a good cron job. We would set up our cron job and executes the job too.&lt;/p&gt;

&lt;p&gt;In the code snippet below, we would create a node cron job that schedules emails sent to our subscribers every minute.&lt;/p&gt;

&lt;p&gt;Our index.js file should be 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 cronJob = require('node-cron');
const nodemailer = require('nodemailer');
const dotenv = require('dotenv');

// .env configuration
dotenv.config();

// creates a mail transporter here
let transporter = nodemailer.createTransport({
   service: "gmail",
   auth: {
      user: process.env.EMAIL,
      pass: process.env.PASSWORD,
   },
});

// Sending emails every minute
cronJob.schedule('59 * * * * *', () =&amp;gt; {
   let mailOptions = {
      from: 'EMAIL NODE CRON APP',
      to: process.env.EMAIL,
      subject: "Scheduled Email",
      html: `&amp;lt;p&amp;gt;Hello there,&amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt; You have an email scheduled from &amp;lt;b&amp;gt;EMAIL NODE CRON APP&amp;lt;/b&amp;gt; &amp;lt;/p&amp;gt;
      &amp;lt;p&amp;gt;Keep learning👌👌&amp;lt;/p&amp;gt;
      Kind regards, &amp;lt;br&amp;gt;
      &amp;lt;h4&amp;gt; EMAIL NODE CRON APP&amp;lt;/h4&amp;gt;`
   };

   transporter.sendMail(mailOptions, (error, info) =&amp;gt; {
      if (error) {
         console.log("Email error application", error.message);
      } else {
         console.log(`${new Date().toLocaleString()} - Email sent successfully:` + info.response);
      }
   });
});

console.log('Application started.....');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In your terminal, type in the code snippet &lt;code&gt;node index.js&lt;/code&gt; to start your application.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;NB: If you are having an error message of&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Email error application Invalid login: 535-5.7.8 Username and Password not accepted.

&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;You might need to allow less secured apps to test if you are using a Gmail address.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is a screenshot of my terminal and the email delivered to my inbox.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Terminal &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rvIXGB8j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1652027414016/B8eknAn74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rvIXGB8j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1652027414016/B8eknAn74.png" alt="Screenshot 2022-05-08 at 5.28.41 PM.png" width="794" height="146"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Email Inbox&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--g76iuWnY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1652027505336/pglR5vrCW.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--g76iuWnY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1652027505336/pglR5vrCW.png" alt="Screenshot 2022-05-08 at 5.29.29 PM.png" width="880" height="97"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;h3&gt;
  
  
  CONCLUSION
&lt;/h3&gt;

&lt;p&gt;In this tutorial, you have learned how to automate scheduling emails in your node.js application using node-cron. This knowledge can be applied in your future projects to be more productive and also avoid repetitive tasks that node-cron can handle.&lt;/p&gt;

&lt;p&gt;You can access the &lt;a href="https://github.com/Marienoir/technical-blog-samples/tree/main/email-node-cron"&gt;GitHub repository&lt;/a&gt; for the sample code used in this tutorial.&lt;/p&gt;

&lt;h3&gt;
  
  
  REFERENCES
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://crontab.guru/"&gt;A quick and simple editor for cron schedule expressions by Cronitor&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.freecodecamp.org/news/schedule-a-job-in-node-with-nodecron/"&gt;https://www.freecodecamp.org/news/schedule-a-job-in-node-with-nodecron/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.digitalocean.com/community/tutorials/nodejs-cron-jobs-by-examples"&gt;https://www.digitalocean.com/community/tutorials/nodejs-cron-jobs-by-examples&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>cronjob</category>
    </item>
    <item>
      <title>Primitive Values And Reference Values As Regards Memory Allocation</title>
      <dc:creator>Mary Okosun</dc:creator>
      <pubDate>Wed, 26 Jan 2022 14:22:44 +0000</pubDate>
      <link>https://dev.to/marienoir/primitive-values-and-reference-values-as-regards-memory-allocation-1nb5</link>
      <guid>https://dev.to/marienoir/primitive-values-and-reference-values-as-regards-memory-allocation-1nb5</guid>
      <description>&lt;p&gt;All programming languages have their in-built data structures, however, they differ from each other.&lt;/p&gt;

&lt;p&gt;In this article, we would understand the types in JavaScript and learn the different types with references to their use cases and memory allocation. Javascript is a &lt;em&gt;loosely-typed programming language&lt;/em&gt; as it allows to assign and reassign values of different types to a variable.&lt;/p&gt;

&lt;p&gt;In JavaScript, we have 8 data types which are&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;String&lt;/li&gt;
&lt;li&gt;Number&lt;/li&gt;
&lt;li&gt;Boolean&lt;/li&gt;
&lt;li&gt;Null&lt;/li&gt;
&lt;li&gt;Undefined&lt;/li&gt;
&lt;li&gt;Functions&lt;/li&gt;
&lt;li&gt;Array &lt;/li&gt;
&lt;li&gt;Objects. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The values of these types are classified into &lt;strong&gt;Primitive Values&lt;/strong&gt; and &lt;strong&gt;Non-primitive/Reference Values&lt;/strong&gt;. The primitive values are values of the data types that includes &lt;strong&gt;String&lt;/strong&gt; , &lt;strong&gt;Number&lt;/strong&gt; , &lt;strong&gt;Boolean&lt;/strong&gt; , &lt;strong&gt;Null&lt;/strong&gt; , and &lt;strong&gt;Undefined&lt;/strong&gt; while the Non-primitive or reference values are values of the data types &lt;strong&gt;Functions&lt;/strong&gt; , &lt;strong&gt;Array&lt;/strong&gt; , and &lt;strong&gt;Object&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Therefore Primitive Data Types are data types of the primitive values and Non-primitive/Reference Data Types are data types of the reference values. When you declare a variable, the JavaScript engine allocates the memory for them on two memory locations which are the &lt;strong&gt;STACK&lt;/strong&gt; and &lt;strong&gt;HEAP&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--uUue4hys--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1642754460436/El-LisrzO.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--uUue4hys--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1642754460436/El-LisrzO.png" alt="Screenshot 2022-01-21 at 09.39.05.png" width="880" height="315"&gt;&lt;/a&gt;I wrote an in-depth article about the JavaScript runtime engine &lt;a href="https://dev.to/marienoir/understanding-javascript-runtime-environment-2dk5-temp-slug-9753136"&gt;here&lt;/a&gt;. You can check it out to understand how the JavaScript environment handles variable allocation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Primitive Data Type
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Primitive data types are immutable i.e they can not be modified.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A primitive data type is a sub-class that allows the assignment of a variable to be by &lt;em&gt;value&lt;/em&gt;. When a variable is assigned to a value with the primitive data type, the Javascript engine allocates the memory for it on a stack.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A stack is a data structure that allows elements to be added and removed in a particular order. It can be used to store static data. A static data means that the Javascript engine knows the size of such data at compile time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let us check out this example to understand better.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let foo = 20 // Initial assignment 
let bar = foo // Assignment of variable *bar* to *foo* variable
foo = 40 // Re-assignment
console.log(foo) // 40
console.log(bar) // 20

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From this code, we can see that the variable &lt;code&gt;foo&lt;/code&gt; was initially assigned the value of 20 and that variable is pushed to the top of the stack. A new variable &lt;code&gt;bar&lt;/code&gt; was assigned to &lt;code&gt;foo&lt;/code&gt;, in the case of a primitive data type of which the type &lt;code&gt;string&lt;/code&gt; is inclusive, only the value of &lt;code&gt;foo&lt;/code&gt; which is 20 is assigned to &lt;code&gt;bar&lt;/code&gt;. The variable &lt;code&gt;bar&lt;/code&gt; with its value is pushed to the call stack.&lt;/p&gt;

&lt;p&gt;In the next line, we can see a reassignment of the value 40 to the variable &lt;code&gt;foo&lt;/code&gt;. When we log both variables to the console, we can see the results of both variables.&lt;/p&gt;

&lt;p&gt;From the code above, we can understand that the reassignment of a value to a primitive data type does not change the value of the initial assignment.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZKYxZMK8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1643206621316/j0A8hPjba.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZKYxZMK8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1643206621316/j0A8hPjba.png" alt="Screenshot 2022-01-26 at 15.16.19.png" width="436" height="372"&gt;&lt;/a&gt;From the image above, we can see that for each assignment of the variables, they are placed at the top of the stack.&lt;/p&gt;

&lt;h3&gt;
  
  
  Reference Data Type
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Reference data types are mutable i.e they can be easily modified.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In reference type, the assignment of a variable is done by &lt;em&gt;reference&lt;/em&gt;. All the reference data types are technically objects so we would collectively refer to them as &lt;strong&gt;Objects&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The variables that are assigned to a non-primitive value are usually given a reference to that value. This reference points to that object's address/location in memory. Note that the variables do not themselves contain the value.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj = { a: 'I', b: 'love', c: 'JavaScript'}
let newObj = obj
newObj.c = 'Python'
console.log (obj) // { a: 'I', b: 'love', c: 'Python' }
console.log(newObj) // { a: 'I', b: 'love', c: 'Python' }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we created an object in memory, and a &lt;em&gt;location&lt;/em&gt; and an &lt;em&gt;address&lt;/em&gt; of the array are created. Using memory allocation, the &lt;strong&gt;address&lt;/strong&gt; is the &lt;strong&gt;stack&lt;/strong&gt; while the &lt;strong&gt;location&lt;/strong&gt; is the &lt;strong&gt;heap&lt;/strong&gt;. All variables usually first point to the stack. If it is a non-primitive value, the stack would contain a reference to the object in the heap.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--CC5MKsHj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1642754415420/STVGUqY_7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CC5MKsHj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1642754415420/STVGUqY_7.png" alt="Screenshot 2022-01-21 at 09.38.44.png" width="880" height="361"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;From the image above, we can see that for the assignment of the &lt;code&gt;obj&lt;/code&gt; variable, the value is not associated with the variable rather an &lt;em&gt;address/reference&lt;/em&gt; is pushed to the stack, and a &lt;em&gt;location/object&lt;/em&gt; is pushed to the heap. For the assignment of the &lt;code&gt;newObj&lt;/code&gt; variable to the &lt;code&gt;obj&lt;/code&gt;, it points to the same address and location of the &lt;code&gt;obj&lt;/code&gt; variable. When there is a reassignment of the &lt;code&gt;new Obj&lt;/code&gt; property, this affects the location thereby changing the value of every variable that points to that location, in our case, affecting the &lt;code&gt;obj&lt;/code&gt; and &lt;code&gt;newObj&lt;/code&gt; variables.&lt;/p&gt;

&lt;p&gt;The memory of the heap is not usually ordered which is why we need to keep a reference to it in the stack.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We can think of the &lt;strong&gt;REFERENCES&lt;/strong&gt; in the stack as the &lt;strong&gt;ADDRESS&lt;/strong&gt; and the &lt;strong&gt;OBJECTS&lt;/strong&gt; in the heap as the &lt;strong&gt;LOCATION&lt;/strong&gt; that the address belongs to.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  CONCLUSION
&lt;/h3&gt;

&lt;p&gt;In this article, we were able to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Understand the various JavaScript data types which are String, Number, Boolean, Null, Undefined, Functions, Array, and Objects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Understand that primitive data types are immutable i.e they can not be modified, and a non-primitive data type can be easily modified.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Understand how JavaScript handles primitive values and non-primitive values using HEAP and STACK.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  RESOURCES
&lt;/h3&gt;

&lt;p&gt;Some resources that helped me understand this concept better include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.javascripttutorial.net/javascript-primitive-vs-reference-values/"&gt;Javascript primitive vs reference values&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://felixgerschau.com/javascript-memory-management/"&gt;JavaScript's Memory Management Explained&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/marienoir/understanding-javascript-runtime-environment-2dk5-temp-slug-9753136"&gt;Understanding JavaScript Runtime Environment&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.freecodecamp.org/news/primitive-vs-reference-data-types-in-javascript/"&gt;Primitive vs Reference Data Types in JavaScript&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you found this article helpful, don't forget to give a thumbs-up 👍 , and please share with your network. I would appreciate a comment if you have any questions or feedback.&lt;/p&gt;

&lt;p&gt;Happy coding👌👌!!!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>Understanding JavaScript Runtime Environment</title>
      <dc:creator>Mary Okosun</dc:creator>
      <pubDate>Fri, 07 Jan 2022 13:54:16 +0000</pubDate>
      <link>https://dev.to/marienoir/understanding-javascript-runtime-environment-4na2</link>
      <guid>https://dev.to/marienoir/understanding-javascript-runtime-environment-4na2</guid>
      <description>&lt;p&gt;In becoming a better JavaScript developer, you need to understand the concept of how JavaScript executes scripts under the hood. In this article, we will better understand how the JavaScript runtime environment works.&lt;/p&gt;

&lt;p&gt;The Javascript runtime environment allows Javascript code to be run and consists of the &lt;strong&gt;Javascript engine&lt;/strong&gt; , the &lt;strong&gt;Web APIs&lt;/strong&gt; , a &lt;strong&gt;callback queue,&lt;/strong&gt; and the &lt;strong&gt;event loop&lt;/strong&gt;. The web browser has an inbuilt runtime environment, as in the case of the Chrome browser, called the &lt;strong&gt;V8 engine&lt;/strong&gt;. This enables JavaScript codes to be run on the web browser.&lt;/p&gt;

&lt;p&gt;However, in order to run JavaScript code outside of the browser, the JavaScript runtime environment needs to be made available. For example, &lt;strong&gt;Node.js&lt;/strong&gt; is a JavaScript runtime environment that allows you to run JavaScript codes outside of the web browser.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;CALL STACK&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The JavaScript engine uses a &lt;strong&gt;call stack&lt;/strong&gt; to manage script execution.&lt;/p&gt;

&lt;p&gt;According to &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Call_stack"&gt;&lt;em&gt;MDN&lt;/em&gt;&lt;/a&gt;, a call stack is a mechanism for an interpreter (such as the Javascript interpreter) to keep track of functions in a script that call multiple functions, i.e., what function is currently being run and what functions are being called from within that function.&lt;/p&gt;

&lt;p&gt;When you execute a script, the JavaScript engine would create a &lt;em&gt;Global Execution Context&lt;/em&gt; and push it to the top of the call stack.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Global Execution Context is the default execution context in which JS code start its execution when the file first loads in the browser.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Whenever a function is called, the JavaScript engine creates a &lt;em&gt;Function Execution Context&lt;/em&gt; for the function, pushes it on top of the call stack, and starts executing the function.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A functional execution context is the context created by the JS engine whenever it finds any function call. Each function has its own execution context.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If a function calls another function, the JavaScript engine creates a new Function Execution Context for the function that is being called and pushes it on top of the call stack.&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(a, b){
  return a * b;
}

function square(c){
  return multiply(c,c);
}

square(8)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zkDxxtV0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641553747330/ydc4WzIXP.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zkDxxtV0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641553747330/ydc4WzIXP.png" alt="Screenshot 2022-01-07 at 12.08.41.png" width="880" height="884"&gt;&lt;/a&gt;From the image above, when the script is executed, a global execution context is created &lt;code&gt;main()&lt;/code&gt; .The first function, which is &lt;code&gt;square()&lt;/code&gt; is executed and pushed as the first item on the stack. Subsequently, the function &lt;code&gt;multiply()&lt;/code&gt; is executed and pushed to the top of the stack.&lt;/p&gt;

&lt;p&gt;A function is immediately popped out of the stack when a script gets to a return statement, . Therefore, the &lt;code&gt;multiply&lt;/code&gt; is popped first, followed by the &lt;code&gt;square&lt;/code&gt; function, and then the &lt;code&gt;main()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;As soon as the call stack is empty, the script stops execution .&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The call stack uses the &lt;strong&gt;LIFO&lt;/strong&gt; principle (Last In, First Out).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The last function in the stack, &lt;code&gt;multiply()&lt;/code&gt; is the first function that popped out.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;STACK OVERFLOW ERROR&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When a function is being invoked recursively, i.e., a function keeps calling itself without any point of exit, it returns a &lt;strong&gt;stack overflow&lt;/strong&gt; error.&lt;/p&gt;

&lt;p&gt;This happens because a call stack has a limited size and when this size is exceeded, it throws an error. &lt;code&gt;RangeError: Maximum call stack size exceeded&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The maximum &lt;a href="https://2ality.com/2014/04/call-stack-size.html"&gt;call stack size limit&lt;/a&gt; ranges from 10 to 50 thousand calls. For the chrome browser, the size limit is 16,000.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function baz(){
  baz();
}
baz()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--tX0dx81g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641553959198/L-8O6SiAm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--tX0dx81g--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641553959198/L-8O6SiAm.png" alt="Screenshot 2022-01-07 at 12.12.01.png" width="880" height="822"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;WEB APIs&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Javascript is a single threaded language, which means that it runs synchronously and handles tasks one at a time. JavaScript has a single call stack, due to its &lt;strong&gt;&lt;em&gt;single-threadedness&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In this section, we will look at how asynchronous functions operate and how they are placed in the order of execution in JavaScript.&lt;/p&gt;

&lt;p&gt;While JavaScript as a language is synchronous, it is possible to run tasks asynchronously, and this is possible through the APIs provided by the browser.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Application Programming Interfaces (APIs) are constructs made available in programming languages to permit developers to form complex functionality more easily. They abstract more complex code far from you, providing some easier syntax to use in its place.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The APIs in client-side JavaScript are divided into two categories:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Browser/Web APIs &lt;/li&gt;
&lt;li&gt;Third-party APIs &lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Browser APIs&lt;/strong&gt; : These are built into the browser that sits on top of the JavaScript language and permit you to implement functionality more easily. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Third-party APIs&lt;/strong&gt; : These are built into third-party platforms (e.g., Twitter, Facebook) that allow you to use a number of those platforms's functionality in your own sites (for example, displaying your latest Tweets on your web page).&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For instance, when we make an API request or image load to the server, the interpreter would not be able to do anything else until a response is gotten from the server.&lt;/p&gt;

&lt;p&gt;This can make our application slow and unusable . With the web APIs, the execution is handled, so this would not block the call stack, and other tasks can be run while we wait for the response.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = () =&amp;gt; console.log('I');
const b = () =&amp;gt; setTimeout(() =&amp;gt; console.log('love'), 1000);
const c = () =&amp;gt; console.log('JavaScript');

a();
b();
c();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From our initial knowledge of the call stack, the result should be printed as &lt;code&gt;I&lt;/code&gt;, &lt;code&gt;love&lt;/code&gt; and then &lt;code&gt;JavaScript&lt;/code&gt; because the functions have a &lt;code&gt;console.log&lt;/code&gt; statement and the script should be executed after each &lt;code&gt;console.log&lt;/code&gt; or &lt;code&gt;return&lt;/code&gt; statement.&lt;/p&gt;

&lt;p&gt;However, the &lt;code&gt;setTimeout&lt;/code&gt; function is an asynchronous function, and it is being executed concurrently while the next statement is being executed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Steps of execution&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;function a&lt;/code&gt; is invoked and executed first. The result &lt;code&gt;I&lt;/code&gt; is output (Step 1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;function b&lt;/code&gt; is invoked and triggers the execution of the web API (Step 2), and after &lt;code&gt;setTimeout&lt;/code&gt; finishes its execution, it adds the callback to the callback queue. In the next section, we will learn what the callback queue is.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;function c&lt;/code&gt; is invoked and executed last, but it is output second because while the &lt;code&gt;setTimeout&lt;/code&gt; is being executed asynchronously, the JS interpreter continues to this task and the result &lt;code&gt;JavaScript&lt;/code&gt; is output (Step 3).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PRMPCblx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641561190946/pxNzTKbsB.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PRMPCblx--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1641561190946/pxNzTKbsB.png" alt="Screenshot 2022-01-07 at 14.12.22.png" width="880" height="381"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;CALLBACK QUEUE AND EVENT LOOP&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When an asynchronous function like &lt;code&gt;setTimeout&lt;/code&gt; gets called, after being executed by the Web APIs, it gets added to the &lt;strong&gt;callback queue&lt;/strong&gt; (Step 4).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A callback queue uses the First-In, First-Out (FIFO) principle.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The functions added to the callback queue are processed in that order. When the event loop in Javascript is fired, it first checks the call stack to see if it is non-empty.&lt;/p&gt;

&lt;p&gt;An event loop monitors the call stack and the callback queue. If the call stack is empty, the event loop will take the first event from the queue and will push it to the call stack, effectively running it.&lt;/p&gt;

&lt;p&gt;In our code instance used above, the event loop checks the call stack to be empty after &lt;code&gt;function a&lt;/code&gt; and &lt;code&gt;function c&lt;/code&gt; have been executed and takes &lt;code&gt;function b&lt;/code&gt; from the callback queue and pushes it to the call stack where it gets executed (Step 5). The script is said to be completed when the call stack and the callback queue are empty.&lt;/p&gt;

&lt;h3&gt;
  
  
  CONCLUSION
&lt;/h3&gt;

&lt;p&gt;I hope this article was able to help you understand some concepts happening behind the scenes of your JavaScript code. Please leave a comment if you have any questions or feedback.&lt;/p&gt;

&lt;p&gt;Some resources I found helpful while researching on this topic:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ"&gt;What the heck is the event loop anyway? | Philip Roberts&lt;/a&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://felixgerschau.com/javascript-event-loop-call-stack/#callback-queue"&gt;Event Loop and Call Stack Explained | Felix Gerschau&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="http://latentflip.com/loupe/?code=JC5vbignYnV0dG9uJywgJ2NsaWNrJywgZnVuY3Rpb24gb25DbGljaygpIHsKICAgIHNldFRpbWVvdXQoZnVuY3Rpb24gdGltZXIoKSB7CiAgICAgICAgY29uc29sZS5sb2coJ1lvdSBjbGlja2VkIHRoZSBidXR0b24hJyk7ICAgIAogICAgfSwgMjAwMCk7Cn0pOwoKY29uc29sZS5sb2coIkhpISIpOwoKc2V0VGltZW91dChmdW5jdGlvbiB0aW1lb3V0KCkgewogICAgY29uc29sZS5sb2coIkNsaWNrIHRoZSBidXR0b24hIik7Cn0sIDUwMDApOwoKY29uc29sZS5sb2coIldlbGNvbWUgdG8gbG91cGUuIik7!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D"&gt;JavaScript Runtime environment Visualisation | Philip Roberts&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4"&gt;JavaScript Event Loop Explained | Anoop Raveendran&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://dev.to/treyhuffine/asynchronous-javascript-part-3-the-callback-queue-414m-temp-slug-93198"&gt;Asynchronous Javascript Part 3: The Callback Queue | Kabir Nazir&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@gaurav.pandvia/understanding-javascript-function-executions-tasks-event-loop-call-stack-more-part-1-5683dea1f5ec"&gt;Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks &amp;amp; more | Gaurav Pandvia&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://medium.com/@happymishra66/execution-context-in-javascript-319dd72e8e2c"&gt;Execution context, Scope chain and JavaScript internals | Rupesh Mishra&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>queue</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
