Daily used 10 confusing topic of JavaScript

Sajib
5 min readAug 18, 2020
JavaScript Confused ?

1. == vs ===, implicit conversion

Both represent logical equality but here is the mighty difference-

  • == checks only values , it tries to compare by implicit type conversion.Number 1 and string “1” is same here
  • === checks both values and types. Number 1 and string “1” can’t be same here

Example :

/* 👎 double equal == */
const first = 1;
const second = "1";
if (first == second) {
console.log(true, `${first} == ${second}`);
} else {
console.log(false, `${first} != ${second}`);
}
// Output : true 1 == 1

/* 👍triple equal === */
const first = 1;
const second = "1";
if (first === second) {
console.log(true, `${first} == ${second}`);
} else {
console.log(false, `${first} != ${second}`);
}
// Output : false 1 != 1

2. map(), filter(), find()

One of the reasons why ES6 is so useful, it makes your life a lot easy.It basically used for a modern for loop.

  • map() - runs through all the elements, returns a new array
  • filter() - runs through all the elements, returns only those elements who fulfill the condition .
  • find() - runs through all the elements, returns only first matching single element who fulfills the condition.

Example :

/* Map */
const numbers = [2, 3, 4, 5, 6, 8];
const squaredNum = numbers.map((num) => num * num);
console.log(squaredNum);
// Output : [ 4, 9, 16, 25, 36, 64 ]

/* Filter */
const shapes = ["🟨", "🟩", "🔵", "🔴", "🟨", "🟩", "🔵", "🔴"];
const circle = shapes.filter((item) => item === "🔴");
const square = shapes.filter((item) => item === "🟩");
console.log(circle);
console.log(square);
// Output : ["🔴", "🔴"]
// Output : ["🟩", "🟩"]

/* Find */
const hearts = ["💙", "💚", "🧡", "💚", "💜", "💛", "🧡"];
const greenH = hearts.find((item) => item === "💚");
console.log(greenH);
// Output : 💚

3. slice(), splice(), join()

  • slice() - takes starting index and before-end index, returns new array.The main array is unchanged.
  • splice() - takes starting index, item number (how many to remove), item number (some number that replace removed number , optional).Effects original array.
  • join() - It takes an array and join the items with argument and returns a string

Example :

/* slice(), splice(), join() */
const sports = ["⚽️", "🏀", "🏈", "🏓", "🏸", "🏏", "🏐", "🎱"];
const part = sports.slice(3, 6);
console.log(part);
// Output: ["🏓", "🏸", "🏏"]

const removed = sports.splice(2, 6, "🎭", "🤹");
console.log(removed);
console.log(sports);
/*
Output:
["🏈", "🏓", "🏸", "🏏", "🏐", "🎱"]
["⚽️", "🏀","🎭", "🤹"]
*/

const together = sports.join(",");
console.log(together);
// Output: "⚽️,🏀"

4. Uses of API by fetch()

Earlier we had to use complex XMLHttpRequest API, now modern Fetch API does the same, and its easier to understand.

fetch(api_link)
.then((res) => res.json())
.then((data) => {
console.log(data) ;
}

5. Class, Constructor, Object

Classes are a template for creating objects. They encapsulate data with code to work on that data

Use the keyword class to create a class, and always add the constructor() method. The constructor method is called each time the class object is initialized.

this points a object. So in a constructor you must use “this” so that while initializing a object the object can set constructorised data in him.Otherwise error

/* inheritence, extends, super */
class Parent {
constructor() {
this.fatherName = "Christopher Nolan";
this.motherName = "Emma Thomas";
}
}
class Chlid extends Parent {
constructor(name, age) {
super();
this.name = name;
this.age = age;
}
getFamily() {
return `Name: ${this.name}, Father: ${this.fatherName}, Mother: ${this.motherName}`;
}
}

const kid1 = new Chlid("Flora Nolan", 18);
const kid2 = new Chlid("Magnus Nolan", 12);
console.log(kid1.name); // Output : Flora Nolan
console.log(kid2.age); // Output : 12
console.log(kid1.getFamily()); // Output: Name: Flora Nolan, Father: Christopher Nolan, Mother: Emma Thomas

6. Truthy/Falsy value

Any number except 0 is true. If the value of any variable is 0 will return false. Similarly, we get a falsy result when undefined, null, NaN, false is the return value.

Example :

/* Truthy/Falsy value */
let age = 0;
if (age) {
console.log(true);
} else {
console.log(false);
}
// Output : false

let name; // undefined, falsy
// name = "Smith"; // truthy
// name = " "; //truthy
// name = []; //truthy
// name = {}; //truthy
console.log(name);

if (name) {
console.log(true);
} else {
console.log(false);
}
// Output : false

7. Null vs Undefined

There are several ways for getting Undefined, for example.

  1. Unassigned variable
  2. No return value/ nothing after return
  3. Passing incorrect parameter
  4. Accessing non-existing index/property
  5. Manually assign undefined

Only if we set “null” to a variable manually then it will be null.

Example :

/* unassigned variable */
let name;
console.log(name);
// Output: undefined

/* No return/ nothing after return */
function add(num1, num2) {
result = num1 + num2;
return;
}
result = add(10, 30);
console.log(result);
// Oputput: undefined

/* passing incorrect parameter */
function add(num1, num2) {
console.log(num1, num2);
}
result = add();
// Oputput: undefined

/* passing incorrect parameter */
function add(num1, num2) {
console.log(num1 + num2);
}
result = add();
// Oputput: NaN;

/* Accessing non-existing index/property */
const userData = {
name: "Jhon Doe",
phone: "123263",
};
console.log(userData.id);
// Oputput: undefined

userData.address = undefined;
console.log(userData.address);
// Oputput: undefined

8. array/object destructuring, spread operator

Magical the 3 dots (...) will spread out what value you want

Example :

/* 3 dots: spread */
const red = ["🧡"];
const green = ["💚"];
const blue = ["💙"];
const rgbHeart = [...red, ...green, ...blue];
console.log(rgbHeart);
// Output : ["🧡", "💚", "💙"]

/* destructure: array */
const hearts = ["🧡", "💚", "💙", "💛", "💜", "🖤", "🤍"];
const [r, g, b] = [...hearts];
console.log(r, g, b);
// Output : 🧡 💚 💙

/* destructure: object */
const userInfo = {
id: 101,
username: "jdoe",
name: "Jhon Paul Doe",
age: 33,
phone: "0123456789",
};
const { name, phone } = { ...userInfo };
console.log(name, phone);
// Output: Jhon Paul Doe 0123456789

/* Finding min/max */
const numArr = [200, 300, 400, 500, 600];
const min = Math.min(...numArr);
const max = Math.max(...numArr);
console.log(min, max);
// Output: 200 600

9. Default parameter

Default parameter is indeed when we may forget to assign parameter value while calling a function

Example :

/* Default Parameter */
function addFifty(num1, num2 = 50) {
return num1 + num2;
}
const result = addFifty(10, 20);
const result2 = addFifty(20);
console.log(result, result2);
// Output : 30 70

10. JSON vs OBJECT

Server provides us only json data and accept only json data. So we need to make json data for sending data to server and parse data as object for using it in our work .

to make json from object use JSON.stringify()

to make object from json use JSON.parse()

Example :

/* Data as JSON */
const data = {`
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz"
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org"
}
`;
const obj = JSON.parse(data);/* Output:
{
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: 'Sincere@april.biz'
phone: '1-770-736-8031 x56442',
website: 'hildegard.org'
}
*/

a

const json = JSON.stringify(obj);
/* Output:
{"id":1,"name":"Leanne Graham","username":"Bret","email":"Sincere@april.biz", "website": "hildegard.org"}
*/

--

--