Tuesday, January 31, 2023

Generate Random Numbers and Strings in JavaScript

Generate Random Numbers and Strings in JavaScript

The ability to generate random numbers or alphanumeric strings can come in handy in many situations. You could use it to spawn enemies or food at different locations in a game. You could also use this to suggest random passwords to users or create filenames to save files.

I have also written a tutorial on this topic in the past where we generate random alphanumeric strings in PHP. I began that post by saying that almost no event is truly random and the same thing applies to random number or string generation.

In this tutorial, I will show you how to generate pseudo-random alphanumeric strings in JavaScript.

Generating Random Numbers in JavaScript

Let's begin with generation of random numbers. The first method that comes to mind is Math.random() which gives back a floating-point pseudo-random number. The random number will always be greater than or equal to 0 and less than 1.

The distribution of the numbers returned in that range is almost uniform so the method can work well for generating random numbers without noticeable bias in everyday usage. Here is the output of ten calls to the Math.random() method:

1
for(let i = 0; i < 10; i++) {
2
  console.log(Math.random());
3
}
4
5
/* Outputs:

6
0.9981169188071801

7
0.7073616929117277

8
0.05826679080842556

9
0.30779242012809105

10
0.37282814053539926

11
0.8991639574910759

12
0.5851162879630685

13
0.40572834956467063

14
0.5286480734412005

15
0.07898699710613699

16
*/

Generating Random Integers within Range

As you saw in the previous section, Math.random() will give us random numbers in the range 0 (inclusive) to 1 (exclusive). Let's say we want random integers in the range 0 (inclusive) to 100 (exclusive). All we need to do here is multiply the original range by 100.

Taking the first output value from the above code snippet as example, 0.9981169188071801 will become 99.81169188071801 when multiplied by 100. Now, we can use the Math.floor() method which will round down and return the largest integer less than or equal to 99.81169188071801. In other words, it will give us 99.

The following code snippet will iterate through a loop 10 times to show all these steps applied to different numbers.

1
const max_limit = 100;
2
3
for(let i = 0; i < 10; i++) {
4
  let random_float = Math.random();
5
  let scaled_float = random_float * max_limit;
6
  let random_integer = Math.floor(scaled_float);
7
  
8
  let rf_str = random_float.toString().padEnd(20, ' ');
9
  let sf_str = scaled_float.toString().padEnd(20, ' ');
10
  let ri_str = random_integer.toString().padStart(2, ' ');
11
  
12
  console.log(`Random Float: ${rf_str} Scaled Float: ${sf_str} Random Integer: ${ri_str}`);
13
}
14
15
/* Outputs:

16
Random Float: 0.7976037763162469   Scaled Float: 79.76037763162469    Random Integer: 79

17
Random Float: 0.3794078358214559   Scaled Float: 37.94078358214558    Random Integer: 37

18
Random Float: 0.5749118617425708   Scaled Float: 57.49118617425708    Random Integer: 57

19
Random Float: 0.7110572178100005   Scaled Float: 71.10572178100006    Random Integer: 71

20
Random Float: 0.9157559644743132   Scaled Float: 91.57559644743132    Random Integer: 91

21
Random Float: 0.8773095295734263   Scaled Float: 87.73095295734264    Random Integer: 87

22
Random Float: 0.7714603913623834   Scaled Float: 77.14603913623834    Random Integer: 77

23
Random Float: 0.6431998616346499   Scaled Float: 64.31998616346499    Random Integer: 64

24
Random Float: 0.7909155691442253   Scaled Float: 79.09155691442254    Random Integer: 79

25
Random Float: 0.1219575935563590   Scaled Float: 12.19575935563590    Random Integer: 12

26
*/

Now that you understand the logic behind the multiplication and flooring, we can write a function that generates a random integer within the maximum limit.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(max_random_number(100));
7
}
8
9
/* Outputs:

10
35

11
23

12
92

13
94

14
42

15
9

16
12

17
56

18
40

19
21

20
*/

What if you want to generate random numbers that are above a specified minimum value but below the maximum value?

In this case, you can add the minimum value beforehand to make sure that the generated number is at least equal to the minimum value. After that, you can simply generate a random number and then scale it by max - min before adding it to the minimum possible value.

1
function min_max_random_number(min, max) {
2
  return min + Math.floor(Math.random() * (max - min));
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(min_max_random_number(50, 100));
7
}
8
9
/* Outputs:

10
96

11
81

12
95

13
56

14
73

15
72

16
71

17
90

18
51

19
53

20
*/

Generate Cryptographically Secure Random Numbers

The Math.random() method is not suitable for generating cryptographically secure random numbers but the Crypto.getRandomValues() method can help us here. This method fills the passed array with cryptographically secure pseudo-random numbers. Keep in mind that the algorithm used to generate these random numbers may vary across user agents.

As I mentioned earlier, you need to pass an integer-based TypedArray to the method for it to fill it up with random values. The original contents of the array will be replaced. The following code will fill up our 10 element array with random integers.

1
let random_values = new Uint8Array(10);
2
console.log(random_values);
3
// Outputs: Uint8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

4
5
crypto.getRandomValues(random_values);
6
console.log(random_values);
7
// Outputs: Uint8Array(10) [ 207, 209, 1, 145, 70, 111, 21, 141, 54, 200 ]

The Unit8Array() constructor gave us an array of 10 8-bit unsigned integers. The array values are all initialized to zero.

Once we pass this array to our getRandomValues() method, the value of random numbers will stay between 0 and 255. You can use other typed arrays to generate random numbers in different ranges. For example, using an Int8Array() constructor will give us an array with integer values between -128 and 127. Similarly, using a Uint16Array() will give us an array with integer values up to 65,535.

1
let random_values = new Int8Array(10);
2
console.log(random_values);
3
// Outputs: Int8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

4
5
crypto.getRandomValues(random_values);
6
console.log(random_values);
7
// Outputs: Int8Array(10) [ -82, -106, 87, 64, 42, -36, -53, 27, -38, 4 ]

8
9
10
let random_values = new Uint16Array(10);
11
console.log(random_values);
12
// Outputs: Uint16Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

13
14
crypto.getRandomValues(random_values);
15
console.log(random_values);
16
// Outputs: Uint16Array(10) [ 47615, 60195, 53177, 15169, 215, 4928, 12200, 6307, 30320, 20271 ]

Generate a Random Alphanumeric String in JavaScript

We will now use the knowledge gained in the previous section to generate random alphanumeric strings in JavaScript.

The concept is pretty simple. We will begin with a string that contains all our desired characters. In this case, the string will consist of lowercase alphabets, uppercase alphabets and numbers 0 to 9. You probably already know that we can access the character at a particular position in a string by passing it an index value.

All we need to do to generate random alphanumeric strings is generate random numbers and then access the character at that random index to append it to our random string. The following code snippet wraps it all up in a nice little function:

1
const char_set = 'abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2
3
function max_random_number(max) {
4
  return Math.floor(Math.random() * max);
5
}
6
7
function get_random_string(length) {
8
  let random_string = '';
9
10
  for(let i = 0; i < length; i++) {
11
    random_string += char_set[max_random_number(char_set.length - 1)];
12
  }
13
  
14
  return random_string;
15
}
16
17
console.log(get_random_string(20));
18
// Outputs: lgtuRJZolu7AXj4HMoiM

19
20
console.log(get_random_string(40));
21
// outputs: scOoal3VXgeAjaHIieolhi2TyWFpAn5bBPPiX6UG

Using toString() to Generate Random Alphanumeric String

Another approach that we can take to generate random alphanumeric strings is to use the toString() method on our randomly generated numbers. The toString() method returns a string that represents our specified numerical value. This method accepts an optional radix parameter that specifies the base in which you want to represent the number. A value of 2 will return a binary string and a value of 16 will return a hexadecimal string. The default value of this parameter is 10. The maximum value can be 36 as it covers all the 26 alphabets and the 10 digits.

Here is the output of a few calls to this method for different radix values:

1
let number = 3498650143868;
2
3
console.log(number.toString(2));
4
// Outputs: 110010111010010111110011001000110001111100

5
6
console.log(number.toString(10));
7
// Outputs: 3498650143868

8
9
console.log(number.toString(16));
10
// Outputs: 32e97cc8c7c

11
12
console.log(number.toString(36));
13
// Outputs: 18n99yoak

You might have noticed that the length of output string keeps decreasing as we increase the radix. In the following code snippet, we will use our max_random_number() function from the previous section to get a random number. We will then convert this random number to an alphanumeric string by using the toString() method.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(max_random_number(Number.MAX_SAFE_INTEGER).toString(36));
7
}
8
/* Outputs:

9
1tr84s6c2sl

10
1yj4varyoj7

11
1zdg9nn0z6r

12
lubrjj1zih

13
13tt2n5vw9t

14
1mv6sctjgf

15
yx3fhnznhf

16
1wj4mdcrqb9

17
26sir75af2r

18
qdv9xv800t

19
*/

What if you want even larger alphanumeric strings and want them to have a fixed length like 40 characters or 100 characters? In that case, we can create a loop that keeps appending our generated strings until we reach the desired length.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
function get_random_string(length) {
6
  let random_string = '';
7
  while(random_string.length < length) {
8
   random_string += max_random_number(Number.MAX_SAFE_INTEGER).toString(36);
9
  }
10
  return random_string.substring(0, length);
11
}
12
13
console.log(get_random_string(40));
14
// Outputs: bn0nfhcsjm18ylzqrm6bo1iktka2aq7qbbl5ybki

15
16
console.log(get_random_string(100));
17
// Outputs: rdosjhthsevmk91mj9zvqexz2z0v3pe2beasbzoworanzjg3bfpf975rzfy2fmo6pmj4p69u0x80ce92jh2vljx90g6r0lzd8vb0

Final Thoughts

In this tutorial, we learned how to generate random numbers and alphanumeric strings in JavaScript. Generating random integers is easy in JavaScript with the help of Math.random() method. All we had to do was scale the output so that it matches our desired range. You can also consider using the getRandomValues() method if you want your random numbers to be cryptograhpically secure.

Once we know how to generate random numbers, creating random alphanumeric strings is easy. All we need to do is figure out how to convert our numbers to characters. We used two approaches here. The first one involved accessing the characters at a random numerical index in a predefined string. This technique is useful if you want to be specific about the characters that should be included in the random alphanumeric strings. The other approach involved to use of toString() method to convert our decimal numbers to a different base. This involves fewer calls to our max_random_number() function.

There are certainly many more techniques that you can use to generate random alphanumeric strings. It all depends on your needs and how creative you want to be with your approach.


Monday, January 30, 2023

Vue.js Tutorial: Beginner to Front-End Developer

Vue.js Tutorial: Beginner to Front-End Developer

This course will teach you the fundamental concepts you need to start building applications with Vue.js.

Who is This FREE Course For?

  • complete beginners who want to be web developers
  • experienced developers who want to explore advanced topics
  • any coder who enjoys learning something exciting

How Long is the Course?

This course is 4 hours 22 minutes long, and it’s split into 35 lessons in total. You’ll find it’s a great resource that you will come back to often.

In this course, you'll learn why Vue.js is a great choice for a front-end framework, and you'll discover how to use it in detail.

You'll start with building the simplest Vue components and learning to use core features like data binding, props, events, and computed properties.

Then you'll build that knowledge step by step with practical projects learning how to use the Vue CLI, forms, watchers, and custom events.

You'll also master key concepts like the Vue router and the Composition API. By the end of this course, you'll be confident in using Vue.js for all your front-end development projects.

What You'll Learn

  • fundamentals of Vue with no build tools or toolchains 
  • create applications, define and use options, organize applications into components 
  • learn the toolchains
  • how to load and work with reactive data 
  • how to handle user input and create custom events 
  • manipulate style, create computed properties
  • define objects that watch your data for changes 
  • how to create single page applications using the Vue router
  • how to use the Composing API 

Follow Along, Learn by Doing

I encourage you to follow along with this course, and you'll learn about all the most important features of Vue.js

To help, the Vue.js Tutorial: Beginner to Front-End Developer GitHub repository contains the source code for each lesson and the completed sample project that was built throughout the course. 

1. What You Will Learn 

Watch video lesson [0:00:00] ↗

Get an introduction to the course and an overview of what you'll be building.

2. Vue.js With no Tool-Chain

Getting Started with Vue

Watch video lesson [0:02:31] ↗

Vue.js is the most approachable UI framework, especially without using any tool-chains.

Here is the complete source code to a minimal, no-toolchain-required Vue.js hello world app.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
6
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
    <title>Vue Basics</title>
8
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
9
    <script src="https://unpkg.com/vue@3"></script>
10
</head>
11
<body>
12
    <div id="content" class="container">
13
        <h1></h1>
14
        <p></p>
15
    </div>
16
17
    <script>
18
        Vue.createApp({
19
            data() {
20
                return {
21
                    pageTitle: 'Hello, Vue',
22
                    content: 'Welcome to the wonderful world of Vue'
23
                };
24
            }
25
        }).mount('#content');
26
    </script>
27
</body>
28
</html>

Using Loops to Generate Content

Watch video lesson [0:10:51] ↗

Collections are some of the most common types of data you will work with within your application. In this lesson, you'll learn how to use the v-for directive to loop over collections to generate output.

Binding Data to Attributes

Watch video lesson [0:17:00] ↗

Data binding automatically keeps your components up to date with the underlying application data. See how it works in this lesson.

Here's an example of binding to data inside a loop.

1
            <ul>
2
                <li v-for="(link, index) in links">
3
                    <a 
4
                        :href="link.url"
5
                    ></a>
6
                </li>
7
            </ul>

Setting Up Events

Watch video lesson [0:25:11] ↗

Events are the lifeblood of any graphical application. You'll learn how to listen for DOM events in this lesson.

Binding CSS Classes I

Watch video lesson [0:33:15] ↗

Manipulating CSS is key to providing dynamic and enhanced user experiences. You'll learn how to bind CSS classes to state in this lesson.

Using Computed Properties

Watch video lesson [0:41:48] ↗

Sometimes you need to compute data on-the-fly in order to provide reactivity to your application. Computed properties give you that ability.

Binding CSS Classes II

Watch video lesson [0:48:05] ↗

There's more than one way to skin a cat... err bind CSS classes. You'll learn how to use arrays to do so in this lesson.

Introducing Components

Watch video lesson [0:55:00] ↗

Components help us organize our applications into smaller, maintainable pieces.

Understanding Data Flow

Watch video lesson [01:04:19] ↗

Components provide data to their children via props, and you'll need to understand how that data flows in order to build your applications.

Here's a snippet that shows how to create and register a new component with Vue.

1
app.component('page-viewer', {
2
    props: ['page'],
3
    template: `

4
        <div class="container">

5
            <h1></h1>

6
            <p></p>

7
        </div>

8
    `
9
});

3. Using the Vue CLI

Getting Started With the Vue CLI

Watch video lesson [1:13:00] ↗

The Vue CLI makes it easy to get up and running with a full-blown project. You'll install the CLI and create a project in this lesson.

Current recommendations are to use create-vue with the Vite tooling for new Vue projects. vue-cli is in maintenance mode, but still works for creating Webpack-powered Vue apps like in this course.

Starting a Project From Scratch

Watch video lesson [1:21:30] ↗

We'll delete most of that fresh new project we created in order to start completely from scratch. It's good to practice these things!

Applying CSS to Components

Watch video lesson [1:32:18] ↗

Our applications are broken into smaller components, and those components need CSS. You'll learn how to provide CSS to your application and components.

4. Working With Data

Using the created() Lifecycle Event to Load Data

Watch video lesson [1:41:51] ↗

The created() lifecycle event works a lot like the browser's load event. It's a great time to fetch data and supply it to your component before it's rendered in the browser.

Here's an example of using the created lifecycle event to load page data from a remote server.

1
export default {
2
    //...

3
4
    created() {
5
        this.getPages();
6
    },
7
    data() {
8
        return {
9
            pages: []
10
        };
11
    },
12
    methods: {
13
        async getPages() {
14
            let res = await fetch('pages.json');
15
            let data = await res.json();
16
            this.pages = data;
17
        }
18
    }
19
}

Working With Unset Props

Watch video lesson [1:48:19] ↗

Sometimes our components are ready and available before they have data to work with. You'll learn how to handle those situations in this lesson.

Deciding When to Load Data

Watch video lesson [1:55:19] ↗

Some components depend upon their parent for data; others are independent and load their own. There are no hard and fast rules, so I'll show you some strategies for loading data.

Working With Forms

Watch video lesson [2:01:14] ↗

The primary way we work with user input is via forms. Vue makes it laughably easy to work with forms and their data.

Validating Forms

Watch video lesson [2:08:43] ↗

Did I mention Vue makes it easy to work with forms? That's includes validation.

Updating and Filtering Data

Watch video lesson [2:14:39] ↗

Vue gives us the tools to get/provide data that our components need in order to function. That includes updating and filtering data.

Using Watchers

Watch video lesson [2:21:05] ↗

Watchers give us the ability to watch certain properties and react when their values change.

5. Creating and Using Custom Events

Creating Custom Events

Watch video lesson [2:25:19] ↗

Vue makes it easy to create custom events. You'll learn how in this lesson.

Writing a Global Event Bus

Watch video lesson [2:32:48] ↗

Unfortunately, custom events don't bubble, which makes it difficult for parent components to listen to events of children nested deep in the tree. Thankfully, we can create our own global event bus.

6. Using Vue Router

Introducing Vue Router

Watch video lesson [2:44:37] ↗

The Vue Router makes it possible to "navigate" between components... kinda like pages. You'll get the rundown in this lesson.

Here is a simple router with a couple static routes.

1
const router = createRouter({
2
    history: createWebHashHistory(),
3
    routes: [
4
        { path: '/', component: PageViewer },
5
        { path: '/create', component: CreatePage }
6
    ]
7
});

Using Route Params

Watch video lesson [2:53:19] ↗

Components that handle routes don't get their data via props because they don't really have a parent. Instead, they rely on data from the URL via route params. You'll learn how to use them in this lesson.

Loading Data for Views

Watch video lesson [2:59:18] ↗

Because views don't get data from their non-existant parent, data has to be loaded from somewhere. A centralized data store could be your solution, and we'll build one in this lesson.

Watching Params to Reload Data

Watch video lesson [3:10:07] ↗

If we try to "navigate" to a view that is already loaded by the router, we have to reload the data for the new route. You'll learn how in this lesson.

Using the Router's Active Class

Watch video lesson [3:16:57] ↗

The router keeps track of the currently active link. You'll learn how to use it in this lesson (and clean up a lot of code!).

Nesting Routes

Watch video lesson [3:23:36] ↗

Routes, like components, can be nested. You'll learn how and why you might want to do so in this lesson. 

Here's an updated router with params and nested routes.

1
const router = createRouter({
2
    history: createWebHashHistory(),
3
    routes: [
4
        { path: '/:index?', component: PageViewer, props: true },
5
        { 
6
            path: '/pages', 
7
            component: Pages,
8
            children: [
9
                { path: '', component: PagesList },
10
                { path: 'create', component: CreatePage }
11
            ]
12
        },
13
    ]
14
});
15

7. Using the Composition API

Introducing the Composition API

Watch video lesson [3:30:52] ↗

The Composition API was created to improve the organization of your component's code. I'll run over the basics in this lesson.

Providing and Injecting Dependencies Into Components

Watch video lesson [3:40:26] ↗

"Setup" components don't use this, and it complicates how we get to our global properties. Instead, we'll use Vue's provide and inject features to access our global objects.

Accessing Props and Router Functions

Watch video lesson [3:48:18] ↗

The Composition API changes how we access... everything, including props and the route/router. You'll learn how to access those in this lesson.

Binding Data and Working With Forms

Watch video lesson [3:54:58] ↗

In this lesson, you'll learn how to bind data to forms in setup components. It's easy.

Defining Computed and Watched Values

Watch video lesson [4:06:00] ↗

You can define computed and watched values in setup components. You'll learn how in this lesson.

Implementing the Delete Functionality

Watch video lesson [4:16:18] ↗

We'll finish off the management UI by providing delete functionality

Conclusion

Watch video lesson [4:20:42] ↗

Vue.js is my favorite UI framework. And don't get me wrong—React, Angular, and all of the other frameworks do their job just fine. But there's something different about Vue. It's very easy to get started, and it lacks a lot of the wonky rules that seem to plague other frameworks.

It's my hope that by now, you have a firm grasp of Vue's fundamentals, and I hope you continue to use it in your current and future projects.

Vue Plugins and Templates 

CodeCanyon, Envato Elements, and ThemeForest are fantastic sources for Vue plugins and templates. They can help you save time, cut down on development costs, and deliver projects on time.