Javascript tips

Ternary Operator

The ternary operator can be used as a substitute for very simple if/else statements. Here is the syntax:

(condition) ? (return value if truthy) : (return value if falsy)

The ternary operation requires 3 operands. The first is a condition value or expression. The second is a value or expression that is evaluated and returned if the condition is truthy. The third is a value or expression that is evaluated and returned if the condition is falsy. Here is a quick example showing how to use the ternary operation as a shortcut for simple if/else statements. This feels good already, but it gets more interesting knowing that ternary operations can be nested. The ternary operator has a right-to-left associativity. Hence, the following expression:

a ? b : c ? d : e ? f : g

is evaluated as:

(a ? b : (c ? d : (e ? f : g)))

Nested ternary operations can be used as alternatives to multiple if/else statements. Here is a simple example: Notice how concise the ternary operation is in comparison to using multiple if/else statements. Note that the ternary operation returns a value since it is a JavaScript expression. Hence, the result of a ternary operation can be stored in a variable or used anywhere JavaScript expects a value. That is the reason why the value of the ternary operation could be returned from the boundedValue() function.

Short-Circuiting

When working with the (|| and &&) logical operators, you may have noticed an interesting behavior called short-circuiting. Here is how it works: The logical && operator returns the first operand if it is falsy, otherwise it returns the second operand. The logical && short-circuiting is commonly used as a replacement for very simple if statements as shown in the following snippet: Note that using short-circuiting actually returns a value since it is a JavaScript expression. Hence, the result of a short-circuiting operation can be stored in a variable or used anywhere JavaScript expects a value.

var personProfile = person && fetchProfile(person);

However, using if statement does not return a value because it is a JavaScript statement. The logical || operator returns the first operand if it is truthy, otherwise it returns the second operand. The logical || short-circuiting is commonly used when assigning fallback values to local variables as shown in the following snippet: In the following snippet, short-circuiting is used to create two functions that always return a boolean value. If the first argument is a boolean value, it is returned, otherwise the desired fallback boolean value is returned.

Type Conversion: Number and String

One of the most common things you find yourself doing in JavaScript is using arithmetic operators: +, -, *, /. These operators expect operands that are numbers. So when any of the operands is not a number, JavaScript implicitly coerces it into a number. But there are times when you may not get the result you may be expecting, especially when you are using the + operator. This is majorly because the + operator is also used for string concatenation. See the following snippet: As you can see, implicit type coercion may not always give you the result you are expecting. This is because of how JavaScript handles type conversion especially for objects. The difference is due to the order in which JavaScript calls the toString() and valueOf() methods on the object for object-to-primitive conversion. Now here is the trick. The + operator when used as a unary operator always converts its operand to a number. Hence, the following: Using the unary + operator on a value is functionally equivalent to casting the value using the Number() function.

+new Date === Number(new Date); // true

The + operator can also be used to convert values to string. Concatenate an empty string('') to any value using the + operator to convert the value to a string. Using the + operator to convert values to string is functionally equivalent to casting values to string using the String() function.

([100, 50] + '') === String([100, 50]); // true

Values: truthy and falsy

Most new JavaScript developers may be aware of the built-in data types in JavaScript. However, not so many may know about JavaScript’s classification of truthy and falsy values. Anytime JavaScript expects a boolean value, a truthy value will behave like true, whereas a falsy value works like false. These are the falsy values:

  • 0
  • -0
  • null
  • undefined
  • ''
  • NaN
  • false As you can see, even an empty string is considered a falsy value. All other values besides the above mentioned are truthy values. The ! operator can be used to convert any value to a boolean. When using the ! operator with values, truthy values evaluate to false, while falsy values evaluate to true. You can use the double (!!) operator to get the corresponding boolean for any value. Let’s say a variable person can either contain an object or null. You can verify that the person variable is not null, by using the following condition:
if (person !== null) { ... }

Considering that null is falsy while every other object is truthy, you can use this (less strict condition):

if (person) { ... }

Double NOT bitwise operator (~~)

The double NOT bitwise operator is a substitute for Math.floor() method.

const floor = Math.floor(6.8); // 6

to ⬇

const floor = ~~6.8; // 6


The double NOT bitwise operator approach only works for 32-bit integers. So for any number higher than that, it is recommended to use Math.floor()

Multiple condition checking

For multiple value matching, we can put all values in an array and use indexOf() or includes() method.

if (value === 1 || value === 'one' || value === 2 || value === 'two') { 

}

to ⬇

An Essential, Time-Saving Method to Dealing With Empty and Non-Empty Values

If you have a mixture array with empty and non-empty values, you need to get rid of those empty values. Here’s a time-saving way to do that: {% code-block language="js" %}   const arr = [0,1,2,null,undefined,"",false];   const nonEmptyValues = arr.filter(Boolean);   console.log("nonEmptyValues: ", nonEmptyValues); //[1, 2]{% code-block-end %} Not only are your empty values eliminated this way, but you also removed the zeros and false values. This is something that you might want to avoid in a few cases. Now, we will use the hasEmptyVals command as shown below. Note that if your array consists of some empty values, instead of a “complete” filter, “some is used”. So the output will let you know whether your array has empty values or not, which is something useful to check. {% code-block language="js" %}   const arr = [0,1,2,null,undefined,"",false];   const hasEmptyValues = arr.some(Boolean);   console.log("hasEmptyValues: ", hasEmptyValues); // true{% code-block-end %} You can also check if each value is empty by replacing “some” with “every”. {% code-block language="js" %}   const arr = [0,1,2,null,undefined,"",false];   const hasEmptyEveryValues = arr.every(Boolean);   console.log("hasEmptyEveryValues: ", hasEmptyEveryValues); // false{% code-block-end %}

Destructuring

The technique of breaking down the array elements and object properties as variables called, destructuring. Let us see it with few examples,

Swap variables

This must be super easy now using the concept of destructuring we learned just now.

let fire = '🔥';
let fruit = '🍉';

[fruit, fire] = [fire, fruit];
console.log(fire, fruit);

undefined vs null

undefined is where a value is not defined for a variable but, the variable has been declared. null itself is an empty and non-existent value which must be assigned to a variable explicitly. undefined and null are not strictly equal,

undefined === null // false

Read more about this topic from here.