7 Pro Tips JavaScript One-Liners for You to Know and Use

Renan Ferro - Sep 20 '23 - - Dev Community

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:

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 :("
Enter fullscreen mode Exit fullscreen mode

💡 Generate Random String Id

Generate a random string id easy:

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

console.log(randomIdentifier);
// Output: 'd5ptscfrln7';
Enter fullscreen mode Exit fullscreen mode

💡 Check if Element has Focus

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

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

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

console.log(onboardingHasFocus);
// Output: false;
Enter fullscreen mode Exit fullscreen mode

💡 Spread Operator

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

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"
//    }
//];
Enter fullscreen mode Exit fullscreen mode

💡 Get a Random Element

Get a random object element with one line of code:

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"
//}
Enter fullscreen mode Exit fullscreen mode

💡 Insert a New Object at a Specific Position

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

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"
//    }
//]
Enter fullscreen mode Exit fullscreen mode

💡 Copy to the Clipboard

Basic and simple structure for copying content to the clipboard:

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

copyContentToClipboard('Do it different!');
Enter fullscreen mode Exit fullscreen mode

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 🤟🏽🤟🏽

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player