Javascript tricks You've Never Heard About : Part 1

Blackkspydo

0 views 2 reactions 2022-10-12

Cover Image

JavaScript is a feature-rich language. It has a lot of features that are not well known. In this article, I will show you JavaScript tricks that you’ve never heard about. Let’s Explore some of them:

1. Destructuring

With the help of destructuring, you can do awesome things like:

1.1. Swap variables

If you ever need to swap two variables. You can do it with the help of destructuring, provided that the variables are declared with let, or var but not const. Also, you should be using ES6 or above.

let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1

1.2. Accessing nested objects

Previously, if you wanted to access a nested object, you would have to do something like this:

const obj = {
  a: {
    b: {
      c: 1
    }
  }
};
const value = obj.a.b.c;
console.log(value); // 1

But now, with the help of destructuring, you can do it in a much simpler way:

const obj = {
  a: {
    b: {
      c: 1
    }
  }
};
const { a: { b: { c } } } = obj;
console.log(c); // 1

const { a: { b: { c:value } } } = obj;
// and yes, you can rename the variable
console.log(value); // 1

1.3. Pass an object as function parameters

If you want to pass different parameters to a function, why not pass an object instead? It will make your code more readable. and you can use destructuring to access the properties of the object.

function foo({ a, b, c }) {
  console.log(a, b, c);
}
foo({ a: 1, b: 2, c: 3 }); // 1 2 3

2. Spread & Rest Operators

2.1. Spread Operator

The spread operator ... is used to spread an array into its elements. It can also be used to spread an object into key-value pairs.

const arr = [1, 2, 3];
console.log(...arr); // 1 2 3

const obj = { a: 1, b: 2, c: 3 };
console.log(...obj); // a b c

2.1.1. Spread in function calls

You can use the spread operator to pass an array as arguments to a function.

function foo(a, b, c) {
  console.log(a, b, c);
}
const arr = [1, 2, 3];
foo(...arr); // 1 2 3

2.1.2. Spread in array literals

You can use the spread operator to create a new array from an existing array.

const arr = [1, 2, 3];
const arr2 = [...arr, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]

2.1.3. Spread in object literals

You can use the spread operator to create a new object from an existing object.

const obj = { a: 1, b: 2, c: 3 };
const obj2 = { ...obj, d: 4, e: 5, f: 6 };
console.log(obj2); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }

2.2. Rest Operator

The rest operator ... is used to collect multiple elements and put them into an array. It can also be used to collect multiple key-value pairs and put them into an object.

const arr = [1, 2, 3, 4, 5];
const [a, b, ...rest] = arr;
console.log(a, b, rest); // 1 2 [3, 4, 5]

const obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
const { a, b, ...rest } = obj;
console.log(a, b, rest); // 1 2 { c: 3, d: 4, e: 5 }

3. Ternary Operator

The ternary operator is the only operator that takes three operands. It is often used as a shortcut for the if statement.

const a = 1;
const b = 2;
const c = a > b ? a : b;
console.log(c); // 2

4. Template Literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

const name = "John";
const age = 20;
const str = `Hello, my name is ${name} 
I'm ${age} years old.`;
console.log(str); 
// Hello, my name is John 
// I'm 20 years old.

5. Short-circuiting

Short-circuiting is a way to make your code more readable. It is a way to use logical operators in a way that they return the value of one of the specified operands, instead of always returning true or false.

5.1. Logical AND (&&)

The logical AND operator (&&) returns the value of the first operand if it can be converted to false; otherwise, it returns the value of the second operand.

const a = 1;
const b = 2;
const c = a && b;
console.log(c); // 2

5.2. Logical OR (||)

The logical OR operator (||) returns the value of the first operand if it can be converted to true; otherwise, it returns the value of the second operand.

const a = 1;
const b = 2;
const c = a || b;
console.log(c); // 1

5.3. Nullish Coalescing Operator (??)

The nullish coalescing operator (??) returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

The main difference between || and ?? is that || returns the right-hand side operand if the left-hand side operand is false, whereas ?? returns the right-hand side operand if the left-hand side operand is null or undefined.

const a = 1;
const b = 2;
const c = a ?? b;
console.log(c); // 1

6. Immediately Invoked Function Expression (IIFE)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. One of the most common uses of an IIFE is to execute a function without polluting the global scope.

(function () {
  console.log("Hello, World!");
})();
// Hello, World!

7. Comma Operator

The comma operator (,) is used to evaluate each of its operands (from left to right) and return the value of the last operand.

const a = 1;
const b = 2;
const c = 3;
const d = a, c = a + b + c, c;
console.log(d); // 6

8. Optional Chaining

Previously, if you wanted to access a property of an object that might be undefined or null, you would have to check if the object exists first.

For example:

const obj = { a: { b: 1 } };

if (obj && obj.a && obj.a.b) {
  console.log(obj.a.b); // 1
}

With the optional chaining operator (?.), you can access properties of nested objects without having to check if the parent objects exist. If the reference is undefined or null, the expression short-circuits with a return value of undefined.

const obj = {
  a: {
    b: {
      c: 1,
    },
  },
};
const c = obj?.a?.b?.c;
console.log(c); // 1

9. Double Bang (!!) Operator

The double bang operator (!!) is used to convert any value to a boolean. It is often used to convert a value to a boolean in a shorter way.

const a = 1;
const b = !!a;
console.log(b); // true

10. Double Tilde (~~) Operator

The double tilde operator (~~) is used to convert any value to an integer. It is often used to convert a value to an integer in a shorter way.

const a = 1.5;
const b = ~~a;
console.log(b); // 1

Thank you so much for taking the time to read the blog post! I appreciate it, and I hope you found it helpful/informative. If you have any questions or comments, feel free to leave them below, and I’ll be happy to answer them. Again, thank you for reading, and have a great day!

Reactions: ❤️ 1 🚀 1
Leave a reaction if you liked this post! 🧡

Subscribe to the newsletter

Get emails from me about Lorem ipsum dolor sit, amet consectetur adipisicing elit. Libero, ducimus..

3 subscribers including my Mom – 23 issues