Tuesday, March 19, 2019

What Is Difference Between Dot Notation And Bracket Notation?

Accessing Properties on an Javascript Object
There are two ways to work/access properties(key/value pair) on a Javascript object:
• Dot Notation
• Bracket Notation

Dot Notation
Dot notation is used most frequently. Let's first look at Dot notation. Consider this example below:
let person = {
  name: 'Anup',
  age: 34
};
Here is a person object with 2 properties name and age. Let's say we need to change the name of the person, so we need to access the name property of an object Person. We can use dot notation as below
 person.name = 'John';
 console.log(person); // {name: 'John', age: 34}

 console.log(person.name); // John
This is an example of dot notation. You can change properties on an object by specifying the name of the object, followed by a dot (period) followed by the property name person.name = 'John'. Similarly we can use the dot notation to read the value of property like person.name.

Bracket Notation
You can access properties on an object by specifying the name of the object followed by the property name in brackets.
 person['name'] = 'Doe';
 console.log(person); // {name: 'Doe', age: 34}
When working with bracket notation, property identifiers only have to be a String. They can include any characters, including spaces. Variables may also be used as long as the variable resolves to a String.

Dot Notation Vs Bracket Notation
Dot notation is bit concise, shorter and much easier to read than bracket notation and is therefor used more often.

• However, bracket notation has its own uses. Sometimes you don't know the name of the target property until the runtime. With dot notation, we can’t use dynamic variables. For example, in our user interface, user might be selecting the name of the target property dynamically.
 let selection = 'name';
 person[selection] = 'Donald';
 console.log(person); // {name: 'Donald', age: 34}
In that case, at the time of writing the code we don't know that what property we're going to access. That is going to be selected at runtime by the user so might have another variable somewhere else like selection that determines the name of the target property that the user is selecting and that can change at the runtime. We can access that property using the bracket notation in a dynamic way so we can pass selection here and we get the same result in the console.

• It is okay to use variables, spaces, and Strings that start with numbers in the bracket notation i.e. obj['1prop'], obj['prop name'] where as in dot notation, property identifiers cannot start with a number and cannot contain variables and can only be alphanumeric (and _ and $) i.e. obj.prop_1, obj.prop$.

dot notation is mostly assuming the existence of the variables if there is no intellisense while with the bracket notation there is a sense of consciousness which is good, because you really to know what you are dealing with.

• One other advantage of bracket notation. If you flatten an object so that all variables are at the root of your object but you retain the dot in the variable name to represent the properties depth you can use bracket syntax: someObject['propCollection.property']

Reference: JavaScript Quickie— Dot Notation vs. Bracket Notation

How To Make Simple Stopwatch Using Plain Javascript?

In the plain javascript you can use factory function or construction function to create an object.

Let's create a stop watch example to show how to a create a construction function. It has three methods start, stop and reset and private variables are defined as startTime, endTime, running and duration. Also it is defined readonly property called duration using Object.defineProperty method. this keyword is being used to set the properties of an object Stopwatch.
function Stopwatch() {
    let startTime = null;
    let endTime = null;
    let running = false;
    let duration = 0;

    this.start = function() {
        if (running) {
            throw new Error('Stopwatch has already started.');
        }

        running = true;

        startTime = new Date();
    };

    this.stop = function() {
        if (!running) {
            throw new Error('Stopwatch is not started yet.');
        }

        running = true;

        endTime = new Date();

        const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
        duration += seconds;

    };

    this.reset = function() {
        startTime = null;
        endTime = null;
        running = false;
        duration = 0;
    };

    //readonly property
    Object.defineProperty(this, 'duration', {
        get: function() {
            return duration;
        }
    });

}
In your browser's console log, you can run this example as below
const sw = new Stopwatch();

sw.start()
sw.stop()
sw.duration
sw.reset()

Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh | Stop watch Exercise

Monday, March 18, 2019

Four Pillars of Object Oriented Programming in Javascript

Four Pillars of Object-oriented Programming (OOP)
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

Encapsulation
In object-oriented programming we group related variable and functions that operate on them into objects and it is called encapsulation. Let's look at the example.
let employee = {
 baseSalary: 30000,
 overtime: 10,
 rate: 20,
 getWage: function() {
   return this.baseSalary + (this.overtime * this.rate)
 }
};
employee.getWage();
We don't have any parameters in the getWage function is because all these parameters are actually modelled as properties of this object. All these properties and getWage function are highly related so they are a part of one unit (i.e employee object). In object-oriented way, your functions end up having fewer and fewer parameters. If fewer the number of parameters the easier it is to use and maintain that function so this is called encapsulation.

Encapsulation gives a couple of benefits as follows.
• Reduce Complexity - We group related variables and functions together and this way we can reduce complexity.
• Increase reusability - We can reuse these objects in different parts of a program or in different programs.

Abstraction
Think of DVD player as an object. This DVD player has a complex logic board on the inside and a few buttons on the outside that you interact with. You simply press the play button and you don't care what happens on the inside. All that complexity is hidden from you. This is abstraction in practice. We can use same technique in our objects so we can hide some of the properties and methods from the outside and this gives a couple of benefits.

• Simple Interface - We'll make the interface of those objects simpler. Understanding an object with a fewer properties and methods is easier than on object with several properties and methods.
• Reduce Complexity - With abstraction, we hide the details and the complexity and show only the essentials. This technique reduces complexity.
• Reduce or isolate the impact of change - Let's imagine that tomorrow we change inner or private methods of the object. None of these changes will leak to the outside because we don't have any code that touches these methods outside of their content object. We may delete a method or change its parameters but none of these changes will impact the rest of the applications code. So with abstraction we reduce the impact of change.

Inheritance
Inheritance is a mechanism that allows you to eliminate redundant code. Here is an example to think of HTML elements like text boxes, drop-down lists, checkboxes and so on. All these elements have a few things in common.

It should have properties like hidden and inner HTML and methods like click and focus. Instead of redefining all these properties and methods for every type of HTML elements we can define them once in a generic object. Lets called it HTML element and have other objects inherit these properties and methods.

Benefit: With inheritance we can eliminate redundant code.

Polymorphism
Poly means many and morph means form. Polymorphism means many forms. In object-oriented programming polymorphism is a technique that allows you to get rid of long if-and-else or Switch-case statements. So back to our HTML elements example, all these objects should have the ability to be rendered on a page but the way each element is rendered is different from others.

If we want to render multiple HTMl elements with object orientation, we can implement a render method in each of these objects and render method will behave differently depending on the type of the object viewer referencing. We can use one line of code like this element.render();

Benefit: With polymorphism we can refactor ugly switch case statements.
Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh Hamedani

Friday, March 15, 2019

Different Ways of Handling Forms in React

There are two types of form input in react. We have the uncontrolled input and the controlled input. The uncontrolled input are like traditional HTML form inputs, they remember what you typed. We will use ref to get the form values.

Travel form Challenge
You just started your own airline, and you need to create a form to collect data about your passengers' upcoming travel plans so they can book their flight.
You should collect the following information from the user:
First name (text input)
Last name (text input)
Age (number input)
Message (textarea)
Gender (radio buttons with 2 or more options)
Location they're traveling to (select box with at least 3 options. You're an airline that doesn't fly to many places...)
• Whether they have any dietary restrictions (check boxes for vegetarian, kosher, lactose free, etc. Include at least 3 options)

Each element of the form should be given a name attribute so you can access the data in JavaScript and do stuff with it. There should also be a button at the end of the form to submit it.

This exercise is adapted from the V School curriculum on vanilla JS forms:
https://coursework.vschool.io/travel-form

Remember to use the concept of controlled forms https://reactjs.org/docs/forms.html and uncontrolled forms(Refs and the DOM) https://reactjs.org/docs/refs-and-the-dom.html

#1 A controlled input form
The controlled input is when the react component that renders a form also controls what happens in that form on subsequent user input. Meaning, as form value changes, the component that renders the form saves the value in its state.

Controlled components are heavy duty. The defining characteristic of a controlled component is the displayed value is bound to component state; to update the value you execute a function attached to the onChange event handler on the form element. The onChange function updates the state property, which in turn updates the form element's value.
Fig: React Controlled form handling

import React, {Component} from "react"
class ControlledForms extends Component {
    constructor() {
        super()
        this.state = {
            firstName: "",
            lastName: "",
            age: "",
            message: "",
            gender: "",
            destination: "",
            isVegan: false,
            isKosher: false,
            isLactoseFree: false
        }
        this.handleChange = this.handleChange.bind(this)
    }
    
    handleChange(event) {
        const {name, value, type, checked} = event.target
        type === "checkbox" ? 
            this.setState({
                [name]: checked
            })
        :
        this.setState({
            [name]: value
        }) 
    }
    
    render() {
        return (
            <main className="container">
                <form>
                    <input 
                        name="firstName" 
                        value={this.state.firstName} 
                        onChange={this.handleChange} 
                        placeholder="First Name" 
                    />
                    <br />
                    
                    <input 
                        name="lastName" 
                        value={this.state.lastName}
                        onChange={this.handleChange} 
                        placeholder="Last Name" 
                    />
                    <br />
                    
                    <input 
                        name="age" 
                        value={this.state.age}
                        onChange={this.handleChange} 
                        placeholder="Age" 
                    />
                    <br />

                    <label>
                        <textarea
                            name="message"
                            onChange={this.handleChange}
                            placeholder="Enter message"
                            value={this.state.message}
                        >
                        </textarea>
                    </label>
                    <br />

                    <label>
                        <input 
                            type="radio" 
                            name="gender"
                            value="male"
                            checked={this.state.gender === "male"}
                            onChange={this.handleChange}
                        /> Male
                    </label>
                    
                    <br />
                    
                    <label>
                        <input 
                            type="radio" 
                            name="gender"
                            value="female"
                            checked={this.state.gender === "female"}
                            onChange={this.handleChange}
                        /> Female
                    </label>
                    
                    <br />
                    
                    <select 
                        value={this.state.destination} 
                        name="destination" 
                        onChange={this.handleChange}
                    >
                        <option value="">-- Please Choose a destination --</option>
                        <option value="Sweden">Sweden</option>
                        <option value="Norway">Norway</option>
                        <option value="Denmark">Denmark</option>
                        <option value="Finland">Finland</option>
                    </select>
                    
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isVegan"
                            onChange={this.handleChange}
                            checked={this.state.isVegan}
                        /> Vegan?
                    </label>
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isKosher"
                            onChange={this.handleChange}
                            checked={this.state.isKosher}
                        /> Kosher?
                    </label>
                    <br />
                    
                    <label>
                        <input 
                            type="checkbox"
                            name="isLactoseFree"
                            onChange={this.handleChange}
                            checked={this.state.isLactoseFree}
                        /> Lactose Free?
                    </label>
                    <br />
                    
                    <button>Submit</button>
                </form>
                <hr />
                <h2>Entered information:</h2>
                <p>Your name: {this.state.firstName} {this.state.lastName}</p>
                <p>Your age: {this.state.age}</p>
                <p>Your Message: {this.state.message}</p>
                <p>Your gender: {this.state.gender}</p>
                <p>Your destination: {this.state.destination}</p>
                <p>Your dietary restrictions:</p>
                
                <p>Vegan: {this.state.isVegan ? "Yes" : "No"}</p>
                <p>Kosher: {this.state.isKosher ? "Yes" : "No"}</p>
                <p>Lactose Free: {this.state.isLactoseFree ? "Yes" : "No"}</p>
                
            </main>
        )
    }
}

export default ControlledForms

The goal is that each time the input changes, the method handleChange is called and will store the input state. Hence the component always has the current value of the input without needing to ask for it. This means that the form component can respond to input changes immediately.

To be able to handle multiple form inputs, we need a way to capture the input with a method instead of declaring multiple methods to do this. Hence we are creating dynamic handleChange method so that our form input can reference it to update it states dynamically.

The value of the name attribute on each input must be the same with the state name declared in the formControls in the constructor.

#2 A uncontrolled input form
An easier, and less labor-intensive way to grab values from a form element is to use the ref property in the form itself.
import React, {Component} from "react"
class UncontrolledForms extends Component {

    handleSubmit = (event) => {
        event.preventDefault();
        const { firstName, lastName, age, message, gender, destination, dietary_restriction } = this.form;

        // convert node list to an array
        const dietaryRestrictionCheckboxArray = Array.prototype.slice.call(dietary_restriction);
        // extract only the checked checkboxes
        const dietaryCheckedCheckboxes = dietaryRestrictionCheckboxArray.filter(input => input.checked);
        // use .map() to extract the value from each checked checkbox
        const dietaryCheckedCheckboxesValue = dietaryCheckedCheckboxes.map(input => input.value);

        const data = {
            firstName: firstName.value,
            lastName: lastName.value,
            age: age.value,
            message: message.value,
            gender: gender.value,
            destination: destination.value,
            dietaryOptions: dietaryCheckedCheckboxesValue
        }

        //alert(JSON.stringify(data));
        console.log(data);
    }
    
    render() {
        return (
            <main className="container">
                <form onSubmit={this.handleSubmit} ref={myform => this.form = myform}>
                    <input name="firstName" placeholder="First Name" />
                    <br />
                    
                    <input name="lastName" placeholder="Last Name" />
                    <br />
                    
                    <input name="age" placeholder="Age" />
                    <br />

                    <textarea name="message" placeholder="Enter message"></textarea>
                    <br />

                    <input type="radio" name="gender" value="male"/> Male
                    <br />
                    <input type="radio" name="gender" value="female"/> Female
                    <br />

                    <select name="destination">
                        <option value="">-- Please Choose a destination --</option>
                        <option value="Sweden">Sweden</option>
                        <option value="Norway">Norway</option>
                        <option value="Denmark">Denmark</option>
                        <option value="Finland">Finland</option>
                    </select>
                    <br />
                    
                    <input type="checkbox" value="vegan" name="dietary_restriction"/>Vegan?
                    <br />
                    <input type="checkbox" value="kosher" name="dietary_restriction"/>Kosher?
                    <br />
                    <input type="checkbox" value="lactoseFree" name="dietary_restriction"/>Lactose Free?
                    <br />
                    <button>Submit</button>
                </form>
                <hr />
            </main>
        )
    }
}

export default UncontrolledForms



Different ways of using refs on form elements
Different form elements and component compositions require different strategies, so the rest of this post is divided into the following sections.

i. Text & number inputs, selects
Text and number inputs provide the most straightforward example of using refs. In the ref attribute of the input, add an arrow function that takes the input as an argument.
<input  
  type="text"
  ref={input => this.fullName = input} />
Since it's an alias for the input element itself, you can name the argument whatever you'd like:
<input  
  type="number"
  ref={cashMoney => this.amount = cashMoney} />
ii. Radio sets
Unlike text and number input elements, radios come in sets. Each element in a set has the same name attribute, like so:
There are two options in the gender radio set – 'male' and 'female'.

Since the whole set is the object of our concern, setting a ref on each radio input is not ideal. And, unfortunately, there's no DOM node that encapsulates a set of radios.

Retrieving the value of the radio set can be obtained through three steps:
1. Set a ref on the <form> tag
2. Extract the set of radios from the form. In this case, it is the gender set
3. Grab the value of the set using dot notation

iii. Checkbox sets
Unlike a radio set, a checkbox set may have multiple values selected. This makes extracting these values a little more complicated than extracting the value of a radio set.

Retrieving the selected values of the checkbox set can be done through these five steps:
1. Set a ref on the <form> tag.
2. Extract the set of checkboxes from the form.
3. Convert the node list to an array, so array methods are available.
4. Use Array.filter() to grab only the checked checkboxes.
5. Use Array.map() to keep only the values of the checked checkboxes.


The primary value of using refs over controlled component is that, in most cases, you will write less code. The exceptional case is that of checkbox sets (and radios to a lesser degree). Source: Learn React for free
Travel Form Challenge
React.js Forms: Using Refs
The complete guide to Forms in React

Tuesday, March 5, 2019

How To Handle Events in React - Different Way vs Best Way?

In the Facebook docs, you’ll see event handling done like this:
// option 1
class Thing extends React.Component {
  constructor() {
    this.handleSmthng = this.handleSmthng.bind(this)
  }
  render() {
    <input onChange={this.handleSmthng}/>
  }
  handleSmthng(e) {
    // ...
  }
}
ES6 classes won’t automatically give this scope to handleSmthng, and since you’ll usually want to call this.setState or perhaps invoke another method in the component, the “official” convention is to bind all the event handlers all the time in constructor. This works, but can quickly feel like boilerplate code.
// option 2
class Thing extends React.Component {
  render() {
    <button onClick={() => this.handleSmthng('foo')}>
      ADD
   </button>
  }
  handleSmthng(arg1) {
    // ...
  }
}
It will pass this context to handleSmthng and it avoids boilerplate code in the constructor. Heck, there’s no state in this component so you don’t even need a constructor! I think the motivations for this approach are right… but there’s a slight performance cost. Using an arrow function will always create a new reference in JavaScript which, in turn, increases memory usage for your apps. While memory is cheap in JavaScript, renders are costly in React. When you pass arrow functions to child components, your child component will indiscriminately re-render since (as far as it’s concerned) that arrow function is new data.

There’s a much cleaner way to write event handlers that
1) avoids boilerplate and
2) doesn’t cause extra re-renders: property initializer syntax!
It’s a fancy name, but the idea is really simple… just use arrow functions to define your event handlers. Like this:
class TodoApp extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          ADD
        </button>
        <input onChange={this.handleInput}/>
      </div>
    );
  }
  handleClick = () => {
    // "this"
  }
  handleInput = (e) => {
    // "this", "e"
  }
}
You defined two handlers, and it’s looking really nice. No boilerplate. Easy to read. Easy to re-factor… if you want to pass arguments:
class TodoApp extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          ADD
        </button>
        <input onChange={this.handleInput}/>
        {
          this.state.todos.map((item) => {
            return (
              <li onClick={this.handleRemove(item.id)}>
                {item.text}
              </li>
            );
          });
        }
       {
    // "this"
  }

  handleInput = (e) => {
    // "this", "e"
  }

  handleRemove = (id) => (e) => {
    // "this", "e", "id"
  }
}
You can pass arguments without using bind in your render methods, or your constructor! Everything looks really spick and span.
Source: A New Way to Handle Events in React