Categories
Book Reviews

The Best Books for Learning JavaScript Programming

Eloquent JavaScript: A Modern Introduction to Programming

Eloquent JavaScript is a great book for introduction to JavaScript.

It’s a book that starts with the basics by introducing us to expressions and statements.

Then it goes into the data types and syntax of the language.

Next, it discusses the object-oriented parts of JavaScript.

Also, it outlines how to do DOM manipulation to make JavaScript programs that manipulate web pages dynamically.

It also has a brief introduction to the HTML canvas.

And it touches on how to make requests so that we can make apps that can communicate over the Internet.

Moreover, it touches on async programming so that we can write speedy apps that can do a lot.

It does a great job explaining all of those topics with easy to understand examples and many practice exercises to do of the work on to master JavaScript.

JavaScript: The Good Parts

This book highlights the good parts of JavaScript.

It goes through the best syntax of JavaScript. Then it discusses the best object-oriented features of JavaScript.

Also, it outlines the best features of JavaScript functions, arrays, and regular expressions.

It also provides plenty of guidance on how to write good JavaScript code.

It’s concise and easy to understand, and it’s a good book to learn how to write good code with JavaScript.

JavaScript: Best Practice

JavaScript: Best Practice is a good that explains how to use the best syntax of JavaScript.

It includes the most up to date features of JavaScript, like destructuring, spread and rest, async and await, and more.

Also, it shows us good design patterns that we should adopt in to build JavaScript programs in an maintainable manner.

It has a section on how to improve performance in our JavaScript apps, which not every book covers.

Essential TypeScript: From Beginner to Pro

Essential TypeScript: From Beginner to Pro by Adam Freeman starts from the basics of JavaScript and TypeScript and how to use various features with them.

It starts with basic syntax of JavaScript and the JavaScript features that TypeScript enhances.

Then it goes through how to set up a TypeScript project from scratch with the TypeScript compiler.

Also, it has a dedicated section on how to tesrt and debug TypeScript projects.

Then it goes into how to define and use basic data types with TypeScript.

It then show us how to use object-oriented features like classes, interfaces, generic types, object types, and more.

It also has several chapters to show us how to build apps with various frameworks with TypeScript.

Freeman shows us how to build apps with TypeScript and React, Angular or Vue.

The practical examples in those chapters are practical and will help you a lot with building high quality front end apps.

Clean Code: A Handbook of Agile Software Craftsmanship

Clean Code: A Handbook of Agile Software Craftsmanship is a book by Robert C. Martin, also known as Uncle Bob that outlines the principles of agile software development and how to write clean code.

Clean code is source code that people understand and change easily.

He goes through the basics like naming, functions, classes, SOLID, and more to show us how to write code well.

In addition, he goes over how to make code neat and easy to read.

The proper use of comments are also emphasized. He suggests that good code is better than comments.

Then he goes over the proper ways to handle errors and good designs for object-oriented programs.

Also, he places great emphasis on automated testing to reduce the burden of manual testing and make software changes easier.

The books go over the principles in Java but they apply to many other programming languages.

It’s a book that outlines all the good practices that we need to know to write high-quality programs.

The Pragmatic Programmer: 20th Anniversary Edition, 2nd Edition: Your Journey to Mastery

This is another book that shows us how to write code that’s easy for us to read and maintain.

Like Clean Code, it starts from the basics and also discuss more advanced concepts.

It’s aimed at both entry level and experienced programmers.

This book has emphasis of making modular code, reducing duplication not only in code but also in everything else involved in building software.

Also, it goes over ways to test ideas and make them reality faster.

Refactoring and testing are also discussed in great details.

This the follow up to the original edition that is more than 20 years old.

They are both classics and both editions still have useful concepts that we can apply today.

The Clean Coder: A Code of Conduct for Professional Programmers

This is another book by Robert C. Martin, which also written Clean Code.

It’s a book that shows us how to be a professional programmer.

It’s the definitive guide that explains how to be a good programmer from a nontechnical perspective.

This book focuses on making commitments, taking responsibility, improving speed.

Furthermore, it talks about testing, time management, estimation, dealing with pressure, and collaboration.

These are all the things that we have to deal with and Robert shares his wisdom with us so that we don’t have to go through the difficulties he went through.

It’s a good book that will make our lives easier if we’re programming software for a living.

Refactoring: Improving the Design of Existing Code

This is another time-tested book that shows us how to create high-quality software.

The angle is different from the others in that this one shows us how to make incremental changes to our code to improve its quality.

First it emphasizes the importance of tests, which are needed before refactoring.

Then it goes over common refactoring techniques with examples in Java.

However, it applies to many other programming languages, since they’re general things that many object-oriented languages can do.

Refactoring including functions, classes, big and small changes, abstraction and more are discussed in this book.

JavaScript is one of the most popular programming languages in the world.

Therefore, if you want to be a software developer, mastering JavaScript will definitely help a lot.

Here are 3 books that are great for learning JavaScript.

JavaScript Patterns: Build Better Applications with Coding and Design Patterns

This book provides us with basic program design principles to let us organize our JavaScript code for maintainability and readability.

Common patterns are covered and they apply to many other programming languages as well.

It comes with many examples to help us learn program design in an easy to understand way.

If you want to improve your JavaScript programming skills, this is a must read book.

JavaScript for impatient programmers

This is a great book for learning the basics of JavaScript. It covers all versions of JavaScript to date from version 1 to the 2019 edition.

Therefore, it covers the latest features.

The concepts are explained simply in an easy to understand way.

Also, the examples are also very simple. Many books have examples that are hard to follow, but this book have examples that are written clearly and concisely.

If you want to learn JavaScript fast, this book is for you.

If you want to get up to date on the latest features of JavaScript, this is also a book for you.

DOM Enlightenment: Exploring JavaScript and the Modern DOM

If you want to be a front end developer, then you must read this book.

It goes the basics of DOM manipulation, which is must-learn knowledge for front end development.

We can learn how to manipulate web pages dynamically with JavaScript with this book.

This book is very concise and it’s organized better than other resources like the Mozilla Developer Network website.

The examples are also concise so that we can follow and understand them easily.

It goes from the basics to the nitty-gritty details.

Therefore, this is a great book for getting the basics of creating dynamic web pages and web apps.

Fundamental Concepts for Web Development: HTML5, CSS3, JavaScript and much more!

This is a good book to introduce us to basic concepts in HTML, CSS, and JavaScript.

It’s very simple and concise. The examples are easy to understand.

This book allows us to understand the most basic building blocks of web development in a flash.

Also, it gives us lots of tips and tricks so that we won’t fall into traps that most beginners fall into.

It also provides us with lots of exercises so that we can master web development quickly.

HTML & CSS, and JavaScript & JQuery

This is another good book on the basics of web development.

It also has chapters on jQuery as a bonus. This is great since jQuery allows us to do more than just JavaScript alone.

Many web apps still use jQuery so we might as well learn it.

This book provides us with all the explanation and examples we need to learn the basics of web development.

It uses a visual approach, which means lots of diagrams, infographics, and photographs to help us learn the ropes.

You Don’t Know JS Series

This is a series of books that we can use to learn the basic and advanced concepts in JavaScript.

If we learn JavaScript thoroughly, we’ll be much better developers as we write better code and work faster.

This book explains the concepts, and also emphasizes how we can avoid the pitfalls of JavaScript.

It has sections about scopes, which is important for writing bug-free code.

Functions are also a topic that this book covers a lot.

Another thing that this book covers are synchronous and asynchronous tasks, which are used everywhere in JavaScript.

Object-oriented programming is also discussed in great detail.

These books are very affordable and will pay for itself many times over if you become proficient developers.

The Principles of Object-Oriented JavaScript by Nicholas C. Zakas

This is a short book that’s focused on the ins and outs of the object oriented parts of JavaScript.

It focuses on data types, objects, constructors, and classes.

These are all the things that can trick even the most experienced developers.

This book makes learning these parts of JavaScript easy by giving us focus and explaining the concepts concisely and with simple examples.

JavaScript for Kids: A Playful Introduction to Programming

Programming is useful for anyone. We can get a job with prorgramming skills or we can use the skill to program our own computers.

JavaScript for Kids: A Playful Introduction to Programming provides us with a gentle introduction to programming that kids can understand.

Explanation of the concepts are easy to understand and simple.

The examples that are included are easy to follow and fun to try.

It’s a good book to learn JavaScript even for adults.

Testing Vue.js Applications

This book covers everything we need to know about testing Vue apps, from creating the first test to testing Vuex and server side rendering.

It’s a very comprehensive book that goes through testing everything that we can think of in a Vue app.

This book provides us with many examples and provides clear explanations of everything that it covers.

Vue.js in Action

This book provides us with a gentle introduction of Vue.

It introduces us from the most basic concepts to concepts that let us build a whole app.

This book goes from introducing us to the most basic part of a Vue app to animations to Vuex and Vue Router.

It’s pretty much the guide that will let us master Vue in no time.

Practical examples are sprinkled throughout the book to help us understand the concepts outlined.

Fullstack Vue: The Complete Guide to Vue.js

Fullstack Vue: The Complete Guide to Vue.js is a book that introduces us to Vue.

In addition, it goes through examples that integrates with other apps like a back end app to provide us with an introduction to integrate Vue apps with other modules to build a complete system.

The book has lots of runnable code to let us poke around with to help us learn.

It covers the latest features.

It covers everything from the basics, to communicating with server APIs, and testing.

Categories
JavaScript React

Add an Enhanced img Element with react-image – an Example

The React img is just like the HTML version. It’s static and loads images synchronously.

Also, there’s no easy way to add fallback images or handle broken images, and there’s no way to lazy load images.

The react-image package provides all that in one easy to use package.

In this article, we’ll look at how to use react-image with some examples.

To use it, we first install it by running:

npm install react-image --save

Then we can use it by writing the following code:

import React from "react";
import Img from "react-image";

export default function App() {
  return (
    <div className="App">
      <Img src="https://images.unsplash.com/photo-1490750967868-88aa4486c946?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" />
    </div>
  );
}

The most basic way to use it is just like a regular HTML img element.

We just add the component and pass in the URL of the image to the src prop.

To add a fallback image, we can pass in an array of images, where the ones other than the first one are fallback images.

For instance, we can write:

import React from "react";
import Img from "react-image";

export default function App() {
  return (
    <div className="App">
      <Img
        src={[
          "https://images.unsplash.com/photo-1490750967868-88aa4486c946?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80",
          "https://images.unsplash.com/photo-1494271823928-a80211877d80?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
        ]}
      />
    </div>
  );
}

The second URL in the array in the src prop value would be the URL for the fallback image.

It takes a decode prop to prevent flashing before the image is loaded.

We can set decode to false to prevent the flash when it’s loading:

import React from "react";
import Img from "react-image";

export default function App() {
  return (
    <div className="App">
      <Img
        src={[
          "https://images.unsplash.com/photo-1490750967868-88aa4486c946?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80",
          "https://images.unsplash.com/photo-1494271823928-a80211877d80?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
        ]}
        decode={false}
      />
    </div>
  );
}

If we load an image restricted with a CORS policy, we can set the crossorigin prop to 'anonymous'.

The loader prop takes a React component to show when an image is loading.

We can write:

import React from "react";
import Img from "react-image";

export default function App() {
  return (
    <div className="App">
      <Img
        src="https://images.unsplash.com/photo-1490750967868-88aa4486c946?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
        loader={<p>Loading</p>}
        decode={false}
      />
    </div>
  );
}

To add lazy loading, we can use the VisibilitySensor component that’s built into the react-visibility-sensor package.

We can write:

import React from "react";
import Img from "react-image";
import VisibilitySensor from "react-visibility-sensor";

export default function App() {
  return (
    <div className="App">
      <VisibilitySensor>
        <Img src="https://images.unsplash.com/photo-1490750967868-88aa4486c946?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" />
      </VisibilitySensor>
    </div>
  );
}

to load the image only when it’s visible on the screen.

The react-visibility-sensor package is separate from react-image, so we have to run:

npm i react-visibility-sensor

to install it.

It’s easy to use react-image to add an enhanced HTML img element. As we can see from the examples, it’s just a matter of passing in a few props to use the enhanced features.

Also, we can use the react-visibility-sensor component to add lazy loading.

Categories
Chart.js JavaScript React

Create a Line Chart with react-chartjs-2 – an Example

react-chartjs-2 is an easy to use library for creating all kinds of charts.

It’s based on Chart.js, which renders chart in an HTML canvas element.

We can use it to render charts in a canvas inside a React app.

To get started, we install Chart.js and react-chartjs-2 by running:

npm install --save react-chartjs-2 chart.js moment

We also installed moments to create dates for the x-axis labels.

Then we can write the following code:

import React from "react";
import { Line } from "react-chartjs-2";
import moment from "moment";

const startDate = new Date(2020, 0, 1);
const labels = [];
for (let i = 0; i < 6; i++) {
  const date = moment(startDate)
    .add(i, "days")
    .format("YYYY-MM-DD");
  labels.push(date.toString());
}

const data = canvas => {
  const ctx = canvas.getContext("2d");
  const gradient = ctx.createLinearGradient(0, 0, 100, 0);
  return {
    backgroundColor: gradient,
    labels,
    datasets: [
      {
        label: "# of Votes",
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 3,
        fill: false,
        borderColor: "green"
      }
    ]
  };
};

export default function App() {
  return (
    <div className="App">
      <Line data={data} />
    </div>
  );
}

We first create the x-axis labels and populate them in the labels array/

We did that by using the moment function and call add on it to add 1 day in each iteration of the for loop.

Then we create a data function, which takes the canvas object, which has the canvas element as the parameter.

Then we get the canvas from it and change the items that we want.

The function returns the options for our graph, including the data.

The object we return in data has various options.

It has the labels property to populate the x-axis labels.

backgroundColor has the color for our graph.

datasets has an array with an object with the data and some options for the line.

data has the y-axis values for each x-axis value.

borderWidth specifies the thickness of the line in pixels.

fill is set to false means that we don’t have any colors between the x-axis and our line.

label is the text label for our legend.

borderColor is the color of our line.

Once we have that code, we’ll see the following graph:

https://thewebdev.info/wp-content/uploads/2020/05/react-chartjs-2.png

Categories
JavaScript React

Using React-Datepicker with Bootstrap

We can use react-datepicker with Bootstrap easily.

We should either use Reactstrap or React Bootstrap to add Bootstrap to our app.

In this article, we’ll use React Bootstrap with react-datepicker.

First, we install both by running:

npm install react-bootstrap bootstrap react-datepicker

Bootstrap is required by React-Bootstrap. react-datepicker is also installed.

Then we can use both of them together by writing:

import React, { useState } from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";
import { Container, Row, Col } from "react-bootstrap";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <div className="App">
      <Container fluid>
        <Row>
          <Col>
            <DatePicker
              selected={startDate}
              onChange={date => setStartDate(date)}
            />
            <p>{startDate.toString()}</p>
          </Col>
        </Row>
      </Container>
    </div>
  );
}

We imported the Container, Row, and Col components from React Bootstrap.

These are components for a container to hold other elements. fluid makes it responsive.

Inside Col, we have DatePicker component from react-datepicker.

Also, we imported the CSS file that comes with react-datepicker so that the date picker is displayed with proper styles.

We have the selected prop that’s set to the startDate state.

onChange is set to a function that calls setStartDate to set the state.

Then we see an input box that shows a date picker when we click on it.

When we click a date, then the date that’s selected is displayed below the input box.

useState has new Date() as its argument, so its initial value will be the current date and time.

So when we first load the page, the current date will be selected on the date picker.

react-datepicker and Bootstrap can be used together. We just have to use React derives of Bootstrap like React Bootstrap or Reactstrap.

Categories
JavaScript Nodejs

How to Use NPM to Manage JavaScript Dependencies

NPM is the most popular package manager for Node.js. It is often used for installing and uninstalling packages. but can also be used for running custom scripts and performing other operations to packages.

The most common operations for developers are installation, clean up, removing duplicates, and running scripts.

npm install

npm install , or npm i for short, is used to install packages. If you don’t put a package name after install, it downloads all the packages listed in package.json if the dependencies aren’t installed yet or the version installed is outdated. If you put a package name after npm install, it will install the package with that name as long as it finds the package. During the installation process, npm will run npm run link and npm run build to compile the packages. You can install packages globally by running npm install -g packageName

npm audit

npm audit is used for running a security audit of the npm packages you installed. It will display the results of the audit in various formats. You can also fix any security vulnerabilities with npm audit fix. To do a dry run, you can do npm audit fix --dry-run .

Both the audit and fix can be displayed in JSON by including --json to the command, such as npm audit --json and npm audit fix --json.

Example output:

=== npm audit security report ===
# Run  npm update set-value --depth 12  to resolve 66 vulnerabilities
High            Prototype Pollution
Package         set-value
Dependency of   @angular-devkit/build-angular [dev]
Path            @angular-devkit/build-angular > sass > chokidar > anymatch >
                  micromatch > braces > snapdragon > base > cache-base >
                  set-value
More info       https://npmjs.com/advisories/1012
High            Prototype Pollution
Package         set-value
Dependency of   @angular-devkit/build-angular [dev]
Path            @angular-devkit/build-angular > webpack > watchpack >
                  chokidar > anymatch > micromatch > braces > snapdragon >
                  base > cache-base > set-value
More info       https://npmjs.com/advisories/1012
High            Prototype Pollution
Package         set-value
Dependency of   @angular-devkit/build-angular [dev]
Path            @angular-devkit/build-angular > webpack-dev-server >
                  chokidar > anymatch > micromatch > braces > snapdragon >
                  base > cache-base > set-value
More info       https://npmjs.com/advisories/1012
High            Prototype Pollution
Package         set-value
Dependency of   @angular/compiler-cli [dev]
Path            @angular/compiler-cli > chokidar > anymatch > micromatch >
                  braces > snapdragon > base > cache-base > set-value
More info       https://npmjs.com/advisories/1012
...

npm bin

npm bin prints the folder where packages are installed.

Example output:

c:\math-calculator>npm bin  
c:\math-calculator\node\_modules\.bin

npm ci

npm ci is used to install all packages from scratch from package-lock.json. If there are any discrepancies between package.json and package-lock.json, it will fail. node_modules will be deleted and everything will be installed from scratch.

You can tab completion to npm by including npm completion in your ~/.bashrc or ~/.zshrc.

npm-config

npm-config is used for saving configuration key-value pairs to npmrc . To set a key-value pair in npmrc, we put:

npm config set key value

To get a value from the key, we run:

npm config get key

We can list all values by running:

npm config list

We can delete the key-value pair by running:

npm config delete key

and we can edit the key-value pair by running:

npm config edit

You can append — global to the above commands to change global config.

npm dedupe

npm dedupe will remove duplicate dependencies from your node_modules folder by moving the dependencies up the dependency tree, allowing common dependencies for multiple packages to reference one dependency.

npm doctor

npm doctor runs checks to make sure your environment has everything to manage Git packages. It checks if Node.js and Git can be run. It also checks if the primary npm registry or an alternative is accessible. node_modules is checked if it can be accessed and is writable, and it checks if the npm cache exists and there are no corrupt packages:

Example output of npm doctor:

npm notice PING https://registry.npmjs.org/
npm WARN verifyCachedFiles Content garbage-collected: 1328 (139761056 bytes)
npm WARN verifyCachedFiles Missing content: 5
npm WARN verifyCachedFiles Cache issues have been fixed
Check                               Value                             Recommendation
npm ping                            OK
npm -v                              v6.9.0                            Use npm v6.10.3
node -v                             v10.16.0                          Use node v10.16.2
npm config get registry             https://registry.npmjs.org/
which git                           C:\Program Files\Git\cmd\git.EXE
Perms check on cached files         ok
Perms check on global node_modules  ok
Perms check on local node_modules   ok
Verify cache contents               verified 8899 tarballs

npm explore

npm explore is used when you need to browse for an installed package. Once you’re in the package directory, you can run commands there.

npm help

npm help-search and npm help commands are used to find help with npm commands.

npm init

npm init is used for adding package.json to a project if it doesn’t already exist. npm init -y is used for skipping all the questions asked before creating the file.

npm outdated

npm outdated is used for checking for outdated packages.

Example output:

Package                            Current   Wanted   Latest  Location
@angular-devkit/build-angular      0.800.3  0.800.6  0.802.1  math-calculator
@angular/animations                  8.0.2    8.2.1    8.2.1  math-calculator
@angular/cdk                         8.0.1    8.1.2    8.1.2  math-calculator
@angular/cli                         8.0.3    8.0.6    8.2.1  math-calculator
@angular/common                      8.0.2    8.0.3    8.2.1  math-calculator
@angular/compiler                    8.0.2    8.0.3    8.2.1  math-calculator
@angular/compiler-cli                8.0.2    8.0.3    8.2.1  math-calculator
@angular/core                        8.0.2    8.0.3    8.2.1  math-calculator
@angular/forms                       8.0.2    8.0.3    8.2.1  math-calculator
@angular/language-service            8.0.2    8.0.3    8.2.1  math-calculator
@angular/material                    8.0.1    8.1.2    8.1.2  math-calculator
@angular/platform-browser            8.0.2    8.0.3    8.2.1  math-calculator
@angular/platform-browser-dynamic    8.0.2    8.0.3    8.2.1  math-calculator
@angular/router                      8.0.2    8.0.3    8.2.1  math-calculator
@ngrx/store                          8.0.1    8.2.0    8.2.0  math-calculator
@types/jasmine                      3.3.13   3.3.16    3.4.0  math-calculator
@types/node                          8.9.5    8.9.5   12.7.1  math-calculator
karma                                4.1.0    4.1.0    4.2.0  math-calculator
karma-chrome-launcher                2.2.0    2.2.0    3.0.0  math-calculator
karma-coverage-istanbul-reporter     2.0.5    2.0.6    2.1.0  math-calculator
mathjs                               6.0.2    6.0.4    6.0.4  math-calculator
rxjs                                 6.4.0    6.4.0    6.5.2  math-calculator
ts-node                              7.0.1    7.0.1    8.3.0  math-calculator
tslint                              5.15.0   5.15.0   5.18.0  math-calculator
typescript                           3.4.5    3.4.5    3.5.3  math-calculator
zone.js                              0.9.1    0.9.1   0.10.1  math-calculator

npm ls

npm ls lists installed packages in the current project. npm list and npm la are aliases of this command.

npm prune

npm prune removes unused packages. npm run --production is used to delete packages from the devDependencies section. The --dry-run option is used for checking which packages will be deleted before the actual run. The --json option can be used to display results in JSON. With package-lock enabled, pruning is automatic.

npm root

npm root displays the root folder for Node packages in the project.

npm run

npm run-script lets you run custom scripts that you write. npm run is an alias of this command.

npm start

npm start starts a package by running the command you define.

npm search

npm search is used to search for packages by name.

npm shrinkwrap

npm shrinkwrap creates npm-shrinkwrap.json by repurposing package-lock.json or creating from scratch. npm-shrinkwrap.json takes precedence over package-lock.json .

npm stop

npm stop stops a package by running stop command that you define.

npm test

npm test allows you to run tests with a script that you define.

npm uninstall

npm uninstall is used for uninstalling packages. You can add -g at the end to remove global packages.

npm update

npm updateupdates packages in the project. npm update packageName updates only the package with the name packageName . It will record the latest version to package-lock.json .

To upgrade npm to the latest version, run npm install -g npm.