top of page

10 JavaScript Tricks You Should Know to Save Time and Effort



JavaScript is a full-fledged dynamic programming language that can add interactivity to a website. It is beginner-friendly and provides many tools that can save a lot of effort and time if used correctly. These are the 10 such tricks you should know while working with JavaScript. Read on for a list of time-saving tips.


1. Console Log like a Pro

When you debug your code, it’s common to log a value to check the assigned result. While you can always do it like below,

console.log('name', name)
console.log('someOtherValue', someOtherValue)
console.log('etc', etc)

you can use Object destructuring to make your life easier.

console.log({name, someOtherValue, etc})

2. Object Short-hand properties

Suppose you have initialized some values in variables x and y, and you want to create an object with the properties x and y. Using basic literal syntax, you’ll end up repeating each identifier

let x = 1, y = 2
const obj = {
   x: x,
   y: y
}

In ES6 and later, you can drop the colon and one copy of the identifier and end up with much simpler code:

let x = 1, y = 2
const obj = {
   x,
   y
}
obj.x + obj.y => 3

3. Logical Assignment Operators

You might be aware of the mathematical assignment operators. It lets you perform a mathematical operation on a variable with the value you are assigning.

let count = 1
count += 2 // 3
count -= 1 // 2

Suppose you’d want to assign a value to the variable if the current value of the variable is truthy.

let obj = {}
obj['name'] && (obj['name'] = 'Joe') // {}

You can replace the above line with the below line. Note that it will not create a property if it doesn’t exist.

obj['name'] &&= 'Joe' // {}
obj['name'] = 'Joe' // assign property 'name' to obj {name: 'Joe'}
obj['name'] &&= 'Colin' // { name: 'Colin' }

You can read more about the logical assignment operators here.

4. Spread operator

In ES2018 and later, you can copy the properties of an existing object into a new object using the “spread operator.” ... inside an object literal:

let x = { p: 1}
let y = { q: 2, r: 3}
let z  = {...x, ...y} // { p: 1, q: 2, r: 3}

In the above code, the properties of x and y are spread out into z. Three dots are used for other purposes in other JavaScript contexts, but object literals are the only context where the three dots cause this kind of interpolation of one object into another one.

Also, note that if there are duplicate properties in the objects being spread out, the value of that property will be the one that comes last.

let user = { name: "Joe", city: "New York", age: "25" }
let updatedUser = { ...user, age: "26"} 
// { name: "Joe", city: "New York", age: "26" }

You can also use this property for an array.

let arr1 = [2, 3, 4]
let arr2 = [5, ...arr1] // [5, 2, 3, 4]

5. Self-Invoking functions

In JavaScript, function expressions can be made self-invoking.

(function() {
 // your code goes here
})();

A self-invoking function is an anonymous function that is ‘invoked’ directly right after it has been defined. These functions are executed automatically if the expression is followed by (). Note that the function declaration can not be self-invoked.

let sum = (function(a,b){
    var result = a+b;
    return result;
})(10,20)
// sum => 30

The primary benefit of self-invoking functions is variable scoping. The variables defined inside these functions are not available outside the function scope. This prevents the global namespace from becoming littered with variables and functions that may not be needed further.

6. Format numbers to a currency

JavaScript provides a way that enables language-sensitive number formatting.

const number = 123456.789
let dollars = new Intl.NumberFormat('en-US', {
      style: 'currency',      
      currency: 'USD',    
}).format(number)
// $123,456.79

If you use the API without specifying a locale, a formatted string in the default locale and default options is returned.

const number = 1234
let dollars = new Intl.NumberFormat().format(number)
// will return number formatted with default locale

7. use === instead of ==

Even though both == and === accomplish similar things, the === is a stricter check for equality. The == or != performs an automatic type conversion if needed. However, whenever you’re using triple equals, it checks for the type and the values of the operands (strict equality) and the reference value (reference equality).

5 == '5' // true, type conversion from int to String
5 === '5' //falseconst user = { name: "Joe" }
const someNewUser = user
user === someNewUser // true, reference check

The triple equals compare the value and the type, which could be considered faster than ==.

8. Swap ’em variables

We all have been there; we have used a temporary variable while swapping variables. But there is a better and an intuitive way to do it in JavaScript… using destructuring.

let x = 5, y = 4;
[ y, x ] = [ x, y ]
// y = 5, x = 4

9. Empty or resize an array using length

In JavaScript, you can override the length property of an array to resize or emptying it.

const array = [1, 2, 3, 4]
array.length = 0 // []array.length = 2 // [1, 2]

10. The ternary operator (?)

Now, this one most of you may be aware of. The ternary operator can be used to replace the if…else statement. For example,

let x = 10;
if( x % 2 === 0 )
   console.log('Number is even.')
else
   console.log('Number is odd')

can be replaced as

let x = 10;
x % 2 === 0 ? console.log('Number is even') : console.log('Number is odd.')

I hope you learned some new things about JavaScript after reading this post.



Source: Medium; Aishwarya Sharma


The Tech Platform

0 comments

Comments


bottom of page