Refreshing Next Generation JavaScript

Once again, it is Saturday. We are experiencing the COVID-19 pandemic and it seems that days, weeks and months are flying by. My routine on workdays has not changed at all. I work five 2-hour blocks with most intermissions of about 15 minutes. The intermission for lunch is about an hour. Actual lunch takes about 20 minutes, but my wife and I sit down with a cup of espresso and chat for about 20 more minutes. When done we do the dishes and I go down to my home office.

Today my wife and I were going to go to Costco in Minneapolis. Last night I sent my son a message so we could meet there at 07:00 AM and chat while shopping. Last evening my wife had some stomach pain and a light fever. We decided to play it safe and stay home. If the fever persists until tomorrow, we will get an on-line medical consultation. Hopefully it is not COVID-19.

Two of our friends with which we tend to travel abroad have both been diagnosed with COVID-19. He has been in a hospital for a few days. She is at home with a mild fever and taking medications. Her daughter is helping her. Best wishes for favorable outcomes and a short hospital stay.

Earlier today I read a tweet from a friend. Apparently last night he watched 13th on Netflix. He wished for change and ends his tweet with the following:

“Please vote, root and call out these racist bigots away! Enough is enough!”

Not sure what he refers with vote or call out these people.

The riots and unrest started when Minneapolis police was called because a person was trying to pass a counterfeit $20 bill at a store. The black person in question had a long police record including violence and drugs. Apparently one thing lead to another and the person died while in police custody. I find it hard to believe that under such circumstances the suspect would end dead; but it happened.

The proper and established procedure is to put the officers in administrative leave and conduct an investigation. Police officers in Minneapolis should have a body camera and should be operational. If the results from the police investigation seem biased, the family, government and public at large have the right to file a law suit. If there is no satisfactory resolution the case could escalate up to the Supreme Court. If that is not acceptable, then peaceful protests all around the country should start and persist until justice and more important, flawed procedures are changed. All people in the chain up and including to the Supreme Court should be liable if found guilty of justice obstruction. Of course this is easily said than done.

Now that the proper process has been established and for some unknown reasons (i.e., presidential elections in a few months) the process was not followed at all, we need to start looking from the police officers involved up. It should be very simple to determine (with evidence not opinions) if reasonable force was used. I get a kick when people that has never been in the position of enforcement, know about what can and does happen in the field. I have never been a police officer, but in a previous life was a naval officer and had to enforce curfews. Things happen very quickly and people breaking the rules and laws tend to be armed, or under the influence of drugs or alcohol. In most cases things get resolved peacefully (that was my experience). On other cases, and I will not go into the specifics here, a naval officer, had to use deadly force because a car was used to run over a checkpoint. The perpetrator was shot and killed during the attempt.

Now let’s move on to the vote part. Police officers are not elected officials. They can be fired and thrown in jail. The city of Minneapolis has mostly (never say all) liberal city council members, the mayor of the city is liberal, the state prosecutor is liberal, the governor of Minnesota is liberal. All these positions have been held by liberals for decades. Nothing has changed and in my humble opinion, they will never change unless all of them are held accountable for what they do. It seems that being in politics gives people some type of immunity that allows them to take advantage of the position for personal gains.

The second part was call out. Once again in my humble opinion, calling out is of no use in our country. We saw the last president (a liberal) which entered office with debts and left a multi millionaire. We see all (should have used most) senators (both liberals and conservatives) that are in office for decades and amass huge fortunes. That is impossible to happen because they should be helping their constituents and not benefiting themselves from public office. When I heard president Trump claiming that he would “drain the swamp” I had to chuckle. That is almost impossible to do.

Today is Sunday. I was planning on completing this post yesterday, but one thing and the other and here we are. I read the news this morning and only one article called my attention. It appears (I do not trust single source news) that the European Union is about to start opening traveling from abroad. It is interesting that the USA is not included in the list at this time. People and organizations in the USA are already complaining.

No matter if you are a conservative or a liberal, you need to study the facts and then make a decision. By the way, my son gave me for Father’s day a mug with the following inscription “Annoy liberals Use FACTS and LOGIC”. You first need to select the proper and valid facts. If you are a liberal and want to believe that it is president Trump’s fault, then you have a problem because that is irrelevant. Allow me to now go into the logic part. I am first generation Italian. I have been visiting Italy through my entire life. I read about it and watch on-line videos. In particular, my wife and I have been watching a YouTube channel (will not say which to avoid bias towards it) which illustrates how people have observed the quarantine rules and guidelines for months. The results are obvious. In some sections of Italy there have been no COVID-19 cases. As time progresses, people are starting to gather to some extent yet following the guidelines.

Now let’s compare what is happening in our country. Traffic on roads is up to 75% of pre COVID-19 levels. I can see that when my wife and I go grocery shopping. That is not bad; it is a good thing. Our economy needs to be restarted. The problem is how we behave when we are in the presence of others. A couple weeks ago, my wife and I were on our way back dropping some bake goods (we are relatively good at cooking and baking) at the house of our granddaughters. We gathered in the garage keeping social distancing. No touching, hugging or kissing. We interacted for no more than 15 minutes and left.

We were driving our convertible with the top down and it was hot and sunny so we decided to drive by a popular grocery store to get some ice cream. We saw a considerable amount of people going into and leaving the store. We noticed that we did not have gloves and masks with us, so we drove home, got our protective equipment, and headed back.

We noticed that no other person was wearing gloves, and no more than 50% of the people had masks. Not only that, but people were getting close while browsing and picking up items from shelves. What happened to social distancing? The same goes for attending restaurants and bars. You need to use common sense in all these situations. That said, as we all know, common sense is not the most common of the senses. So, who do you think is responsible for spreading the COVID-19 virus? It is we! I hear over and over from family and friends that they are tired of the new rules and want to go back to normal life. Not only that, but we believe that we have the right to do whatever we wish whenever we desire. We do not live in a vacuum. We live with other people in our country and in the world. We all need to concentrate and getting into a new normal. If we just refuse because we have absurd concepts and beliefs, we will be left behind and alone. Stop blaming others for what you do and believe. We first need to change. Then, if there is something left behind, then we can get together to address the few things that might need to be adjusted.

OK, now just one more thing which happens to be closer to the subject of this post. I read “What you need to know about JavaScript ES6” by Christina. It just happens that the contents are quite similar to chapter 2 of “React – The Complete Guide (incl. Hooks, React Router and Redux)” by Maximilian Schwarzmuller published by O’Reilly. I am refreshing on React and other subjects in preparation for a project.

const myName = 'Bond, James Bond';
console.log("myName: " + myName);

myName = 'Moneypenny';
console.log("myName: " + myName);

Because the JavaScript language is loosely typed, one used to define variable of any type and assign a value. If you decided to assign a variable a value to be used as a constant, it could happen that the variable could accidentally be changed. That would create havoc in other parts of the code. For that reason ES6 introduced the concept of constants.

"myName: Bond, James Bond"
"TypeError: Assignment to constant variable.
    at behocif.js:4:8
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"

In this last code snippet, the constant myName is defined and assigned a value. We then display the value. All is well so far. Then we attempt to change the value for the constant (this would work if the constant was defined as var). As you can see an error is detected.

function printMyName(name, age) {
  console.log(name + " " + age);
}

const printName = (name, age) => {
  console.log(name + " " + age);
}

const printOnlyName = name => {
    console.log(name);
}

const multiply = (number) => {
  return number * 2;
}

const mult = number => number * 2;

let name = 'John';
let age = 22;

printMyName(name, age);
printName(name, age);
printOnlyName(name);

console.log(multiply(2));
console.log(mult(2));

In this example we define a function that displays a name and age. We then define an anonymous function and assigned it to a variable. As you can see there is no need to use the keyword function.

As a second example we can define a function that doubles the specified value. We can now use the arrow function (=>) to streamline the code. Note that when using a single argument, the need of the parenthesis ‘()’ is not required.

"John 22"
"John 22"
"John"
4
4

You can see that the same results are obtained by different implementations of functions using less code. Not only that, but once you become familiar and start using the new syntax, you would probably find it is easier to read which makes it easier to maintain.

Exports and imports are something that one uses when the number of JavaScript scripts increases. In general, regardless of the programming language you use, you should keep related functionality together. Classes are ideal, but if you are not using them, try keeping related operations on specified sets of data in a folder and possibly in a reduced set of files.

const person = {
	name: 'John';
}

export default person

In this example we have a file named person.js in which we define a constant person with a specified name. We then export the constant.

export const clean = () => {...};
export const baseDate = 10;

In the previous code snippet we have a file named utility.js which exports two items.

import person from './person.js'
import prs from './person.js'

import {baseData} from './utility.js'
import {clean} from './utility.js'

default export:
import person from './person.js'
import prs from './person.js'

named export:
import {smth} from './utility.js'
import {smth as Smth} from './utility.js' 
import * as bundled from './utility.js'

In this last code snippet the app.js file makes some imports. Try and edit the files and check out how imports and exports behave.

class Human {
  constructor() {
    this.gender = 'male';
  }
  
  printGender() {
    console.log(this.gender);
  }
}

class Person extends Human {
  constructor() {
    super();
    this.name = 'Bond; James Bond';
    this.gender = 'female';
  }
  
  printMyName() {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName();
person.printGender();

We define a class Human with a constructor and a method that displays the gender.

The class Person is defined extending the class Human. Note the constructor and the call to super() to execute the constructor in the parent class.

Finally we created a new object of class Person. We invoke methods from the Human and Person classes.

The results of executing the code snippet are displayed in the following screen capture:

"Bond; James Bond"
"female"

In the following code we generate a similar example to the last one but simpler.

class Human {
  gender = 'male';
  printGender = () => {
    console.log(this.gender);
  }
}

class Person extends Human {
  name = 'Bond; James Bond';
  gender = 'female';
  printMyName = () => {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName();
person.printGender();

We perform similar declarations but as you can verify the constructor function has been eliminated.

"Bond; James Bond"
"female"

The output of the last code snippet is displayed. Note that the same output is generated but using less and easier to follow code.

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];

console.log(numbers);
console.log(newNumbers);

This last code snippet illustrates the use of the Spread operator. We start by declaring the numbers array. We then declare the newNumbers which includes the elements of the previous array. In addition we include two new members.

[1, 2, 3]
[1, 2, 3, 4, 5]

The console.log statements display the resulting values. You might try removing the … (spread operator) and see what is returned for the newNumbers array.

const person = {
  name: 'Bond, James Bond'
}

const newPerson = {
  ...person,
  age: 22
}

console.log(person);
console.log(newPerson);

In the last code snippet we declare a constant and use an object. We then declare a new object and add the age element. The values are displayed.

[object Object] {
  name: "Bond, James Bond"
}
[object Object] {
  age: 22,
  name: "Bond, James Bond"
}

Try experimenting removing the … operator and make sure you understand the differences in the output.

const filter = (...args) => {
  return args.filter(el => el === 1);
}

console.log(filter(1, 2, 3, 1));

In this case the … Rest operator is used to take the elements of the argument array and return a new array in which the elements are set to 1 when the array element is also a 1. The function is then invoked.

[1, 1]

The results are displayed for the filter.

const numbers = [1, 2, 3 ];
[num1, num2] = numbers;

[num1, , num3] = numbers;
console.log(num1, num3);

We declare an array. We the extract and assign the first and second values to two new variables. If we wish to skip the second value and go for the third, we would use the second set of statements.

const number = 1;
const num2 = number;
console.log(num2);

// **** ****
const person = {
  name: 'John'
};

const secondPerson = person;
console.log(secondPerson);

person.name = 'James';
console.log(secondPerson.name);

// **** ****
person.name = 'John;'

// **** copy the properties, not the pointer to person ****
const thirdPerson = {
  ...person
};
console.log(thirdPerson);

We experiment with objects and how they are passed and assigned to functions. Remember that JavaScript passes objects and arrays by reference (not value).

1
[object Object] {
  name: "John"
}
"James"
[object Object] {
  name: "John;"
}

We see how the different variables display. The key is to understand how variables represent the address or the object itself.

const numbers = [ 1, 2, 3 ];

const doubleNumArray = numbers.map((num) => {
  return num * 2;
});

console.log(numbers);
console.log(doubleNumArray);

In this last code snippet we declare an array and a constant that represents a function that doubles the values passed to it.

[1, 2, 3]
[2, 4, 6]

The output from the two console.log statements is captured.

Hopefully you get a chance to experiment with the examples and see how they operate. For additional information on the code samples you should check on the Mozilla documentation.

If you have comments or questions regarding this, or any other post in this blog, or if you would like for me to serve of assistance with any phase in the SDLC (Software Development Life Cycle) of a project associated with a product or service, please do not hesitate and leave me a note below. If you prefer, send me a private message using the following address:  john.canessa@gmail.com. I will reply as soon as possible.

Keep on reading and experimenting. It is the best way to learn, refresh your knowledge and enhance your developer toolset!

One last thing, many thanks to all 1,253 subscribers to my blog!!!

Keep safe during the COVID-19 pandemic and help restart the world economy.

John

Twitter:  @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.