7 Pro Tips JavaScript One-Liners for You to Know and Use
Tags: javascript, beginners, frontend, codenewbie
Published: 2023-09-20 12:02:14

Hey guys, how are you?!

Let's see some JavaScript useful tips with a maximum of 2 lines of code that can help us in our daily lives?!

So let's go!!!

___

##💡 Conditional (ternary) Operator
If ternary is a very simple way to work with "if" validations:

**The code:**

```javascript
function validateBetterCommunity(community) {
  // Structure to Verify
  return community === 'devto' ? 'You are right!' : 'You are wrong :(';
}

console.log(validateBetterCommunity('devto'));
// Expected output: "You're right!"

console.log(validateBetterCommunity('another one'));
// Expected output: "You're wrong :("
```
___
##💡 Generate Random String Id

Generate a random string id easy:

```javascript
// Structure to Generate
const randomIdentifier = Math.random().toString(30).slice(2.5);

console.log(randomIdentifier);
// Output: 'd5ptscfrln7';
```
___

##💡 Check if Element has Focus

Checks if any `element` has focus with the **read-only** `activeElement` property:

```javascript
const onboarding = document.querySelector('.onboarding');

// Structure to Verify
const onboardingHasFocus = onboarding == document.activeElement;

console.log(onboardingHasFocus);
// Output: false;
```
___

##💡 Spread Operator

With **spread(...)** we get an alternative to "merge" elements:

```javascript
const devToPeople = [
  {
    name: 'Renan',
    id: 'renancferro',
  }
];

const newDevToParticipants = [
  {
    name: 'New User',
    id: 'newUserId',
  },
  ...devToPeople
];

console.log(newDevToParticipants);
// Output: 
//[
//    {
//        name: 'New User',
//          id: 'newUserId',
//    },
//    {
//        "name": "Renan",
//        "id": "renancferro"
//    }
//];
```
___

##💡 Get a Random Element

Get a random object element with one line of code:

```javascript
const newDevToParticipants = [
  {
    name: 'New User',
    id: 'newUserId',
  },
  {
    name: 'Renan',
    id: 'renancferro',
  },
];

// Structure to Get
const getRandomUser = (users) =>  users[Math.floor(Math.random() * users.length)];

console.log(getRandomUser(newDevToParticipants));
// Output: {
//    "name": "Renan",
//    "id": "renancferro"
//}
```
___

##💡 Insert a New Object at a Specific Position

How to insert a new object at a specific position within an array of objects:

```javascript
const newDevToParticipants = [
  {
    name: 'New User',
    id: 'newUserId',
  },
  {
    name: 'Renan',
    id: 'renancferro',
  },
];

// Structure to insert:
const insertNewUser = (originalArray, index, newItem) => [...originalArray.slice(0, index), newItem, ...originalArray.slice(index)];

const newUser = {
    name: 'New User 2',
    id: 'newUser2',
};

console.log(insertNewUser(newDevToParticipants, 1, newUser));
// Output
//[
//    {
//        "name": "New User",
//        "id": "newUserId"
//    },
//    {
//        "name": "New User 2",
//        "id": "newUser2"
//    },
//    {
//        "name": "Renan",
//        "id": "renancferro"
//    }
//]
```
___

##💡 Copy to the Clipboard

Basic and simple structure for copying content to the clipboard:

```javascript
// Structure to Copy
const copyContentToClipboard = (contentToCopy) => navigator.clipboard.writeText(contentToCopy);

copyContentToClipboard('Do it different!');
```
___

Sometimes some things can be simpler than we imagine!

And do you know any other cool tips?! Leave a comment below so we can see!

I hope you liked it and If you have any suggestions, please leave them in the comment.

If you found this post helpful, please like and share it, please!

**Happy Coding**, See you soon 🤟🏽🤟🏽