Categories
CSS HTML JavaScript

Mastering Git: A Comprehensive Guide to Using Version Control for Collaborative Software Development

Version control is a system that allows developers to track and manage changes to their codebase over time. It helps teams work collaboratively on projects and ensures that everyone is working off of the most up-to-date version of the code. This is especially important for large projects where multiple developers may be working on different parts of the code simultaneously.

There are many different version control systems available, but the most popular is Git. In this post, we’ll be focusing on using Git for version control, including an overview of how it works and how to get started using it.

What is Git and how does it work?

Git is a distributed version control system, which means that it allows developers to work on their own copies of the code and track their changes locally. When they’re ready to share their changes with the rest of the team, they can push their changes to a central repository.

The central repository is typically hosted on a service like GitHub or GitLab, which provides a web-based interface for developers to interact with the repository. This includes features like code review, issue tracking, and project management.

One of the key features of Git is its ability to handle branching and merging. Branching allows developers to create a separate copy of the codebase to work on, without affecting the main codebase. This is useful for working on new features or experimenting with different approaches without affecting the stability of the main codebase.

Merging is the process of taking the changes made in a branch and incorporating them into the main codebase. This is done through a process called a “merge request,” which allows other members of the team to review the changes before they are merged.

Getting started with Git

To start using Git, you’ll need to install it on your computer. You can download the latest version of Git from the official website (https://git-scm.com/). Once you’ve installed Git, you’ll need to set up a few basic configuration options, such as your name and email address.

To set up your name and email address, you can use the following commands:

$ git config --global user.name "Your Name"
$ git config --global user.email "your.email@example.com"

Once you’ve set up your basic configuration, you’re ready to start using Git. The first thing you’ll need to do is create a repository for your code. A repository is a central location where all of your code and related files are stored.

To create a new repository, you can use the git init command. This will create a new directory called “.git” in your current working directory, which will be used to store all of the metadata and history for your repository.

For example:

$ git init

Once you have a repository set up, you can start tracking changes to your code. To do this, you’ll need to add your files to the repository and commit them.

To add a file to the repository, you can use the git add command. This will tell Git to start tracking the file and include it in the next commit.

For example:

$ git add file.txt

To commit your changes, you’ll need to use the git commit command. This will create a new commit in your repository, which is a snapshot of your code at a particular point in time. When you commit your changes, you’ll also need to provide a commit message, which is a short description of the changes you’ve made.

For example:

$ git commit -m "Added new feature"

Once you’ve committed your changes, you can push them to a central repository. To do this, you’ll need to specify the location of the repository and use the git push command.

For example:

The origin in this example refers to the name of the remote repository, and master refers to the branch you’re pushing to.

Collaborating with Git

One of the key benefits of using Git is the ability to collaborate with other developers. Git makes it easy for multiple developers to work on the same codebase simultaneously, and it provides tools for resolving conflicts and merging changes.

To collaborate with other developers, you’ll need to clone their repository to your local machine. To do this, you can use the git clone command, followed by the URL of the repository you want to clone.

For example:

$ git clone https://github.com/user/repository.git

This will create a copy of the repository on your local machine, and you can start making changes to the code. When you’re ready to share your changes with the rest of the team, you can push them to the central repository and create a merge request.

A merge request is a request to merge your changes into the main codebase. It allows other members of the team to review your changes and provide feedback before they are merged.

To create a merge request, you’ll need to push your changes to a separate branch and create a pull request in the web-based interface. This will notify the rest of the team that you have changes ready to be reviewed and merged.

Wrapping it all up

Using version control with Git is an essential tool for any software development team. It allows developers to track and manage changes to their codebase, collaborate with others, and ensure that everyone is working off of the most up-to-date version of the code.

If you’re new to Git, we recommend starting with the basics and gradually learning more advanced features as you become more comfortable with the system. There are many resources available to help you learn Git, including online tutorials, books, and courses. With a little bit of practice, you’ll be a pro at using Git in no time.

Categories
HTML Marketing

Collecting all the phone numbers on a webpage with JavaScript

In today’s digital world, it is becoming increasingly common for businesses and organizations to use phone numbers as a primary method of communication with customers and clients. As such, there may be instances where you need to collect all of the phone numbers on a webpage for various purposes.

In this post, we will discuss how to collect all of the phone numbers on a webpage using JavaScript. We will cover the basics of phone number extraction, as well as provide examples and tips on how to effectively collect phone numbers using JavaScript.

What is Phone Number Extraction?

Phone number extraction, also known as phone number scraping or phone number harvesting, is the process of collecting phone numbers from a webpage or other online source. This can be done for various reasons, such as for marketing or lead generation purposes.

Phone numbers can be extracted manually by copying and pasting them from a webpage, or automatically using software or programming languages such as JavaScript. In this post, we will focus on the latter method, discussing how to use JavaScript to collect phone numbers from a webpage.

Collecting Phone Numbers with JavaScript

To collect phone numbers from a webpage using JavaScript, there are a few steps that need to be taken:

  1. Locate the phone numbers on the webpage.
  2. Extract the phone numbers from the webpage.
  3. Store the extracted phone numbers in a data structure.

Let’s discuss each of these steps in more detail.

Locate the Phone Numbers on the Webpage

The first step in collecting phone numbers using JavaScript is to locate the phone numbers on the webpage. There are a few ways to do this, such as using DOM traversal methods or regular expressions.

DOM Traversal Methods

One way to locate phone numbers on a webpage is to use DOM traversal methods such as getElementsByTagName() or querySelectorAll(). These methods allow you to select elements on the webpage based on their tag name or a CSS selector.

For example, you can use getElementsByTagName() to select all of the a elements on the webpage, which may contain phone numbers if they are linked to a phone number using the tel: protocol.

var links = document.getElementsByTagName('a');

You can then iterate through the array of a elements and check for phone numbers using the href attribute.

for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.startsWith('tel:')) {
    console.log(link.href);
  }
}

Regular Expressions

Another way to locate phone numbers on a webpage is to use regular expressions. Regular expressions are a pattern-matching language that allows you to search for specific patterns in a string of text.

For example, you can use the following regular expression to search for phone numbers in a string of text:

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

This regular expression will match phone numbers that are formatted in one of the following ways:

  • (123) 456-7890
  • 123-456-7890
  • 123.456.7890
  • 123 456 7890

To use this regular expression to search for phone numbers on a webpage, you can use the String.prototype.match() method, which returns an array of matches for the given regular expression.

For example, you can use the following code to search for phone numbers in the innerHTML of the body element:

var body = document.body.innerHTML;
var phoneNumbers = body.match(/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/);
console.log(phoneNumbers);

This will output an array of phone numbers that were found in the innerHTML of the body element.

Extract the Phone Numbers from the Webpage

Once you have located the phone numbers on the webpage, the next step is to extract them. This can be done by iterating through the array of phone numbers and extracting the relevant information.

For example, if you are using DOM traversal methods to collect the phone numbers, you can extract the phone number from the href attribute of the a element.

for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.startsWith('tel:')) {
    var phoneNumber = link.href.substring(4); // remove the "tel:" prefix
    console.log(phoneNumber);
  }
}

If you are using regular expressions to collect the phone numbers, you can extract the phone number by accessing the first element in the array of matches.

var phoneNumber = phoneNumbers[0];
console.log(phoneNumber);

Store the Extracted Phone Numbers in a Data Structure

The final step in collecting phone numbers using JavaScript is to store the extracted phone numbers in a data structure. This can be done using an array, object, or other data structure.

For example, you can use an array to store the phone numbers as follows:

var phoneNumbers = [];

for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.startsWith('tel:')) {
    var phoneNumber = link.href.substring(4); // remove the "tel:" prefix
    phoneNumbers.push(phoneNumber);
  }
}

console.log(phoneNumbers);

This will output an array of phone numbers that were collected from the webpage.

Tips for Collecting Phone Numbers with JavaScript

Here are a few tips to keep in mind when collecting phone numbers using JavaScript:

  • Make sure to include error handling in your code to account for phone numbers that are not formatted correctly or are not in the expected location on the webpage.
  • Consider using regular expressions to match a wider range of phone number formats.
  • Use browser dev tools to test and debug your code before implementing it on a live webpage.
  • Keep in mind that phone number extraction may be against the terms of service for some websites, so be sure to check the terms before collecting phone numbers from a webpage.

Wrapping up

In this post, we discussed how to collect phone numbers from a webpage using JavaScript. We covered the basics of phone number extraction, as well as provided examples and tips on how to effectively collect phone numbers using JavaScript. By following the steps outlined in this post, you can use JavaScript to collect phone numbers from a webpage for various purposes.

Remember, it is important to consider the legal and ethical implications of phone number extraction, and to make sure to follow the terms of service for any websites from which you are collecting phone numbers. Additionally, it is important to test and debug your code before implementing it on a live webpage.

By following these guidelines, you can effectively collect phone numbers from a webpage using JavaScript, and use them for marketing, lead generation, or other purposes.

Categories
CSS HTML JavaScript

10 Common Mistakes Made by New Web Developers (And How to Avoid Them)

Web development can be a challenging and rewarding field, but it’s easy for beginners to make mistakes that can hinder the success of their projects. In this article, we’ll explore the most common mistakes that people new to web development make, and offer tips on how to avoid them. Whether you’re just starting out as a web developer or have been working in the field for a while, this information is essential for ensuring that your projects are successful and your skills are sharp.

Not planning ahead

One of the biggest mistakes that new web developers make is failing to properly plan their projects. This can lead to a host of problems, including missed deadlines, budget overruns, and poor user experiences.

To avoid these issues, it’s important to start your projects by creating a detailed plan that outlines your goals, budget, timeline, and resources. This will help you stay organized and focused, and ensure that you’re able to complete your projects on time and on budget.

Not testing your code

Testing your code is an essential part of the web development process, but it’s often overlooked by beginners. Failing to test your code can lead to a host of problems, including bugs, security vulnerabilities, and poor user experiences.

To ensure that your code is of high quality, it’s important to test it thoroughly before launching your website or app. This may include manual testing, automated testing, and user testing to ensure that everything is functioning as intended.

Not optimizing for mobile

In today’s digital age, it’s essential that websites and apps are optimized for mobile devices. However, many new web developers overlook this important aspect of development, resulting in poor user experiences for those accessing their sites on smartphones or tablets.

To ensure that your website or app is mobile-friendly, it’s important to test it on a variety of devices and screen sizes. You should also consider using responsive design techniques, which allow your site to automatically adapt to different devices and screen sizes.

Not optimizing for search engines

SEO (search engine optimization) is an essential aspect of web development, as it helps to ensure that your site is visible to search engines like Google. However, many new web developers overlook this important aspect of development, resulting in poor search engine rankings and reduced traffic to their sites.

To optimize your site for search engines, it’s important to conduct keyword research, create high-quality content, and implement technical SEO best practices, such as using header tags and optimizing your site’s loading speed.

Not using version control

Version control is a system that helps to track changes to your code over time, making it easier to collaborate with other developers and revert back to previous versions if necessary. However, many new web developers overlook this important aspect of development, which can lead to a host of problems.

To ensure that you’re able to collaborate effectively with other developers and maintain control over your code, it’s important to use version control systems like Git. These systems allow you to track changes to your code, collaborate with others, and revert back to previous versions if necessary.

Not keeping up with industry trends

Web development is a constantly evolving field, and it’s essential that you stay up-to-date with the latest technologies and best practices. However, many new web developers neglect to keep up with industry trends, which can hinder the success of their projects and limit their career opportunities.

To stay current in the field, it’s important to regularly attend conferences and workshops, read industry blogs and publications, and participate in online communities. This will help you stay up-to-date with the latest technologies and best practices, and ensure that your skills are relevant and in demand.

Not asking for help when needed

Web development can be a complex field, and it’s natural to encounter challenges and roadblocks along the way. However, many new web developers make the mistake of trying to tackle these problems on their own, rather than seeking help when needed.

Asking for help is a critical part of the learning process, and it’s important to remember that there are always people who are willing to lend a hand. Whether it’s reaching out to a colleague, seeking guidance from an experienced mentor, or posting a question on an online forum, don’t be afraid to ask for help when you need it.

Not taking security seriously

Web security is an essential aspect of development, as it helps to protect your site and your users from potential threats like hacking and data breaches. However, many new web developers overlook security, resulting in vulnerabilities that can compromise the safety and integrity of their sites.

To ensure that your site is secure, it’s important to implement best practices like using secure passwords, keeping your software and plugins up-to-date, and using SSL certificates to encrypt data transmitted between your site and your users.

Not considering user experience

The user experience (UX) of a website or app is critical to its success, as it determines how easily and effectively users are able to interact with your site. However, many new web developers overlook UX, resulting in confusing or frustrating user experiences.

To ensure that your site has a positive UX, it’s important to consider the needs and expectations of your users, and design your site accordingly. This may include conducting user research, creating wireframes and prototypes, and testing your site with a variety of users to ensure that it meets their needs.

Not learning from your mistakes

Finally, it’s important to remember that making mistakes is a natural part of the learning process. The key is to learn from your mistakes and use them as opportunities for growth and improvement.

By actively seeking feedback, seeking out new learning opportunities, and reflecting on your experiences, you can continuously improve your skills and avoid making the same mistakes in the future.

Avoiding these common mistakes

Web development can be a challenging field, but by avoiding these common mistakes, you can set yourself up for success. Whether you’re just starting out as a web developer or have been working in the field for a while, it’s important to stay organized, test your code, optimize for mobile and search engines, use version control, stay up-to-date with industry trends, seek help when needed, prioritize security, consider user experience, and learn from your mistakes. By following these tips, you can create high-quality websites and apps that meet the needs of your users and achieve your goals.

Categories
JavaScript

Automatically refresh your browser after 30 seconds with JavaScript

Have you ever been waiting for a webpage to update and gotten tired of hitting the refresh button over and over again?

I know I have, especially when I need to buy tickets for a show or concert.

I sometimes find myself hitting the refresh button hundreds of times an hour in the hopes of capturing the instant the tickets go on sale.

It’s an annoying process, for sure.

But luckily, we have JavaScript!

In this guide, I’ll show you how to use JavaScript automatically refresh your browser after 30 seconds.

It’s actually pretty easy. So let’s get started.

  1. Open the webpage that you want to refresh in your browser.
  2. Right-click on the webpage and select “Inspect” (or “Inspect Element” depending on your browser). This will open the developer console.
  3. In the developer console, go to the “Console” tab. This is where you can enter and run JavaScript code.
  4. To refresh the page every 30 seconds, use the setInterval function. The setInterval function takes two arguments: a callback function, and the interval time in milliseconds.
setInterval(function() {
  // code to refresh page goes here
}, 30000);

To refresh the page, you can use the location.reload function. This function will reload the current webpage from the server rather than using a cached version.

setInterval(function() {
  location.reload();
}, 30000);

Press “Enter” to run the code. The page will now refresh every 30 seconds.

If you want to stop the page from refreshing, you can use the clearInterval function. This function takes the interval ID returned by the setInterval function and stops the interval from running.

// stop the interval from running
clearInterval(intervalId);

Keep in mind that constantly refreshing a webpage can put a strain on the server and may not be the best user experience. It’s important to consider if automatic page refresh is necessary and to use it sparingly.

Additionally, the JavaScript code that you enter in the developer console will only run while the console is open. If you close the console, the page will stop refreshing.

Et voila! That’s it!

Pretty simple, eh?

Categories
JavaScript

Mastering JavaScript: The Essential Concepts for Aspiring Developers

As one of the most popular programming languages in the world, JavaScript is an essential skill for any aspiring developer. In this article, we will discuss the most important concepts to master to become proficient in JavaScript.

Variables

Variables are used to store data in a program. In JavaScript, there are several different types of variables, including strings, numbers, and Booleans. It is important to understand how to declare and assign values to variables and use them in expressions and statements.

Data types

In addition to the basic data types mentioned above, JavaScript has more complex data types, such as arrays and objects. Understanding how to work with these data types is crucial for storing and manipulating data in your programs.

Control structures: Control structures are used to control the flow of a program. In JavaScript, the main control structures are if/else statements, for loops, and while loops. It is important to understand how to use these structures to make decisions and repeat actions in your code.

Functions

Functions are blocks of code that can be defined and called upon when needed. In JavaScript, functions can be defined with or without arguments and can return a value if needed. Understanding how to write and use functions is essential for organizing and reusing code in your programs.

Objects

Objects are data structures that store data in a key-value format. In JavaScript, objects can be used to represent real-world entities and can be created using constructor functions or object literals. Understanding how to create and work with objects is important for organizing and accessing data in your programs.

Arrays

Arrays are data structures that store a list of items. In JavaScript, arrays can hold any type of data and can be created using array literals or the Array constructor. Understanding how to create and work with arrays is important for storing and manipulating lists of data in your programs.

DOM manipulation

The DOM, or Document Object Model, is a representation of a web page as a tree of objects. In JavaScript, it is possible to manipulate the DOM by adding, deleting, or modifying elements on a page. Understanding how to manipulate the DOM is essential for building interactive web applications.

Asynchronous programming

Asynchronous programming is a way to execute code in a non-blocking manner. In JavaScript, asynchronous programming is achieved through the use of callback functions, promises, and async/await. Understanding how to use these techniques is important for building responsive and scalable applications.

Error handling

No matter how well you write your code, errors and exceptions are an inevitable part of programming. In JavaScript, it is important to understand how to handle errors and exceptions in order to prevent your program from crashing.

By mastering these concepts, you will have a strong foundation in JavaScript and be well on your way to becoming a proficient developer. As you continue to learn and grow, it is important to stay up-to-date with the latest developments and best practices in the JavaScript community. With dedication and practice, you can become an expert in JavaScript and build powerful and interactive web applications.

Categories
JavaScript

The Benefits of Learning JavaScript for Non-Developers: How it Can Improve Your Life

Learning JavaScript can seem intimidating, especially if you have no background in programming. But it doesn’t have to be. JavaScript is an incredibly powerful and versatile language that can provide a range of benefits to non-developers. From website development to game design, it can open the door to a world of opportunities and new ideas. Learning JavaScript can even help improve your life in surprising ways, such as enhancing your problem-solving skills and boosting your confidence. Whether you’re a designer, a marketer, an entrepreneur, or just someone who wants to learn something new, JavaScript can provide a range of benefits that can help you take your skills to the next level. So, let’s take a look at the benefits of learning JavaScript for non-developers, and how it can help improve your life.

What is JavaScript?

JavaScript is a programming language that was developed in the 1990s for creating interactive websites. It was designed to run in a browser and to be interpreted by a browser engine. It can be used on both client-side and server-side programming and is commonly embedded into HTML code. JavaScript is a high-level programming language, meaning it is similar to languages like Java and C++. However, it is an interpreted language, which means that it doesn’t need to be compiled into machine code. JavaScript was created by Brendan Eich, who also created Java. JavaScript’s popularity increased dramatically when Tim Berners-Lee released the first version of the World Wide Web. Since then, JavaScript has become a crucial part of the web, and is used for tasks ranging from website development to game design.

Benefits of learning JavaScript for non-developers

While programming is a crucial skill for any developer, learning JavaScript can provide several benefits for non-developers. These include improved problem-solving skills, boosted confidence and creativity, and the opportunity to open the door to new opportunities. If you’re interested in learning JavaScript, but don’t want to become a developer, these benefits can help show you how it can improve your life.

Improved problem-solving skills

Problem-solving is a crucial skill for any type of work, and it can be beneficial to learn new ways to approach problems. While programming is often approached with a structured and logical approach, JavaScript has a more unpredictable nature. This can make it more difficult to predict how the code will behave. However, it can also provide more freedom and flexibility when tackling problems. By having a more open mindset toward problem-solving, you can tackle problems in new ways that allow you to create interesting and unexpected things.

Boosted confidence and creativity

Learning how to create with JavaScript can be a daunting task. But, once you understand the basics and get used to its quirks, you can create some amazing things. Creating interactive and engaging content can be a great way to boost your confidence. It can also help you become more creative as you try to figure out new ways to use JavaScript to develop your ideas. By learning JavaScript, you can open the door to creating new and interesting things that you might not have otherwise been able to create. You can create new interactive content for websites or explore ways to use JavaScript in your creative projects.

Open the door to new opportunities

The best way to learn is to teach, so don’t just learn from others, but also share what you’ve learned with others. By learning JavaScript, you can open the door to new opportunities and share your skills with others. Whether you want to become a teacher or want to improve your chances of getting a job, learning JavaScript can open the door to new opportunities. This can be beneficial in a range of different fields, including marketing, design, and entrepreneurship.

How to learn JavaScript

The best way to learn is to start small. You don’t need to learn everything there is to know about JavaScript; you just need to learn the basics. This will help you get started with the language and give you a basic understanding of how it works. There are a number of different ways you can learn JavaScript, including online courses and tutorials, books, or interactive websites. There are also a range of JavaScript challenges and competitions, where you can apply your skills in fun and interesting ways.

JavaScript learning resources

There are a number of different resources you can use to learn JavaScript. This includes online courses, tutorials, and books. There are also a number of interactive websites where you can apply your skills in a fun and interactive way. You can also find a range of JavaScript challenges and competitions, where you can apply your skills in a fun and competitive way.

Practical applications of JavaScript

JavaScript is a versatile language that can be applied in a range of different industries and situations. This includes website development, where it can be used for tasks such as manipulating images and creating animations. JavaScript can also be used for data visualization and mapping, as well as scientific and mathematical functions. JavaScript can also be applied in marketing, where it can be used for tasks such as website analytics and email marketing. It can also be applied in design, where it can be used for tasks such as 3D modeling and creating interactive visuals. JavaScript is also becoming increasingly popular in education. It can be used for tasks such as creating immersive and engaging content, and exploring concepts in a new and exciting way.

Examples of successful JavaScript projects

As we’ve discussed, JavaScript can be applied in a range of different industries and situations. This includes creating new and innovative educational content, improving website analytics and design, and creating new and exciting ways to explore concepts. Let’s take a look at a few examples of successful JavaScript projects: – Virtual Reality – Virtual reality has become increasingly popular in recent years. It’s used in a variety of scenario, ranging from gaming to education. To create virtual reality experiences, developers use JavaScript for real-time 3D rendering, interacting with sensors, and designing virtual environments. – Education – Education is becoming more and more immersive and interactive. This is particularly true when it comes to online learning. This can be a great way to engage students and provide a new and exciting experience. One example of how JavaScript is being used in education is in Virtual Human Interaction Lab (VHIL). VHIL uses a combination of virtual reality and motion-capture technology to allow students to engage with avatars of real people. – Improved website analytics – One of the most important aspects of running a website is understanding its users. This can be difficult if you’re not a developer. However, JavaScript can be used to create new and innovative ways of understanding website visitors. One example of this is Hotjar. Hotjar is a tool that uses website analytics to provide insights into user behavior. It provides information such as where users are clicking, their journey through the website, and their device type. It also provides information about where users are coming from, and what they are doing once they leave the website.

Examples of successful non-developers using JavaScript

JavaScript is a powerful language that can be applied in a wide range of industries. This includes marketing, education, and design. It can also be used to create new and innovative ways to explore concepts. These are just a few examples of how non-developers can use JavaScript to create new and engaging content. Let’s take a look at a few examples of successful non-developers who have used JavaScript: – Marketing – When marketing your products or services, it’s important to use different and innovative methods. This can help you stand out and engage with your audience in new ways. One example of how JavaScript is being used in marketing is with interactive infographics. These are visual representations of information that are usually designed using online tools. They’re a great way to convey information quickly and effectively. – Design – Design is becoming increasingly digital. This means that designers can use a variety of new tools and methods to create new and exciting designs. One example of how JavaScript is being used in design is with 3D modeling. This is a highly creative process that can be used to create a range of design elements. A popular example of this is designing logos and other branding elements using software like Sketch or Autodesk.

Conclusion

Learning JavaScript can be a daunting task for anyone, but it can be particularly challenging for non-developers. However, it is a worthwhile investment and can open the door to a range of different opportunities. It can also help improve your life.

Categories
JavaScript

Object-oriented programming with JavaScript

Good JavaScript programming needs a process — a way to guide how you think about problems and how you write code to solve these problems.

Arbitrarily inventing and improvising your code’s structure is fine for a beginner, but any technical recruiter administering a JavaScript proficiency test will always consider this amateurish at best.

So stop improvising your code structure and writing spaghetti JavaScript.

How?

Use a programming paradigm.

In JavaScript, one of the best programming paradigms is the object-oriented paradigm.

It’s a set of principles that guide the logic of your code structure and how you should write your JavaScript.

And while it has technical aspects, it is not solely a technical component of JavaScript, as a function or loop is. It’s also a way of thinking about problems and a set of rules about how to write your code to solve these problems.

In its simplest interpretation, it’s nothing more than a way to structure your code.

In its most complex, it’s a set of methodologies to guide how you think about and solve problems with your JavaScript code.

This guide will help you understand and apply the object-oriented programming paradigm.

Object-oriented programming

Object-oriented programming relies heavily on objects and is based on four scary-sounding principles:

  • encapsulation
  • abstraction
  • inheritance
  • polymorphism

Each principle is applied through JavaScript objects, meaning you’ll be using objects to structure and organize your program.

You’ll still use functions and loops and all your favorite JavaScript methods, but they will all be organized within and around the capabilities of objects.

Let’s explore these principles to help you understand what they mean.

Encapsulation

Or, in simpler terms — keep related parts of your code grouped together.

Your JavaScript programs will always have portions of code that are directly related to each other.

The principle of encapsulation dictates that when you have code that can be grouped together, you group it together.

Take a look at the code below, do you see any groups that the statements can be organized into?

let dogBreed = "Golden Retriever"
let dogColour = "Yellow";
let dogAge = 2;
let dogSound = function() {
alert("Woof Woof!");
};
let catBreed = "Tabby";
let catColour = "Grey";
let catAge = 3;
let catSound = function() {
alert("Meooooow!");
}
      

Right, the two categories are fairly obvious: dog and cat.

Following the principle of encapsulation, let’s reorganize our code with the use of JavaScript objects.

Here’s what that looks like:

let dog = {
  breed: "Golden Retriever",
  colour: "Yellow",
  age: 2,
  sound: function () {
    alert("Woof Woof!");
  },
};

let cat = {
  breed: "Tabby",
  colour: "Grey",
  age: 3,
  sound: function () {
    alert("Meooooow!");
  },
};	

That’s really it, to apply this principle you just need to make sure that when you have code that can be grouped together, you group it together.

And with the use of the encapsulation principle, we can ensure that data and methods are all grouped together, thereby making your code easier to understand and maintain.

Abstraction

Or, in simpler terms — keep the JavaScript objects you create simple.

Objects have a tendency to become unnecessarily complex as they are versatile and have no limit to the number of methods or properties they can contain.

The principle of abstraction encourages you to keep your object simple by only using the methods and properties which are essential to the object to perform it’s desired output.

Let’s consider a TV through the lens of abstraction to arrive at a better understanding of the concept.

A TV does many things, it can turn on, turn off and switch to specific channels, and you can even cast content to it from your phone.

A TV also has many properties: weight, size, colour, age, and brand.

Through the lens of abstraction, if we were to create a JavaScript object to allow the TV to turn on, that object should only contain the properties and methods directly related to making the TV turn on, everything else is irrelevant.

In other words, the object is an abstraction of the TV as a whole. It is a simplified version of a TV as it does not contain all the properties and capabilities of a TV, but only what is necessary to allow the TV to turn on.

Let’s write some code to demonstrate how abstraction works for this TV object designed to turn the TV on.

Here’s what the object might look like without abstraction.

turnOnTV = {
  tvAge: 4,
  tvColour: "black",
  tvHeight: 45,
  tvBrand: "Samsung",
  turnOn: function() {
  console.log("TV is on");
  }
}

Here’s what the object looks like with abstraction.

turnOnTV = {
  turnOn: function() {
  console.log("TV is on");
  }
}

Notice how the second version only contains what is necessary to allow the TV to turn on?

That’s the essence of abstraction. Only put in your objects what is necessary.

Inheritance

Or, in simpler terms — reduce repetition.

When using objects in JavaScript we often end up with a lot of very similar objects. Many times you’ll need an object to have the same method or property as an existing object.

Object-oriented programming seeks to minimize the confusion that similar objects have through inheritance.

This is a bit of a tricky concept, so let’s use an analogy of a library.

Think of a library with thousands of books. While each of these books may be unique, they are all still books, and books can all be read.

Thinking of this through the principle of abstraction and objects, we’d want to have a single instance of the read method that is shared (inherited) by all books.

We can do this with the use of a JavaScript prototype.

A prototype allows you to create objects that are based on a single, master object. In JavaScript, this process is called instantiation.

For books, we’d want our prototype to contain a read function so that any time a new book object is instantiated from it, it contains the same read method, saving us from having to recreate the same read method for every book.

Let’s use some code to help illustrate the concept of inheritance and prototypes in action.

First, let’s create a prototype for the book.

function Book(title, author, year, category) {
  this.title = title;
  this.author = author;
  this.date = year;
  this.category = category;
  this.read = read() {
  console.log("You are reading this book!");
  }
}

Next, let’s instantiate a new object based on the prototype.

function Book(title, author, year, category) {
  this.title = title;
  this.author = author;
  this.date = year;
  this.category = category;
  this.read = function() {
  	console.log("You are reading this book!");
  }
}

let book1 = new Book("Dune", "Frank Herbert", 1965, "science fiction");

Now that you’ve instantiated a new object from the prototype, try calling the function from the Book prototype with the book1 object in your JavaScript console.

Notice how the book1 object has the read method even though it wasn’t specified when you were creating it?

The book1 object has the read method because it inherited it from the Book prototype.

With the use of the inheritance principle, we can ensure that data and features used by multiple objects are contained in a single source, thereby reducing the need for repetition and making your code easier to maintain.

Polymorphism

Or, in simpler terms — your JavaScript statements can have varied outputs.

The concept of polymorphism is the trickiest of the four principles for me. It took me quite some time to wrap my head around the concept and how to apply it, but I think the explanation that follows will help you avoid some of the headaches I experienced.

The word polymorphism is ancient Greek and translates roughly to many kinds. In JavaScript, this means a statement can have many varied outputs.

Think of the prototype concept we just explored in the previous section which can pass on a method or property to an instantiation.

Polymorphism allows each instantiation to produce its own unique output when using a method or property inherited from a prototype.

Let’s look at an example using animal sounds to better understand how polymorphism works.

First, let’s create an Animal prototype that receives a parameter for the sound an animal makes.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}

Next, let’s instantiate three objects from the Animal prototype and give them each a unique sound.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}
    var dog = new Animal("woof");
    var cat = new Animal("meow");
    var cow = new Animal("moo");

Next, let’s create a function to display each of the sounds in the console.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
}
}
    var dog = new Animal("woof");
    var cat = new Animal("meow");
    var cow = new Animal("moo");

function showInfo(obj){
    console.log(obj.speak());
}

And finally, let’s log each of the sounds to the console.

function Animal(sound){
    this.sound = sound;
    this.speak = function(){
        return this.sound;
	}
}
var dog = new Animal("woof");
var cat = new Animal("meow");
var cow = new Animal("moo");

function showInfo(obj){
    console.log(obj.speak());
}

showInfo(dog);
showInfo(cat);
showInfo(cow);

Notice how each instantiation of the Animal object passes its own unique argument to the same speak method and a single speak method has three different outputs? This is polymorphism.

Within the Animal prototype there is a single method speak. Within each instantiation of this prototype (dog, cat and cow) the method expresses different outputs.

So, to reiterate, your JavaScript statements can have varied outputs. This is polymorphism.

Applying the principle of polymorphism allows you to keep your code organized and efficient by minimizing the need for repetition.

Applying Object-oriented programming methodology to your problem solving

To use the object-oriented programming methodology effectively you must teach yourself how to look at problems through an object-oriented lens.

Now that we’ve covered the four principles of object-oriented programming: encapsulation, abstraction, inheritance, and polymorphisms, I want to share my approach to looking at problems through an object-oriented lens.

But first, I want to acknowledge that there are many articles expressing countless views on how you can, should, and should not think about programming in JavaScript.

I suspect that over time JavaScript developers each develop a unique approach to writing JavaScript and that every one of them will profess to you that their approach is the best.

I’m not going to argue that my approach is the best, but simply that it works for me.

My approach is simple and relies on following the steps:

  1. Deconstructing each part of your problem.
  2. Encapsulating each part into an object.
  3. Ensuring each object is an abstraction and contains only what is necessary to arrive at the desired output.
  4. Applying Inheritance and polymorphism to reduce complexity.

Let’s take a try using the four steps above on this Netflix homepage.

First, let’s deconstruct the parts of the homepage.

I see three main parts: the navigation, the hero image, and the “Popular on Netflix” slider.

Now that we’ve deconstructed the page, let’s create an object for each component.

let navBar = {};
let heroImage = {};
let popSlider = {};

Now, let’s use abstraction to add properties and methods to the navBar and heroImage objects.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg"
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

let popSlider = {

};

Seeing as the popSlider object has a number of movies, we’ll use the principle of inheritance and create a prototype to avoid repetition.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}

Now let’s instantiate some objects from the popSlider prototype.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}
let pop1 = new popSlider("Have a Good Trip", 2020, "documentary");
let pop2 = new popSlider("The Last Dance", 2020, "documentary");
let pop3 = new popSlider("Deadpool 2", 2019, "action");
let pop4 = new popSlider("Jerry Seinfeld", 2018, "comedy");
let pop5 = new popSlider("Into the Night", 2017, "suspense");

Finally, let’s use the principle of polymorphism to use our inherited movie method to list the title of each of our popSlider instantiations.

let navBar = {
  logo: "netflix-logo.jpg",
  homeBtn: "netflix.com",
  tvBtn: "netflix.com/tv",
  moviesBtn: "netflix.com/movies",
  latesBtn: "netflix.com/latest",
  myListBtn: "netflix.com/list"
};

let heroImage = {
	mainImage: "theLastDance.jpg",
  	playBtn: function() {
    console.log("starting your show");
    },
    moreInfoBtn: function() {
    console.log("here's more info");
    }
};

function popSlider(title, year, category) {
  this.title = title;
  this.date = year;
  this.category = category;
  this.movie = function() {
  	console.log(this.title);
  }
}
let pop1 = new popSlider("Have a Good Trip", 2020, "documentary");
let pop2 = new popSlider("The Last Dance", 2020, "documentary");
let pop3 = new popSlider("Deadpool 2", 2019, "action");
let pop4 = new popSlider("Jerry Seinfeld", 2018, "comedy");
let pop5 = new popSlider("Into the Night", 2017, "suspense");

function showInfo(obj){
    console.log(obj.movie());
}

showInfo(pop1);
showInfo(pop2);
showInfo(pop3);
showInfo(pop4);
showInfo(pop5);

And there you have it, you’ve now got a working understanding of object-oriented programming and are well on your way to becoming an intermediate JavaScript developer.

This is one of the most challenging topics for beginners, so congratulations on making it this far.

Categories
JavaScript

Beginner’s guide to JavaScript objects

Objects are one of the most elegant, simple and extraordinarily useful tools you’ll ever work with when programming in JavaScript.

In fact, objects are one of the reasons why JavaScript is such a popular and widespread programming language.

And if you want to improve your JavaScript programming from beginner to intermediate, you’ll need to understand JavaScript objects.

In fact, without understanding JavaScript objects, you’ll never really understand JavaScript, as almost everything in JavaScript is an object.

This guide will help you understand objects in the JavaScript language. Specifically, it will help you understand object syntax and how to write and use the objects you create.

What are JavaScript objects

The easiest way to think of a JavaScript object is as a container that holds related variables and functions. Sort of like a storage container.

Imagine you have a container and you fill it with sewing items.

You could label this container “sewing supplies” and fill it with thread, needles, pins, and other sewing related items.

This sewing supplies container helps keep your sewing supplies organized and easy to find.

A JavaScript object does the same thing. It helps you keep your data organized and easy to find, and things that help keep your data organized and easy to find are often referred to as data structures.

Actually, you may already be familiar with data structures if you read my beginner’s guide to arrays.

Either way, if it helps you keep your data organized, it’s a data structure, and objects are some of the most useful and simple data structures.

In fact, a JavaScript object is really nothing more than a collection of related name-value pairs, and name-value pairs really only consist of two things: a data value and the name that is used to identify that data value.

Here’s what a name-value pair looks like in a basic JavaScript statement:

let myName = "Daniel"	

The name in the example above is myName and the value assigned to it is "Daniel".

Here’s what a name-value pair looks like for a function:

let myFunction = function() {
console.log("Hello!");
}

The name in the example above is myFunction and the value assigned to it is function() {console.log("Hello!");}

A JavaScript object is, as mentioned, a collection of name-value pairs grouped together.

Here’s what the two examples above would look like organized into a JavaScript object:

let nameValuePairExamples = {
 myName: "Daniel",
 myFunction: function() {
 console.log("Hello!");
 }
};

Both the variable declaration and function declaration from the two previous examples are now within the nameValuePairExamples object.

In other words, a JavaScript object is not only a collection of name-value pairs, but the object itself is like a container you can use to group the name-value pairs. Just like the sewing supplies container.

Here’s another example to demonstrate how a JavaScript object is like a container.

Let’s imagine we wanted to group together a set of attributes for someone named Steve.

In this example, Steve would be the object and the name/value pairs would be the properties of Steve.

Here’s what this looks like:

let steve = {
 height: 190,
 weight: 185,
 hairColour: black,
 alias: "Smiley",
 sayHelloSteve: function() {
 alert("Hello Steve!");
 }
}
};

Simple right? All of the name-value pairs: height: 190, weight: 185, hairColour: black and sayHelloSteve: function() {alert("Hello Steve!"); all fit nicely under the category Steve, which is the object name: steve.

Also, notice how much easier it is to understand that the name-value pairs are all associated with the object steve?

This is a huge help when working on enormous projects with thousands of lines of code.

Now let’s take a look at JavaScript object syntax.

JavaScript object properties, methods and syntax

As mentioned, a JavaScript object is a collection of name-value pairs.

In JavaScript, object name-value pairs have two types: properties and methods.

Let’s take a look at both object properties and methods and then deconstruct a JavaScript object to understand its syntax further.

Object properties

Object properties are any variable declarations within the object that are not functions.

Here’s what this looks like using a car as an example:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
};

Each variable declaration contained within the opening { and closing } of the myCar object: brand: "Subaru" colour: "Blue" and year: 2019 are all properties of the myCar object.

All of these variables declarations are not function declarations and so they are properties of the object.

Object methods

Object methods are function declarations within the object.

Let’s continue with the car example, but this time we’ll create two methods instead of properties for the myCar object.

Here’s what this looks like:

let myCar = {
	carStart: function() {
    alert("Engine is on");
    },
  	carShutdown: function() {
    alert("Engine is off");
    }
}

Each function declaration contained within the opening { and closing } of the myCar object: carStart: function() {alert("Engine is on");} and carShutdown: funtion() {alert("Engine is off");} are all methods of the myCar object.

All of these declarations are function declarations and so they are methods of the object.

To reiterate: any variables contained within the object that are not functions are called properties, while any functions declared within the object are called methods.

Now let’s deconstruct a JavaScript object with both properties and methods to get a better understanding of how objects work.

Object syntax

An empty object in JavaScript is created with the following:

let myNewObject = {};

let myNewObject = asssigns the variable named myNewObject to the object specified by the opening { and closing }.

In JavaScript, an object is created and its contents are defined within the opening { and closing }.

In the example above, however, the object is empty.

Let’s explore the syntax further by deconstructing an object which has content within the opening { and closing } and combines the properties and methods from the car examples from the previous section.

Here’s what that looks like:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
  	carStart: function() {
    	alert("Engine is on");
    },
  	carShutdown: function() {
    	alert("Engine is off");
    }
};

Ok, the first part you should be familiar with already.

let myCar = asssigns the variable named myCar to an object.

The first statement within the object opening { and closing } is brand: "Subaru". This is a property statement, one of the two types of name-value pairs allowed by JavaScript objects: properties and methods.

brand: "Subaru", is a property of the myCar object. The property name is brand, the value is "Subaru", and a colon : is used to assign the property name to the value.

You indicate that there’s another statement in the object with a ,.

As you can see, there’s another property after brand: "Subaru" which is colour: "Blue". So to indicate there’s another property statement in the object you’d write a , after brand: "Subaru".

Following the property statement colour: "Blue" is another property statement year: 2019.

Each statement in an object must end with a comma , if there is a statement following it.

If it’s the last statement in the object then it does not require a ,.

Following the last property statement year: 2019 you’ll see the other type of statement for a JavaScript object, a method statement, which contains a function.

The first method statement of the myCar object is carStart: function() { alert("Engine is on"); }.

The method statement name is carStart and is assigned to the value with a :. The actual function value which follows is the same syntax as a regular JavaScript function: function() { alert("Engine is on"); }.

And, as we mentioned previously, each statement unless it’s the last statement, ends with a ,.

The final statement in the myCar object is another method statement: carShutdown: funtion() { alert("Engine is off"); }.

Since this is the final statement in the myCar object, there’s no need for a final ,.

Okay, so that covers object properties, methods and syntax.

Now let’s take a look at how you call and reference objects and their properties and methods.

Calling properties and methods of a JavaScript object

Accessing information within a JavaScript object is straightforward.

You can access the properties and methods within an object by calling the object name followed by a . and then the name of the property or method you’d like to access.

Let’s imagine we wanted to access the year property of the myCar object below:

let myCar = {
	brand: "Subaru",
  	colour: "Blue",
  	year: 2019,
  	carStart: function() {
    	alert("Engine is on");
    },
  	carShutdown: function() {
    	alert("Engine is off");
    }
};

If you wanted to access or reference the year property of the myCar object you’d use: myCar.year.

If you wanted to access or reference the carShutdown method of the myCar object you’d use myCar.carShutdown().

If you wanted to list all the properties and methods available to an object you’d simply type the object name in your JavaScript developer console.

In this example that would be myCar.

Ok, pretty handy right?

I think so!

Hopefully, you now have a better grasp on JavaScript objects, their syntax, and how to write and use the objects you create.

Next up, let’s take a look at how to apply your knowledge of JavaScript objects to write better code through an object-oriented programming paradigm.

Categories
JavaScript

Conditional statements in JavaScript

One of the most incredible powers you can give to your JavaScript program is the ability to make decisions on its own.

Whether you want your program to decide the best time to ask a visitor to subscribe to your newsletter or display your site content in a different language, conditional statements will allow your JavaScript program to make decisions based on conditions and then act on them.

In a way, conditional statements give intelligence to your programs. And this adds a powerful layer of sophistication to any JavaScript program.

This guide will help you understand conditional statements in the JavaScript language. Specifically, it will help you understand conditional statement syntax and how to write and use conditional statements.

What is a JavaScript conditional statement?

A conditional statement tells JavaScript how it should behave when a certain condition is met.

For example, if a user visits your website and their preferred language is French, you could use a JavaScript conditional statement to determine the user’s preferred language is French, and then display the content of your website in French to them.

The best part? You aren’t limited to a single condition, you can repeat this approach for any number of conditions — if the user prefers German, display the page in German, if they prefer Russian, display it in Russian.

An interesting thing about conditional statements is how simple they are. A conditional statement really has only two parts:

  1. the condition
  2. the action to perform once the condition is met

In the language examples above, the condition would be the user’s language preference, and the action to perform would be to display the content in the preferred language.

Another way to think of a conditional statement is to compare it to how you’d make a decision about what time you’ll wake up.

Let’s imagine you had a job that required you to arrive at work by 9 a.m. from Monday to Friday.

Let’s also imagine that you needed to wake up two hours before 9 a.m to arrive to work on time.

The conditions in this example would be pretty simple:

If it’s Monday, Tuesday, Wednesday, Thursday or Friday, you’ll need to wake up at 7 a.m., otherwise, you can wake up any time you’d like.

Let’s take a look at JavaScript conditional statement structure and syntax to get a better grip on how it works.

JavaScript conditional statement structure and syntax

Conditional statements in JavaScript rely on a set of three basic syntax keywords: if, else and else if.

Here’s what this looks like:

if (condition === true) {
  //execute this code
}
else if (alternative condition === true) {
  //execute this code
}
else {
  //execute this code
}

Let’s break down what’s actually going on here:

  1. You specify a condition to match within the opening ( and closing ) with the keyword if.
  2. JavaScript checks if the condition is matched.
  3. If the condition is matched, JavaScript identifies the condition as true.
    • JavaScript then executes the code within the opening { and closing } associated with the condition which is true.
  4. If the condition is not matched, JavaScript identifies the condition as false.
    • JavaScript skips the code associated with the condition which returned false and proceeds to check if the condition within the next else if statement is true.
      • If the condition is matched, JavaScript identifies the condition as true and executes the code within the associated opening { and closing }.
      • If the condition is not matched, JavaScript identifies the condition as false.

The process above is repeated until each condition is checked.

If none of the conditions return true then the final else statement will run.

Once a condition is matched as true the conditional statement stops running. Only if the condition is false will JavaScript proceed to the next condition.

Let’s dissect the syntax.

The if keyword tells JavaScript which condition it should listen for.

The content within the opening ( and closing ) is the specific condition that must be matched. They will return as either true if matched and false if not matched.

The code between the opening { and closing } will run if the preceding condition is true.

The else if keyword tells JavaScript what to do when the previous condition is false, and the associated opening { and closing } is the code JavaScript will then execute.

The else keyword tells JavaScript what to do when none of the previous conditions are true. The code within the associated opening { and closing } is the code JavaScript will then execute.

Let’s take a look at another example using our alarm clock where the if condition is Monday, Tuesday, Wednesday, Thursday or Friday.

Here’s what this looks like:

if (Monday, Tuesday, Wednesday, Thursay or Friday === true) {
  //execute this code
  console.log("Time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

To reiterate, when it is Monday, Tuesday, Wednesday, Thursday or Friday, the if condition will return as true.

When the if condition is true JavaScript will execute the code within the associated opening { and closing }. In the code example above, this is console.log("Time to wake up!");

Otherwise, if the condition is false, and it is not Monday, Tuesday, Wednesday, Thursday or Friday, JavaScript will skip the associated code within the opening { and closing } and instead execute the code within the opening { and closing } which follows the else keyword.

Additionally, as mentioned, you are not limited to two conditions, you can add as many conditions as you’d like with else if.

Here’s what this looks like:

if (Monday === true) {
  //execute this code
  console.log("It's Monday, time to wake up!");
}
else if (Tuesday === true) {
  //execute this code
  console.log("It's Tuesday, time to wake up!");
}
else if (Wednesday === true) {
  //execute this code
  console.log("It's Wednesday, time to wake up!");
}
else if (Thursday === true){
  //execute this code
  console.log("It's Thursday, time to wake up!");
}
else if (Friday === true){
  //execute this code
  console.log("It's Friday, time to wake up!");
}
else {
  //execute this code
  console.log("It's ok, you can sleep in");
}

Clear as mud?

Don’t worry, let’s practice by building a working alarm clock, it’s the perfect way to get a real understanding of conditional statements.

Writing a program with JavaScript conditional statements

Let’s start by creating a few variables in your JavaScript developer console to get the current day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

The variable currentDate uses the new Date() constructor to tell your web browser what date it is.

The variable dayOfWeek then applies the getDay() method to currentDate and returns an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday and 6 for Saturday.

Let’s add a conditional statement to alert us if it’s a day of the week.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}

Notice the use of ||, called an OR logical operator, within the opening ( and closing )?

This tells JavaScript that it can match 0 or 1 or 2 or 3 or 4 or 5 or 6.

They are really useful and allow you to specify multiple conditions for a single set of actions. In the example above, it allows us to specify each day of the week.

Ok, now let’s add an else keyword to our code to tell JavaScript what to do when it’s a weekend and the conditions above are not met.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 3 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

Now, let’s make this a bit more robust, let’s add an additional condition for Wednesday, when you work from home, with the use of else if keyword.

We’ll need to remove Wednesday from our first if condition and then add it to a newly created else if condition.

var currentDate = new Date();
var dayOfWeek = currentDate.getDay();

if (dayOfWeek === 0 || 1 || 2 || 4 || 5 || 6 ) {
  alert("It's a weekday, make sure you are awake by 7 a.m.");
}
else if (dayOfWeek === 3) {
alert("You work from home today, you can wake up a bit later at 8 a.m.");
}
else {
alert("Relax, you can sleep in, it's the weekend!");
}

And voila, you now have a working alarm clock in your JavaScript console that knows the difference between weekdays, weekends, and when you work from home.

Pretty neat right?

Hopefully, now you understand why conditional statements give intelligence to your programs. And how this adds a powerful layer of sophistication to your JavaScript program.

Next up, let’s take a look at JavaScript objects, the most powerful concept in JavaScript programming.

Categories
HTML JavaScript Marketing

Collecting all the email addresses or links on a webpage with JavaScript

Have you ever wanted, or needed, to collect all of the email addresses or links on a website?

Have you ever tried to do this manually?

I have. It’s incredibly tedious.

There’s nothing quite as dehumanizing as robotically copying and pasting hundreds of email addresses or links from a webpage to an excel sheet over and over again.

So let’s make sure you never have to do that again.

In this guide, I’ll show you how to use JavaScript to collect all of the email addresses or links on a webpage.

It’s actually pretty easy. So let’s get started.

Thinking before writing your code

Before we begin writing our program, it’s always useful to think about what we’re trying to accomplish; this helps us write a more coherent program.

Here’s what we know we’ll need to do for this program:

  1. Search through the content of the webpage for emails/links.
  2. Collect the email/links.

Seems pretty straightforward, right? It is!

Now let’s break down each of the steps above into actual statements that we’ll need to write to complete the task of collecting emails from a website.

Here’s what we need to do:

  1. Create an empty array to populate with email/links.
  2. Specify where in the DOM we want JavaScript to search.
  3. Convert the content of the DOM to a string.
  4. Use the .match method to specify what we’re searching for.
  5. Add the matched items to our array.

Also pretty straightforward, so let’s start writing some code.

I created a test page for you to practice with. Please open this page in a new window beside this one, activate your developer console, and follow the instructions below.

Collecting all the email addresses on a webpage

Once you’ve opened up this page and started your JavaScript developer console, you’ll need to create an empty array to store the email addresses.

Please type this into your JavaScript developer console:

var listOfEmails = [];

Great, now let’s determine where we want JavaScript to look for these email addresses.

In the test page, I created for you, the email addresses are within the opening <body> and closing </body> HTML tags of the page.

Let’s write a variable and assign the content within these tags to it:

var contentToSearch = document.body.innerHTML;

Now let’s verify the content assigned to our variable is correct by typing the following in our JavaScript developer console:

contentToSearch;

Did you see the HTML content of the page appear in your developer console? Excellent.

Now we need to convert the content from HTML to text so we can search it. To do this we’ll use the .toString method and apply it to our contentToSearch variable, which will convert all the HTML to text:

var contentAsText = contentToSearch.toString();

All of the content within the opening <body> and closing </body> HTML tags have just been converted to text and assigned to the variable contentAsText.

Let’s now search through it for the email addresses.

To do this we’ll use the .match method on the variable contentAsText in conjunction with a regular expression that matches some standard email address patterns:

listOfEmails = contentAsText.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

Now, to access the list of emails you just need one final step, type the following in your browser console:

listOfEmails

You should see your list of emails! Well done!

Here’s the entire program we just wrote.

Final program for collecting all the email addresses on a webpage

var listOfEmails = [];
var contentToSearch = document.body.innerHTML;
var contentAsText = contentToSearch.toString();
listOfEmails = contentAsText.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
console.log(listOfEmails);

Please don’t forget to run this code in your web browser’s developer console.

Collecting all the links on a webpage

This will be pretty similar to the program we wrote for collecting all the email addresses.

Please open this page in a new window beside this one, activate your developer console, and start by creating an array to store our links:

var listOfLinks = [];

Now let’s collect all the links on the page.

Lucky for us, there’s a default JavaScript method called .links which can collect all the links on a page for us, without the need for writing a custom function.

Let’s write a variable to use the .links method:

var collectLinks = document.links;

Now we’ll need to loop through the links one by one and add them to our array.

Let’s do this with a JavaScript loop which utilizes the .push method:

for(var i=0; i<collectLinks.length; i++) {
  listOfLinks.push(collectLinks[i].href);
}

Did you see the number 12 in your developer console?

If you did, congratulations, you’ve just collected all of the links on the page.

Now let’s take a look at the content of our array by typing the following:

listOfLinks;

Notice it collected all the email addresses and links?

That’s perfectly normal since both email addresses and links use the HTML tag a href.

Well done!

Here’s the entire program we just wrote.

Final program for collecting all the links on a webpage

var listOfLinks = [];
var collectLinks = document.links;
for(var i=0; i<collectLinks.length; i++) {
  listOfLinks.push(collectLinks[i].href);
}
console.log(listOfLinks);

Please don’t forget to run this code in your web browser’s developer console.

Why this works

You might be wondering how this is possible, considering you don’t have the ability to edit the JavaScript files on a website you are visiting.

Well, you don’t actually need to edit a website’s JavaScript files directly as you can run the JavaScript program in your web browser’s developer console. This is actually one of JavaScript’s best features!

So, with only our web browser and a little bit of JavaScript know how we were able to collect all the email addresses and links on a webpage.

Pretty handy right?

Next, let’s learn how to add some intelligence to our programs with conditional statements which let our programs make decisions on their own.