A Quick Overview of map(), filter(), and reduce() in JavaScript

Image by Nathan Dumlao

Learn how to use map, filter, and reduce in JavaScript.

Higher Order Functions

A higher-order function is a function that takes one or more functions as arguments or returns a function as its result. map, filter, andreduce are all higher order functions, which take a function as an argument.

Map, Filter, Reduce Fundamentals

All the functions are part of the JavaScript Array prototype which means they must be called directly on an array.

const arr = [1, 2, 3]
arr.map()
arr.filter()
arr.reduce()

When we are using map,filter, and reduce, we cannot:

  • break the loop
  • use continue

map → Executes a function on each element of an array

Every element of the array is passed to the callback function and returns a new array with the same length.

When to use map: If we want to perform the same operation/transformation on each element of the array and get back a new array of the same length with the transformed values.

Example 1 :

var numbers= [1,2,3,4,5];
var doubled  = numbers.map(n => n * 2);
doubled; // [2,4,6,8,10]

filter → Remove items which don’t satisfy a condition

Every element of the array is passed to the callback function. On each iteration, if the callback returns true, then that element will be added to the new array, otherwise, it is not added to the new array.

var numbers = [1,2,3,4,5];
var greaterThan2 = numbers.filter(n => n > 2);
greaterThan2; // [3,4,5]

Reduce → Creates a single value from elements of Array

While using reduce, we need to declare the initial value of accumulator(final result). On each iteration, inside the callback we perform some operation and that will be added to the accumulator.

Example 1: Sum of numbers

var numbers = [1,2,3,4,5];
var initialVal = 0;
let result=numbers.reduce((accu, val) => val + accu , initialVal);
console.log(result) // 15

Example 2: Creating an array of objects from user names

https://gist.github.com/Jagathishrex/7261bcc6cae88a629fd28759ac119805#file-reduce-js

Real-world example

Let’s create a real-world practical example: Conducting an Interview

  • map: Conducting a test for multiple candidates
  • filter: Selecting candidates who passed the test
  • reduce: Creating a team from the selected candidates

https://gist.github.com/Jagathishrex/3ee5f85a69d31a723cbead54d13afec8#file-map_filter_reduce-js

Join your hand🖐 with me Javascript Jeep🚙💨.

Buy me a coffee

Buy me a coffee

Creating a Color Generator Website in JavaScript

Learn about how to create a website which will generate unique colours

Image by Paola Galimberti

This is how the final result looks like

In this tutorial we are only focusing on Javascript , you can just copy and paste the html and css from the above pen.


The UI has

  • Color Block → Created using JavaScript
  • Button → When we click the button we need to generate 10 random unique color blocks
  • Container → Color Block are appended to Container block

When the user click a button we need to

  • Generate Random Colour
  • Create a color Block
  • Make sure the colour is not already present
  • Append the color block to the container

Generating random Hex colours

We know that , hex colours has 1–9 and a-f

To generate random colours

  • Store hex values on array
  • Use math.rand to get index
  • Create a color string of length 6 or three

https://gist.github.com/Jagathishrex/13a7dab8cff2e9e904b5948bd1eaa35b#file-random_color-js

Math.random() → Generate a random number between 0 and 1 . We can multiply the random number with the length-1 of the array to get a random index.

View at Medium.com

When we call generateColor method , it will give us a random color String.

We need to make sure that the color is unique .

To store unique values we can use Set → collection of elements which does’t have duplicate values.

Learn about Set

View at Medium.com

Let’s create the set and add event listener to the button.

var set = new Set();
var btn = document.getElementById('button');
btn.addEventListener('click', function (ev) {
    // operation
});

When the user click the btn we need to generate 10 random unique colours ,for that

  • we can store the current set length in a variable size
  • Create a random color
  • Check if random color already present in the set
  • If not present in the set , then add the color to the set , create a color block and append to the container.
  • If already present in the set do nothing
  • On completion of each iteration we need to check if the set.size is less than size(old Set size)+ 10 variable
  • If the set.size is greater than size+10 than the loop will be terminated
let size = set.size; // old set Size
while(set.size < (size + 10) ) {
      let newColor = generateColor();
      if(!set.has(newColor)){
          set.add(newColor);
          // addColorBlock;
      }
}

Let’s implement addColorBlock function

function addColorBlock(color) {
   let child = document.createElement('div'),
   p = document.createElement('p');
   child.style.background = color;
   p.innerText = color.toUpperCase();
   child.append(p);
   child.classList.add("child");
   container.append(child);
}

Join your hand 🖐 with me Javascript Jeep🚙💨.

Buy me a coffee.

Buy me a coffee.

Become a writer in JavaScript Dots .

Submitting story to JavaScript Dots.

Image by The Climate Reality Project

Want to spread your teaching skills to the world . Let’s us help you by publishing your story through our publication and make the story travel 🧳 through the world 🌍 .

We will publish any submission related to the JavaScript.

Checklist before submitting stories

Mandatory

  • Add an Attractive Title
  • Add a cover image relative to your story
  • Please add reference of the story

Optional

  • If you want to add other story link you can add
  • Don’t forgot to add follow me (yours) medium profile

Send a mail to jagathish1123@gmail.com with Your story link. We will review within a day and add you as a writer .

Thanks 🙏 .

Basics of loops in JavaScript

Learn about Different ways to loop in JavaScript

Image by Tine Ivanič

What is Loop ?

Consider we need to print “hi” 5 times. If we don’t have loop , what we would be doing is

console.log("hi");
console.log("hi");
console.log("hi");
console.log("hi");
console.log("hi");

But , if we know how to use loop , then we can simplify the above code to

for(let i = 1; i <= 5; i++) {
console.log('👋');
}

Loop

Looping is a way of executing the same function repeatedly .

In other words

Loops are used to execute the same block of code again and again, until certain condition is met.

Different Types of Loops available in JavaScript

  • for
  • while
  • do while

for

syntax

for(initialValue; condition; step or increment) {
// operation
}

Example .

for(let i = 0 ;i < 5; i = i + 1) {
console.log(i);
}

In the above code

  • initialValue →i = 0 → Will be executed at the beginning of the loop
  • condition → i < len → is checked every-time before the body of the loop is executed
  • operation → console.log(i) ; → body of the loop
  • step/increment → i = i+1 → Executed every-time after each iteration.

Let’s breakdown how it works

At the beginning of the for loop 
 i = 0 ; is initialised 

First Iteration
 i < len is checked
 i is printed

After end of first iteration
i = i + 1 is executed
Second iteration

i < len check

print i
This will be repeated  until the condition becomes false.

The above code will be executed like

for (let i = 0; i < 2; i++)  {
console.log(i);
}
// initial Value
let i = 0
// if condition → execute body 
if (0 < 2) → true → log(1)
// increment 
i = i+1;
i = 1;
// if condition → execute body 
if (1 < 2) → true → log(1)
// increment 
i = i+1;
i = 2;
// if condition → execute body
if (2 < 2) → false→ loop terminated

If you want to break the loop , while running the loop , we can use break . break keyword will break the loop , break keyword is only valid inside looping statement.

for(let i =0; i < 5; i = i +1 ){
if(i > 2) {
break;
}
console.log(i);
}
// the above code will print
0,1,2, when the value of i is 3 the loop breaks

In some case we don’t need to execute the operation for specific value for that we can use continue statement. continue statement will break the current iteration . Once the JavaScript engine Executes continue statement , the block of code below the continue statement will not be executed.

for(let i =0; i < 5; i = i +1 ) {
if(i%2 == 0) {
continue; // if continue is
}
console.log(i);
}
1,3

The initial value, condition and increment all are optional

for(;;) {
console.log("Infinite loop");
}

Example 1 : without initial value

var i = 0;
for( ; i< 5 ; i = i+1 ) {
console.log(i);
}

Example 2 : without condition

var i = 0;
for(;; i =i + 1) {
if( i < 5) {
break;
}

console.log(i);
}
// output
0,1,2,3,4

Example 3 : without increment

var i = 0;
for(;;) {
if( i < 5) {
break;
}
console.log(i);
i = i + 1;
}
// output
0,1,2,3,4

while loop

syntax

while(condition) {
operation
}

In while loop we have only space for checking condition .

let i = 0;
while(i < 5) {
console.log(i);
i = i + 1;
}
//output 
1,2,3,4,5

If we forgot the increment then it will result in infinite loop

let i = 0;
while(i < 5) {
console.log(i);
}

In the above code the value of i will always 0 , so the loops run infinitely .

The break and continue work same for while also

let i = 0;
while(i < 5) {
if(i == 2) {
break;
}

console.log(i);
}
//output
0,1

continue

let i = 0;
while(i < 5) {
if(i == 2) {
continue
}

console.log(i);
i = i + 1;
}
//output
0,1,3,4,5

do while

syntax

do {
// body
} (condition is checked)

do…while loop will execute the body once , then it check for the condition , If the condition is true , it go for next iteration, otherwise stop the loop.

let i = 0;
do{
   console.log(i);
} while(i != 0);
//output
0;

In the above code even though i !=0 condition fails , the body of the do…while is executed once.

let i = 0;
do {
console.log(i);
i = i + 1;
} while (i < 3);
// output
0,1,2

We can also use break and continue inside the loop.

Let’s join your hand 🤚 with me JavaScript Jeep🚙💨 .

Buy me a coffee.

Buy me a coffee.

Six ways to create an Array in JavaScript.

Learn Different ways to create JavaScript Arrays.

Image by Clem Onojeghuo

1 . Using assignment operator

var array = [];
var array2 = [1,2,3,4,5];

2. Using new operator

new Array(length) ;

  • Creates an array with length set to the number.
  • length > 0 otherwise it will throw error
var arr = new Array(2);
arr; [empty × 2]
arr.length; // 2
arr[0]; undefined
// when we set
arr[3] = 10; //It will increase the array size
[empty × 3, 10]

3. Using Array.from

var arr = Array.from({length : 2});
arr; // [undefined, undefined]
arr[0] = 1; arr[1] = 2;
var arrCopy = Array.from(arr);
arrCopy; // [1,2]

4. Usign Spread operator

var arr =  [1,2,3,4,5]
var array2 = [ ...arr ]
array2; // [1,2,3,4,5]

5. Using Array

Creates a new array with the arguments as items. The length of the array is set to the number of arguments.

var array = Array(1,2,3,4,5);
array; // [1,2,3,4,5]

If we pass single number argument , then the Array constructor will create a new Array of the length equivalent to the argument

var array= Array(5);
array; //[empty x 5]

If we pass string

var array= new Array("5");
array; ["5"]

To create a Array with single number elemennt , we can use Array.of

6. Using Array.of

It is similar to Array constructor . But

  • . Array.of(5) → [5]
  • Array(5) → [empty x 5]
var array = Array.of(5);
array; / [5]
var array2 = Array.of(1,2,3,4,5,6, "string");
array2; // [1, 2, 3, 4, 5, 6, "string"]

Follow me JavaScript Jeep🚙💨 .

Buy me a coffee.

Buy me a coffee

Other articles

View at Medium.com

Detecting the End of CSS Transition Events in JavaScript

An overview of proper chaining

Image by Hello I’m Nik 🇬🇧

Before CSS transition and animation (keyframes), to animate, we needed to code in JavaScript. But once these two properties were introduced, we can achieve complex animations with only CSS.

In JavaScript, we can call the callback function once the animation is done. But in CSS, there is no option to perform any action after the end of the transition/animation.

Whenever the transition is finished, the transitionend event will be triggered. We can use this event to find the end of the transition. We can also use it like ontransitionend.

If the browser is WebKit-based then we need to define the prefix for the event.

    "transition"      : "transitionend",
    "OTransition"     : "oTransitionEnd", // opera
    "MozTransition"   : "transitionend", // mozilla
    "WebkitTransition": "webkitTransitionEnd"

Let’s create a practical example to detect the end of a transition.

We are going to create a search box that will expand when we focus on the input.


HTML: Create an Input Box

<input type="text" class="search" placeholder = "Enter the text">

CSS: Add Style to the Input Box

.search {
width : 200px;
height :30px;
border :5px solid red;
border-radius : 10px;
padding : 10px;
color : blue;
outline:none;
transition : all .3s linear;
}

Once the input box is focused, we need to increase its width.

.expand {
width : 50vw;
}

JavaScript: Add focus and focusout Listeners

let input = document.querySelector('.search');
input.addEventListener('focus',  function(ev, data) {
input.classList.add('expand');
});
input.addEventListener('focusout',  function(ev, data) {
input.classList.remove('expand');
});

This will create an expanding input box.

Now we need to detect the transition end event based on the browser. We can detect that by checking any of the transition events, available in the style attribute of any element.

https://gist.github.com/Jagathishrex/25870f6e6d85dee709744f7db9f9846f#file-gettransitoin-js

// using above code we can get Transition end event name
let transitionEndEventName = getTransitionEndEventName();

Now, we need to add the event listener once the input is focused. For that, add the event listener inside the focus event callback:

input.addEventListener('focus',  function(ev) {
  input.classList.add('expand');
input.addEventListener(transitionEndEventName, callback);
});

Once the transition is finished, the callback function will be called.

We also need to remove the transitionend event once the callback is executed, otherwise, the listener will keep running, causing it to run multiple times.

For example: On focusing input, the input box expands. This is one transition, and once the focus is out, the input box shrinks. This is also a transition. So, we need to remove the event listener inside the callback function.

function callback(ev) {

console.log("transition finished ");
input.removeEventListener(transitionEndEventName, callback);
}

The complete code:

We can detect the name of the transition using the propertyName attribute in the ev argument of the callback function. We can also find the time taken to end the transition using the elapsedTime property.


References

Thanks for reading. I hope you liked this.

Add Styles and Formatting to Your console.log Messages in JavaScript

Learn how to add CSS and formatting log messages in JavaScript.

Image by Joanna Kosinska

We all know the console.log function will log a simple message to the console. But console.log can also format the text and make the message stand out from other messages. This gives us the ability to find our important messages in the console.

Format specifier

Format specifiers define the type of data to be printed on standard output. We can use Format specifiers to tell the log function how the data should be printed.

%s → Formats the value as a string.

var a = 10;
console.log("%s treated as string", a);

List of format specifier we have:

%s → Formats the value as a string
%i or %d → Formats the value as an integer
%f → Formats the value as a floating point value
%o → Formats the value as an expandable DOM element. As seen in the Elements panel
%O → Formats the value as an expandable JavaScript object
%c → Applies CSS style rules to the output string as specified by the second parameter

%c → A format specifier that will apply CSS style rules to the output string. We pass the CSS as a string as the second parameter.

console.log("%cJavascript Jeep 🚙in Blue", "color:blue; font-size:50px");


Having multiple styles

We can also apply multiple styles to the message. Use %c before each part of the string and pass a separate style for each %c:

console.log("%cJavascript Jeep 🚙in Blue %cJavascript Jeep 🚙in red", "color:blue; font-size:50px", "color:red; font-size:50px" );


We can also pass the style as a string:

var style = "color: red; background: #eee; font-size: 50 ";
console.log("%c Javascript Jeep 🚙in Blue",  style);

We can define them in an array and join them into a string for convenience:

var styles = [ "color: red", "background: #eee", "font-size: 50"];
var styleStr = styles.join('; ');

This will produce the same result as above.

Adding an image to the console

We can add an image to the console by using background-image property from CSS:

var styleArray= [
'background-image: url("https://media.giphy.com/media/2dQ3FMaMFccpi/giphy.gif")',
'background-size: cover',
'color: #fff',
'padding: 10px 20px',
'line-height: 35px',
'width : 70px',
'height : 70px',
'border : 5px solid black'
];
console.log('%cI love you!', styleArray.join(';'));


Surprise your customers

var style = 'color: tomato; background:#eee; -webkit-text-stroke: 1px black; font-size:30px;';
console.log('%cHi, We are Happy 😆 to have you as our customer', style );


Creating Facebook stop 🛑 message in the console

If you have opened the console on facebook.com, you have undoubtedly been greet by the “stop” message. Instead of “stop” let’s print a welcome message:

const style = 'color:red; font-size:30px; font-weight: bold; -webkit-text-stroke: 1px black;'
console.log("%c Javascript Jeep Welcomes you", style);


Tips :

1. If you want to prevent console.log by the users

console.log = function() {
console.error(" Logging by user is disabled ");
}

The above code will restrict users from logging messages because the function has been replaced.

2. Logging after a delay

Log a message after a given interval.

https://gist.github.com/Jagathishrex/05ea52eabfe524fa22a20aa55bfa4d6f#file-delaylog-jsView at Medium.com
View at Medium.com

Thanks for Reading 📖 . I hope you like this. If you found any typos or mistakes send me a private note 📝 thanks 🙏 😊 .

Follow me JavaScript Jeep🚙💨 .

Buy me a coffee.

Buy me a coffee.

Dot vs Bracket Notation in Accessing JavaScript Object.

Learn when to use dot and bracket notation in JavaScript.

Dot vs Bracket notation in JavaScript

We can access the property of an object by

  • Dot notation
  • Bracket notation

Dot Notation

This is the most popular and most used way of accessing the property of an object. This makes code more readable. Dot notation is used most frequently.

Syntax: obj.property_name

var user = {name : "Mark"};
user.name ; // "Mark"

When not to use dot notation

Consider that we are having a property name as 123

var obj = {
'123' : 123
};

In the above case if we cannot access using

obj.123; 

So, If the property name is not a valid identifier , then we cannot access its value using . notation.

What is an Identifier?

An identifier is a sequence of characters in the code that identifies a variable, function, or property. Generally name of function or variable or property name of Object

What is a valid Identifier?

  • In JavaScript, identifiers are case-sensitive and
  • can contain Unicode letters, $, _, and digits (0-9),
  • but may not start with a digit.

In this case, we can use bracket notation

var obj = {
'123' : 123
};
obj['123']; // 123

Note

In JavaScript $ , and _ are valid identifiers. so we can access those properties using . notation.

var obj = {
$ : 10,
_ : 20
}
obj.$; // 10
obj._; // 20

Bracket Notation

The bracket notation is used when the property name is an invalid identifier(starts with a number, contains symbols).

var obj = {
test-123 : "test"
}
// in this case we cannot use dot notation
obj['test-123']; // "test"

If the property name is number then we don’t need to wrap the property name inside single /double quotes in object creation. But in bracket notation, if the property name is whole number , then we don’t need to wrap the name inside single /double quotes . But if the property name is double , then need to warp the property name inside single /double quotes .

Example 1: whole number

var obj = {
123456 : 10
}
obj[123456];

Example 2: Double

var obj = {
123.456 : 10
}
obj[123.456]; // undefined
obj['123.456']; // 10

Example 3: Using an invalid number

var obj = {
123.123.123 : 10 // throws invalid number error
}
For this case use single/double quotes
var obj = {
'123.123.123' : 10
}

Example 4: Using special symbols

var obj = {
'123-test' : "test"
}
obj[123-test]; // error(test is not defined)
obj['123-test']; // "test"

Using variable as the property name

Example 1:

var test = "test";
var obj = {
test : "Test success"
}
obj[test] // "Test success"

Example 2 :

var obj = {
name : "Mark"
age : 20
}
var name = "age";
obj["name"]; // Mark
obj[name]; // 20

Example 3: Real-world Example of using bracket notation

function getFood(user) {
let foods ={
veg : ["🍏", "🌽", "🍕", "🍅"],
      'non-veg': ["🐓", "🐣", "🥩", "🍖"] 
}
   let {foodPreference} = user;
   return foods[foodPreference];
}
let user = {name: "Mark", foodPreference : "veg"};
getFood(user); // ["🍏", "🌽", "🍕", "🍅"]

We can also use object as the property name, but that will be converted into [object Object]

var a = {};
var b = {};
var c = {};
c[a] = 10;
c ; {[object Object]: 10}
c[b] = 20; // this will replace old [object Object]
c; {[object Object]: 20}

We can also have empty string as property name

var obj= {};
var emptyString = "";
obj[emptyString] = "10";
obj[emptyString]; // 10

References :

Sponsor me a coffee ☕️ .

Different Ways to Duplicate Objects in JavaScript

It turns out there are a lot of different ways to duplicate objects

Photo by James Orr on Unsplash

In JavaScript, a variable can store two types of data:

  • Primitive
  • Reference

When we copy primitive values, only the value will be copied.

var a = 10;
var b = a;
console.log(a, b); // 10, 10
b = 20;
console.log(a, b); // 10, 20

When we copy primitive values, only values are copied.

But when we copy reference values, the memory address of the object is shared.

var a = { one : 1};
var b = a;
a.one = 2;
console.log(b.one); // 2
b.one = 3;
console.log(a.one); //3

When we assign the object to other variables, only the memory address is copied.

Once we change the property of a or b, we are changing the value at the address of the object.

When the property of the object is changed, the changes are reflected in all variables pointing to the object.

If we want to copy a primitive value, we can use assignment operator (=), but for objects we cannot use the assignment operator.

When copying objects, there are two types:

  • Shallow copy
  • Deep copy

When we shallow-copy a source object to a target object, if the property value of the source object is primitive, then the value is copied to the target object. But if the property value of the source object is reference, then the reference is shared between the source and target objects.

In a deep copy, all the properties (including reference) of the source object are copied as values to the target object. There is no sharing of the reference between the source and target objects.

Difference between shallow and deep copy

Shallow Copy

Using the spread operator

https://gist.github.com/Jagathishrex/8cd8af78bb7d4c9c7cfbba8507be0a6a#file-copyobjbyspread-js

The spread operator will copy all the enumerable properties of the obj to the copiedObj.

Using loop

https://gist.github.com/Jagathishrex/ba23b837ff09ef78f3be40ed9b443609#file-copyobjbyfor-js

This above code will loop through all the properties of the object and copy the value to the target object.

Object.assign

var source = {one : 1, nested: {two : 2}};
var target = Object.assign({}, source);

Deep Copy

Using JSON.stringify and JSON.parse

https://gist.github.com/Jagathishrex/63fef951126bd3da53496abf4a822009#file-jsoncopy-js

JSON.stringify and JSON.parse only work with number, string, and object literals and don’t support function or symbol properties.

Also, if the value of the property in the object is Date, then using JSON.stringify will convert the Date object to a string.

var a = { d : new Date() };
var b = JSON.parse(JSON.stringify(a));
b ; // {d: "2019-11-26T00:28:18.775Z"}

What is a circular object?

var a = {}; 
a.a = a;

Circular objects are objects that have a property value referencing to themselves.

When we perform a deep copy of a circular object, it goes on endlessly. JSON.stringify/parse will throw an exception error when we perform a deep copy on a circular object.

We can use Object.assign to copy a circular object — but avoid creating a circular object in the first place.


Implementing Custom Clone

In the deepClone method, we will loop through all the properties of the object. If the value of the object is primitive, just copy it. If the value is reference, call the deepclone method.

https://gist.github.com/Jagathishrex/0884e892f4321ffa056620cadc83dfdf#file-deepcopy-js


All the above methods only focus on objects, not arrays. They may not work for arrays.

Thanks for reading, and I hope you liked this piece.

Sponsor me a coffee ☕️ .

Understand the Three Different Value Equality Comparison Algorithm in JavaScript.

Learn about different types of equality checking in JavaScript.

Image from Coffee Geek.

In JavaScript, there are three different value-comparison operations

  • Abstract Equality Comparison(loose equality || == || double equals).
  • Strict Equality(triple equals || === ).
  • Same Value Equality ( Object.is() ). Introduced in ES2015 .

Abstract Equality Comparison (==).

a == b;

Double Equals compares whether two values(a and b) are same .

During this comparison the type of the a and b is converted to same type.

This comparison doesn’t check for the type of the a and b .

If the a and b are different types , then we can use == comparison.

After converting , it will check if both the values are same

Example 1:

// here there is no type conversion
var a = 10;
var b = 10;
var c = 20;
a == b; // true
b == c; // false

Example 2 :

// with type conversion
var a = 10;
var b = '10';
var c = new String(10);
a == b; // true

In the above code a == b is evaluated to true , because the b is converted to number , and the comparison happens .

How type of the variables are converted is ,

Basic comparisons

Number and String .

a → number , b → string
b converted to number .
Example 
'1' == 1;  will be converted to  
Number(1) == 1 → 1 == 1 → true
--------

Examples

'' == 0;  // true because Number('') → 0
10' == 10.1; //false

A boolean and a non-boolean

a → boolean , b → non-boolean
a is converted to number, then comparison will be performed.
Example
'1' == true ;
this will changed as 
'1' == Number(true) → '1' == 1 
Now string and number comparison 
'1' == 1 → will be converted to 1 == 1 → true.

Examples

0 == false  // true
[] == false ; // true because Number([]) → 0 & Number(false) → 0
'' == false; // true because Number('') → 0 & Number(false) → 0
1 == true; // true

A string or a number to an object

a → string|number , b → object
b is converted to respective(a) primitive type and comparison will be performed
var a = '1';
var b = Number(1);
a == b;
Here , a → String & b → Number Object 
b is converted to String, 
'1' == 1 → '1' == String(1) → '1' == '1' → true

Examples

1 == String(1); // true
10 == Number(10); //true

Comparing NaN

NaN is not equivalent to anything – including NaN .

NaN == NaN; // false
NaN == 0; // false

Comparison with Infinity

Infinity|| -Infinity is truthy . But, when compared to true or false , it always return false .

Infinity == Infinity; // true
Infinity == - Infinity; // false
if(-Infinity)
console.log("will be printed")
if(Infinity)
console.log("will be printed");
Comparing with true and false.
Infinity == true ; // false.
Infinity == true → Number(Infinity) == Number(true) → Infinity == 1→ false.
Infinity == false; // false.

Comparing empty Array

if([])
console.log("This is printed");

An empty Array is true , because an Array is Object , an object without any properties is always true.

But

[] === true

When we compare empty array ([]) with boolean , When comparing boolean with non-boolean, both the values are converted to number and then comparison will takes place,

Number([]) == Number(true)
0 == 1; // false

Comparing Object

JavaScript, has two different approaches for testing equality. Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and objects are compared by their reference. The reference are considered to be same if both the object points to same memory location.It is same for both triple equals and double equals

var a = {};
var b = {};
a == b; // false
a === b; // false

Concluding == comparison

// all true
false == 0;
0 == '';
null == undefined;
[] == false;
[0] == false;
[1] == true;
// all false
false == null;
NaN == NaN;
Infinity == true;
[] == true;
[0] == true;
[1] == false;

Strict Equality

a === b

Strict equality compares two values and types are equal .

If the type of two variables a and b is different , then a and b are not equal.

Example 1:

var a =10; 
var b =10;
a ===b; // true

Example 2 :

10 == '10'; // true
10 === '10'; //false

Example 3:

10 === Number('10'); // true 

Example 4 :

10 === new Number(10);//false 
because 
- 10 in Left side is Primitive
- 10 in Right side is Object
Both types are different 

Example 5:

var a = {};
var b = {};
a === b; // false , different reference
a === a; // true

In Strict Equality

* undefined === undefined; // true
* null === null; // true
* +0 === -0; // true
* NaN === NaN; // false
* Infinity === Infinity // fale
* Infinity === -Infinity // false
* null === undefined; // false

Object.is()

The Object.is() method determines whether two values are same.

In object is similar to triple equals comparison, except
Objects.is(+0, -0) // false
Object.is(NaN, NaN) // true
Object.is(NaN, 0/0);// true; Because 0/0 is NaN

Conclusion

Abstract Equality Algorithm

Strict Equality Comparison

Same value comparison

https://dorey.github.io/JavaScript-Equality-Table/

Thanks for Reading 📖 . Hope you like this. If you found any typo or mistake send me a private note 📝 thanks 🙏 😊 .

Follow me JavaScript Jeep🚙💨 .

Please make a donation here. 98% of your donation is donated to someone needs food 🥘. Thanks in advance.

Design a site like this with WordPress.com
Get started