DEV Community

Cover image for 7 Pro Tips JavaScript One-Liners for You to Know and Use
Renan Ferro
Renan Ferro

Posted on

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

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

Top comments (4)

Collapse
 
renancferro profile image
Renan Ferro

Oh, I really appreciate it! Hope this can help you in future JavaScript code!

Collapse
 
kurealnum profile image
Oscar

This is a really good post for beginners and advanced JavaScripters alike!

Collapse
 
renancferro profile image
Renan Ferro

Cool! There are some cool and interesting things, right?! Do you know another code example?!

Collapse
 
raulferreirasilva profile image
Raul Ferreira

Thanks for sharing your knowledge, I needed to do something similar to "Check if Element has Focus" and I ended up getting a little beaten up, if I had seen this post before, it would have been a thousand times easier. Thank you very much for sharing your knowledge 🦤.