Reader small image

You're reading from  JavaScript from Beginner to Professional

Product typeBook
Published inDec 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781800562523
Edition1st Edition
Languages
Tools
Right arrow
Authors (3):
Laurence Lars Svekis
Laurence Lars Svekis
author image
Laurence Lars Svekis

Laurence Svekis is an experienced web application developer. He has worked on multiple enterprise-level applications, hundreds of websites, business solutions, and many unique and innovative web applications. He has expertise in HTML, CSS, JavaScript, jQuery, Bootstrap, PHP, and MySQL and is also passionate about web technologies, web application development, programming, and online marketing with a strong focus on social media and SEO. He is always willing to help his students experience what technology has to offer and looks forward to sharing his knowledge and experiences with the world.
Read more about Laurence Lars Svekis

Maaike van Putten
Maaike van Putten
author image
Maaike van Putten

Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.
Read more about Maaike van Putten

Codestars By Rob Percival
Codestars By Rob Percival
author image
Codestars By Rob Percival

Rob Percival is a highly regarded web developer and Udemy instructor with over 1.7 million students. Over 500,000 of them have taken Rob's Complete Web Developer Course 2.0, as well as his Android Developer and iOS Developer courses.
Read more about Codestars By Rob Percival

View More author details
Right arrow

Intermediate JavaScript

The concepts and solution approaches presented up to this point in the book are not the only way to think about solving issues. In this chapter, we will challenge you to look a little deeper, be curious, and practice the good habit of optimizing solutions.

In previous chapters, you were promised great things about this chapter because the optimal use of some built-in methods require knowledge of regular expressions, which we will cover in this chapter. There is a lot more fun to be had though—here is a list of topics that we'll cover:

  • Regular expressions
  • Functions and the arguments object
  • JavaScript hoisting
  • Strict mode
  • Debugging
  • Using cookies
  • Local storage
  • JSON

As you can see, a selection of diverse topics, but all advanced and fun. The sections in this chapter are not as related to each other as you might have gotten used to by now. They are mostly individual topics that can help...

Regular expressions

Regular expressions, also known as regex, are simply ways to describe text patterns. You can consider them next-level strings. There are different regex implementations. This means that depending on the interpreter, regex might differ a bit in the way they're written. However, they are somewhat standardized, so you write them (almost) the same for all versions of regex. We are going to use regex for JavaScript.

Regex can be very useful in many situations, for example when you need to look for errors in a large file or retrieve the browser agent a user is using. They can also be used for form validation, as with regex you can specify valid patterns for field entries such as email addresses or phone numbers.

Regex is not only useful for finding strings, but can also be used for replacing strings. By now you might think, so regex is amazing, but is there a catch? And yes, unfortunately, there is a catch. At first, regex might kind of look like your neighbor...

Functions and the arguments object

JavaScript deals with arguments in functions by adding them to a custom object called arguments. This object works a lot like an array, and we can use it instead of using the name of the parameter. Consider the following code:

function test(a, b, c) {
  console.log("first:", a, arguments[0]);
  console.log("second:", b, arguments[1]);
  console.log("third:", c, arguments[2]);
}
test("fun", "js", "secrets");

This outputs:

first: fun fun
second: js js
third: secrets secrets

When you update one of the parameters, the argument gets changed accordingly. The same goes for the other way around;

function test(a, b, c) {
  a = "nice";
  arguments[1] = "JavaScript";
  console.log("first:", a, arguments[0]);
  console.log("second:", b, arguments[1]);
  console.log("third:", c, arguments[2]);
}
test("fun", "js"...

JavaScript hoisting

In Chapter 6, Functions, we discussed that we have three different variables, const, let, and var, and we highly recommended that you should use let instead of var because of their different scopes. JavaScript hoisting is why. Hoisting is the principle of moving declarations of variables to the top of the scope in which they are defined. This allows you to do things that you cannot do in many other languages, and for good reason by the way. This should look normal:

var x;
x = 5;
console.log(x);

It just logs 5. But thanks to hoisting, so does this:

x = 5;
console.log(x);
var x;

If you try to do this with let, you'll get a ReferenceError. This is why it is better to use let. Because clearly, this behavior is very hard to read, unpredictable, and you don't really need it.

The reason this happens is that the JavaScript interpreter moves all the var declarations to the top of the file before processing the file. Only the declarations...

Using strict mode

We can change the understanding and forgiving behavior of JavaScript to some extent using strict mode. You can switch on strict mode with the following command in your code. This needs to be the first command of your code:

"use strict";

Here is something that works when we don't use strict mode:

function sayHi() {
  greeting = "Hello!";
  console.log(greeting);
}
sayHi();

We forgot to declare greeting, so JavaScript did it for us by adding a greeting variable to the top level and it will log Hello!. If we enable strict mode, however, this will give an error:

"use strict";
function sayHi() {
  greeting = "Hello!";
  console.log(greeting);
}
sayHi();

The error:

ReferenceError: greeting is not defined

You can also use strict mode only in a particular function: simply add it to the top of the function and it gets enabled for that function only. Strict mode alters a few other things...

Debugging

Debugging is a delicate art. In the beginning, it usually is very hard to spot what's wrong with your code. If you are using JavaScript in the browser and it is not behaving as you would expect, step 1 is always to open the console in the browser. Often it will contain errors that can help you further.

If that doesn't solve it, you can log to the console in every step of your code, and also log the variables. This will give you some insight as to what is going on. It might just be that you are relying on a certain variable that happens to be undefined. Or perhaps you are expecting a certain value from a mathematical computation, but you've made an error and the result is something completely different from what you thought. Using console.log() during development to see what's happening is rather common.

Breakpoints

A more professional way to go about debugging is to use breakpoints. This can be done from most browsers and IDEs. You click on...

Using cookies

Cookies are small data files that are stored on your own computer and used by websites. Cookies were invented to store things about the user of the website. Cookies are strings with a special pattern. They contain key-value pairs, and these key-value pairs are separated by semi-colons.

You can create a cookie and use it again later. Here is how you can create a cookie:

document.cookie = "name=Maaike;favoriteColor=black";

This does not work in all browsers when you run it on the client side (such as in your <script> tag). In Chrome, for example, you cannot set the cookies from the client side. You have to run the code from a server. (I have used Safari instead to do this here, but there are no guarantees about future support.) An alternative is the web storage API.

It is also possible to start Chrome from the command line with certain settings enabled, or to enable the cookies in the settings under privacy preferences. Careful to turn...

Local storage

We have looked at cookies as a way to save user data, but there is actually a more modern way to do this: local storage. Local storage is an amazing fun topic that will add to your ability to make smart websites. With local storage, we can save key-value pairs in our web browser and use them again in a new session (when the browser is opened again later). The information is typically stored in a folder on the computer of the user, but this differs a bit by browser.

This allows the website to store some information and retrieve it later, even after refreshing the page or closing the browser. The advantage of local storage over cookies is that they don't need to be passed around with every HTTP request, which is the case with cookies. Local storage just lives there and waits to be accessed.

The localStorage object is a property of the window object that we have seen before. There are a few methods on the localStorage object that we need to know to use it effectively...

JSON

JSON stands for JavaScript Object Notation, which is nothing more than a data format. We saw this notation when we were creating our objects in JavaScript; however, JSON doesn't mean JavaScript objects, it's just a way of representing data using a similar format as JavaScript objects. It can also be easily converted to a JavaScript object.

JSON is a standard used to communicate with APIs, including APIs that aren't written in JavaScript! APIs can accept data, for example, the data from a form on a website, in JSON format. And nowadays, APIs almost always send data back in JSON. Sending data from an API happens, for example, when you enter a web shop—the products typically come from a call to an API that is connected to a database. This data gets converted to JSON and is sent back to the website. Here is an example of JSON:

{
  "name" : "Malika",
  "age" : 50,
  "profession" : "programmer",
  "...

Chapter projects

Email extractor

Use the following HTML as a starter template and add the JavaScript code to make an email extractor function:

<!doctype html>
<html>
<head>
    <title>Complete JavaScript Course</title>
</head>
<body>
    <textarea name="txtarea" rows=2 cols=50></textarea> <button>Get Emails</button>
    <textarea name="txtarea2" rows=2 cols=50></textarea>
    <script>
    </script>
</body>
</html>

Take the following steps:

  1. In JavaScript, select both text areas and the button and set them as JavaScript objects.
  2. Add an event listener to the button that will invoke a function that gets the content of the first textarea and filters it to only accept email addresses.
  3. Within the extracting function, get the content of the first input field. Using match(), return an array of the email addresses that were matched from...

Self-check quiz

  1. What will the following regex expression return from the following words?
    Expression / ([a-e])\w+/g
    "Hope you enjoy JavaScript"
    
  2. Are cookies part of the document object?
  3. What will the following code do to a JavaScript cookie?
    const mydate = new Date();
    mydate.setTime(mydate.getTime() - 1);
    document.cookie = "username=; expires=" + mydate.toGMTString(); 
    
  4. What is the output in the console from the following code?
    const a = "hello world";
    (function () {
        const a = "JavaScript";
    })();
    console.log(a);
    
  5. What is the output in the console from the following code?
    <script>
    "use strict";
    myFun();
    console.log(a);
    function myFun() {
        a = "Hello World";
    }
    </script>
    
  6. What is the output of the following code?
    console.log("a");
    setTimeout(() => {
        console.log("b");
    }, 0);
    console...

Summary

In this chapter, we had some important, more advanced topics that we still had to cover, but that you were probably not ready for earlier in the book. After this chapter, you should have deepened your understanding of JavaScript in several areas, first and foremost, regular expressions. With regex, we can specify patterns of strings and we can use these to search other strings for matches to our patterns.

We also considered functions and the arguments object, with which we can access arguments by their index. We continued with a look at JavaScript hoisting and strict mode, which enables us to use JavaScript with a few more rules. Getting used to JavaScript in strict mode is generally a good practice and is great preparation for working with JavaScript frameworks.

Debugging and tweaking were also discussed: we can use breakpoints or log our output to the console to get an idea of what is going on. Handling errors well can prevent unnecessary crashes of our program....

lock icon
The rest of the chapter is locked
You have been reading a chapter from
JavaScript from Beginner to Professional
Published in: Dec 2021Publisher: PacktISBN-13: 9781800562523
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Laurence Lars Svekis

Laurence Svekis is an experienced web application developer. He has worked on multiple enterprise-level applications, hundreds of websites, business solutions, and many unique and innovative web applications. He has expertise in HTML, CSS, JavaScript, jQuery, Bootstrap, PHP, and MySQL and is also passionate about web technologies, web application development, programming, and online marketing with a strong focus on social media and SEO. He is always willing to help his students experience what technology has to offer and looks forward to sharing his knowledge and experiences with the world.
Read more about Laurence Lars Svekis

author image
Maaike van Putten

Maaike is a software consultant and trainer with a passion for sharing her expertise to empower others in their careers. Her love for software development shows in the numerous software development projects she participated in and the many certifications she obtained. She has designed and delivered a broad spectrum of training courses catering to beginners and seasoned developers in Java, Python, C# and many other languages and frameworks. Next to that, she has authored multiple books and online courses through multiple platforms reaching over 500,000 learners across the globe.
Read more about Maaike van Putten

author image
Codestars By Rob Percival

Rob Percival is a highly regarded web developer and Udemy instructor with over 1.7 million students. Over 500,000 of them have taken Rob's Complete Web Developer Course 2.0, as well as his Android Developer and iOS Developer courses.
Read more about Codestars By Rob Percival