JavaScript & React Hooks Some Filtering Topics You Need To Know

JavaScript variables are loosely/dynamically typed and the language doesn’t care how a value is declared or changed
  1. javascript Truthy & Falsy value

In JavaScript, truthy are expressions which evaluate to boolean true value and falsy evaluates to boolean false value. Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms.

As well as a type, each value also has an inherent boolean value, generally known as either truthy or falsy. Some of the rules are a little bizarre so understanding the concepts and effect on comparison helps when debugging JavaScript applications.

The following values are always falsy:

  • false
  • 0 (zero)
  • '' or "" (empty string)
  • null
  • undefined
  • NaN

Everything else is truthy. That includes:

  • '0' (a string containing a single zero)
  • 'false' (a string containing the text “false”)
  • [] (an empty array)
  • {} (an empty object)
  • function(){} (an “empty” function)

A single value can therefore be used within conditions, e.g.

if (value) {
// value is truthy
}
else {
// value is falsy
// it could be false, 0, '', null, undefined or NaN
}

2. NULL & UNDEFINED

At first glance, null and undefined may seem the same, but they are far from it. This article will explore the differences and similarities between null and undefined in JavaScript.

There are two features null you should understand:

  • null is an empty or non-existent value.
  • null must be assigned.

Here’s an example. We assign the value of null to a:

let a = null;
console.log(a);
// null
let b;console.log(b);
// undefined

You can also explicitly set a variable to equal undefined:

let c = undefined;console.log(c);
// undefined

Finally, when looking up non-existent properties in an object, you will receive undefined:

var d = {};console.log(d.fake);
// undefined

3. Double & Triple Equals
JavaScript has two visually similar, yet very different, ways to test equality. You can test equality with == or ===. Here are the differences:

Type coercion means that two values are compared only after attempting to convert them into a common type.

An example will illustrate this. Recall earlier when we tested the following with strict equality:

77 === '77'
// false (Number v. String)

77 does not strictly equal '77' because they have different types. However, if we were to test these values with loose equality…

77 == '77'
// true

You can see we get true. That because of type coercion. JavaScript will actually try to convert our values into a like type. In this case, it succeeds. The string value '77' can easily be converted into the number value of 77. Since 77 equals, we get our answer to true.

Let's look at a couple of examples of strict equality.

In this first example, we’re comparing the number 5 with the number 5. As expected, true is returned. Both are numbers, and both share the same value of 5.

5 === 5
// true

With this in mind, we can look at two more examples that will return true:

'hello world' === 'hello world'
// true (Both Strings, equal values)true === true
// true (Both Booleans, equal values)

Awesome. Now let's take a look at some examples that will return false:

In this example, we’ll compare the number 77 to the string value of 77. This means our operands will have the same value, but a different type. This will return false

77 === '77'
// false (Number v. String)

Here are two additional examples:

'cat' === 'dog'
// false (Both are Strings, but have different values)false === 0
// false (Different type and different value)

4. javaScript Map & Filter

This method can have many uses when working with arrays. In this tutorial, you’ll look at four noteworthy uses of in JavaScript: calling a function of array elements, converting strings to arrays, rendering lists in JavaScript libraries, and reformatting array objects.

.map() accepts a callback function as one of its arguments, and an important parameter of that function is the current value of the item being processed by the function. This is a required parameter. With this parameter, you can modify each item in an array and create a new function.

Here’s an example:

const sweetArray = [2, 3, 4, 5, 35]
const sweeterArray = sweetArray.map(sweetItem => {
return sweetItem * 2
})
console.log(sweeterArray)

This output is logged to the console:

Output[ 4, 6, 8, 10, 70 ]
var numbers = [1, 3, 6, 8, 11];var lucky = numbers.filter(function(number) {
return number > 7;
});
// [ 8, 11 ]

The example above takes the numbers array and returns a new filtered array with only those values that are greater than seven.

Filter syntax

var newArray = array.filter(function(item) {
return condition;
});

The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.

If the current item passes the condition, it gets sent to the new array.

Filtering an array of objects

A common use case of .filter() is with an array of objects through their properties:

var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]

5.Find an array of objects

Searching in an array of objects can be done in Javascript using a loop, Array.find(), or Array.findIndex() methods.

You can iterate through the array using a for a loop.

var __POSTS = [ 
{ id: 1, title: 'Apple', description: 'Description of post 1' },
{ id: 2, title: 'Orange', description: 'Description of post 2' },
{ id: 3, title: 'Guava', description: 'Description of post 3' },
{ id: 4, title: 'Banana', description: 'Description of post 4' }
];
// Search for post with title == "Guava"
var __FOUND = -1;
for(var i=0; i<__POSTS.length; i++) {
if(__POSTS[i].title == 'Guava') {
// __FOUND is set to the index of the element
__FOUND = i;
break;
}
}
// On success __FOUND will contain the index of the element
// On failure it will contain -1
console.log(__FOUND); // 2

The Array.find() method takes a callback function as a parameter and executes that function once for each element present in the array until it finds one where the function returns a true value.

If the element is found it returns the value of the element, otherwise undefined is returned.

var __POSTS = [ 
{ id: 1, title: 'Apple', description: 'Description of post 1' },
{ id: 2, title: 'Orange', description: 'Description of post 2' },
{ id: 3, title: 'Guava', description: 'Description of post 3' },
{ id: 4, title: 'Banana', description: 'Description of post 4' }
];
var __FOUND = __POSTS.find(function(post, index) {
if(post.title == 'Guava')
return true;
});
// On success __FOUND will contain the complete element (an object)
// On failure it will contain undefined
console.log(__FOUND); // { id: 3, title: 'Guava', description: 'Description of post 3'

6. Scope, Block Scope

Scope determines the visibility or accessibility of a variable or other resource in the area of your code.

There’s only one Global scope in the JavaScript document. The area outside all the functions is considered the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

//global scope
var fruit = 'apple'
console.log(fruit); //apple
function getFruit(){
console.log(fruit); //fruit is accessible here
}
getFruit(); //apple

Variables declared inside the functions become Local to the function and are considered in the corresponding local scope. Every function has its own scope. The same variable can be used in different functions because they are bound to the respective functions and are not mutually visible.

//global scope
function foo1(){
//local scope 1
function foo2(){
//local scope 2
}
}
//global scope
function foo3(){
//local scope 3
}
//global scope

A local scope can be divided into function scope and block scope. The concept of block scope is introduced in ECMA Script 6 (ES6) together with the new ways to declare variables — const and let.

Whenever you declare a variable in a function, the variable is visible only within the function. You can’t access it outside the function. var is the keyword to define variables for function-scope accessibility.

function foo(){
var fruit ='apple';
console.log('inside function: ',fruit);
}
foo(); //inside function: apple
console.log(fruit); //error: fruit is not defined

Block scope is the area within if, switch conditions or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

function foo(){
if(true){
var fruit1 = 'apple'; //exist in function scope
const fruit2 = 'banana'; //exist in block scope
let fruit3 = 'strawberry'; //exist in block scope
}
console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
}
foo();
//result:
//apple
//error: fruit2 is not defined
//error: fruit3 is not defined

7. Bind, call & apply

You can use call()/apply() to invoke the function immediately. bind() returns a bound function that, when executed later, will have the correct context ("this") for calling the original function. So bind() can be used when the function needs to be called later in certain events when it's useful.

To get a grasp of “this” in JavaScript, read Understanding “This” in JavaScript.

Check the code sample below for call()

//Demo with javascript .call()var obj = {name:"Niladri"};var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
console.log(greeting.call(obj,"Newtown","KOLKATA","WB"));
// returns output as welcome Niladri to Newtown KOLKATA in WB

The first parameter in call() the method sets the "this" value, which is the object, on which the function is invoked. In this case, it's the "obj" object above.

The rest of the parameters are the arguments to the actual function.

Check the below code sample for apply()

//Demo with javascript .apply()var obj = {name:"Niladri"};var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
// array of arguments to the actual function
var args = ["Newtown","KOLKATA","WB"];
console.log("Output using .apply() below ")
console.log(greeting.apply(obj,args));
/* The output will be
Output using .apply() below
welcome Niladri to Newtown KOLKATA in WB */

Similarly to call() method the first parameter in apply() the method sets the "this" value which is the object upon which the function is invoked. In this case, it's the "obj" object above. The only difference between the method is that the second parameter of the apply() method accepts the arguments to the actual function as an array.

Check the below code sample for bind()

//Use .bind() javascriptvar obj = {name:"Niladri"};var greeting = function(a,b,c){
return "welcome "+this.name+" to "+a+" "+b+" in "+c;
};
//creates a bound function that has same body and parameters
var bound = greeting.bind(obj);
console.dir(bound); ///returns a functionconsole.log("Output using .bind() below ");console.log(bound("Newtown","KOLKATA","WB")); //call the bound function

8. React Hooks Recap

React Hooks are a way for your function components to “hook” into React’s lifecycle and state. They were introduced to React Previously, only Class-based components were able to use React’s lifecycle and state. Aside from enabling Function components to do this, Hooks make it incredibly easy to reuse stateful logic between components.

If you are moving to Hooks for the first time, the change can be a little jarring. This chapter is here to help you understand how they work and how to think about them. We want to help you transition from the mental model of Class components to function components with React Hooks. Here is what we’ll be covering:

  1. A quick refresher on the lifecycle of Class components
  2. An overview of the lifecycle of Function components with Hooks
  3. A good mental model to understand React Hooks in Function components
  4. A subtle difference between Class and Function components

Ah, state. A cornerstone of the React ecosystem. Let’s get our feet wet with Hooks by introducing the most common hook that you will be working with — useState().

Let’s take a look at a class component that has a state.

import React, { Component } from 'react';
import './styles.css';
class Counter extends Component {
state = {
count: this.props.initialValue,
};
setCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<h2>This is a counter using a class</h2>
<h1>{this.state.count}</h1>
<button onClick={this.setCount}>Click to Increment</button>
</div>
);
}
}
export default Counter;

With React Hooks, we can rewrite this component and remove a lot of stuff, making it easier to understand:

import React, { useState } from 'react';function CounterWithHooks(props) {
const [count, setCount] = useState(props.initialValue);
return (
<div>
<h2>This is a counter using hooks</h2>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Click to Increment</button>
</div>
);
}
export default CounterWithHooks;

On the face of it there is less code, but what’s going on?

So we’ve seen our first hook! Hurrah!

const [count, setCount] = useState();

Let’s apply our newly minted useState clone in a familiar-looking setting. We’ll make a Counter component!

// Example 1
function Counter() {
const [count, setCount] = useState(0) // same useState as above
return {
click: () => setCount(count() + 1),
render: () => console.log('render:', { count: count() })
}
}
const C = Counter()
C.render() // render: { count: 0 }
C.click()
C.render() // render: { count: 1 }

Here, instead of rendering to the DOM, we’ve opted to just console.log out our state. We’re also exposing a programmatic API for our Counter so we can run it in a script instead of attaching an event handler. With this design, we can simulate our component rendering and react to user actions.

While this works, calling a getter to access the state isn’t quite the API for the real React.useState hook. Let’s fix that.

If we want to match the real React API, our state has to be a variable instead of a function. If we were to simply expose _val instead of wrapping it in a function, we’d encounter a bug:

// Example 0, revisited - this is BUGGY!
function useState(initialValue) {
var _val = initialValue
// no state() function
function setState(newVal) {
_val = newVal
}
return [_val, setState] // directly exposing _val
}
var [foo, setFoo] = useState(0)
console.log(foo) // logs 0 without needing function call
setFoo(1) // sets _val inside useState's scope
console.log(foo) // logs 0 - oops!!

This is one form of the Stale Closure problem. When we destructured foo from the output of, it refers to the _val as of the initial useState call… and never changes again! This is not what we want; we generally need our component state to reflect the current state, while being just a variable instead of a function call! The two goals seem opposed.

9. Accessibility

React has also developed a stigma within the accessibility community that web applications created in React are not accessible. Lots of accessibility advocates, and even developers who develop in the framework, think that accessibility is a very big challenge that can be almost impossible to achieve. Some of these issues include:

  • One generic page title that cannot change
  • Focus management makes applications impossible to navigate with the keyboard
  • Extra added <div> and wrappers can break semantics
  • Using semantic HTML is hard to achieve

This one may be pretty obvious, however, there is still React content that does not use semantic HTML to create basic elements on the page. Instead of creating a button with <div> and <span>, use the <button> tags that have inherent meaning for assistive technology. The more semantics you can use in your application, the easier it will be on you (the developer) and the assistive technology user.

React fully supports building accessible websites, often by using standard HTML techniques. We are going to look at a few ways to make your react applications more accessible.

Tip: Use Bit to build React apps faster with components. It helps your team share components and reuses them to quickly build new apps. It’s great for keeping a set of accessible components you can use. Give it a try.

10. Alt Text on Images

The alt (or “alternate”) the attribute is another quick way of making your React app more accessible. When a screen reader reaches an image, it will read out loud the alt text to describe the image’s content.

const AlligatorImg = () => (
<img
src='./img/alligator.png'
alt='Alligator coming out of water with mouth open'
/>
)

The purpose of the alt text is for the person hearing it to understand the content of the image. It should be specific enough that the person can imagine the image without seeing it.

Conclusion

We have now learned the JavaScript main Filtering Concept what we can accomplish. If you feel inspired to build on these examples. Cheers!

I’m A Professional React Js Web Developer & Cyber Security Specialist that will assist me in developing, improving, and obtaining the necessary skills.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store