DEV Community

Cover image for 9 Tricks To Write Less JavaScript.
Shoaib Sayyed
Shoaib Sayyed

Posted on • Edited on

9 Tricks To Write Less JavaScript.

Hi Dev πŸ‘‹, Thanks for opening my blog. I hope you are doing well and ready to learn some Tricks To Write Less JavaScript 😎.

So, let's start!

1. Declaring Variables

//Longhand
let x;
let y;
let z = "post";

//Shorthand
let x, y, z = "post";
Enter fullscreen mode Exit fullscreen mode

2. Assignment Operator

//Longhand
x = x + y;
x = x - y;

//Shorthand
x += y;
x -= y;
Enter fullscreen mode Exit fullscreen mode

3. Ternary Operator

let answer, num = 15;

//Longhand
if (num > 10) {
  answer = "greater than 10";
} 
else {
  answer = "less than 10";
}

//Shorthand
const answer = num > 10 ? "greater than 10" : "less than 10";
Enter fullscreen mode Exit fullscreen mode

4. Short for Loop

const languages = ["html", "css", "js"];

//Longhand
for (let i = 0; i < languages.length; i++) {
  const language = languages[i];
  console.log(language);
}

//Shorthand
for (let language of languages) console.log(language);
Enter fullscreen mode Exit fullscreen mode

5. Template Literals

const name = "Dev";
const timeOfDay = "afternoon";

//Longhand
const greeting = "Hello " + name + ", I wish you a good " + timeOfDay + "!";

//Shorthand
const greeting = `Hello ${name}, I wish you a good ${timeOfDay}!`;
Enter fullscreen mode Exit fullscreen mode

6. Arrow Function

//Longhand
function sayHello(name) {
  console.log("Hello", name);
}

list.forEach(function (item) {
  console.log(item);
});

//Shorthand
sayHello = name => console.log("Hello", name);

list.forEach(item => console.log(item));
Enter fullscreen mode Exit fullscreen mode

7. Object Array Notation

//Longhand
let arr = new Array();
arr[0] = "html";
arr[1] = "css";
arr[2] = "js";

//Shorthand
let arr = ["html", "css", "js"];
Enter fullscreen mode Exit fullscreen mode

8. Object Destructuring

const post = {
  data: {
    id: 1,
    title: "9 trick to write less Javascript",
    text: "Hello World!",
    author: "Shoaib Sayyed",
  },
};

//Longhand
const id = post.data.id;
const title = post.data.title;
const text = post.data.text;
const author = post.data.author;

//Shorthand
const { id, title, text, author } = post.data;
Enter fullscreen mode Exit fullscreen mode

9. Object with identical Keys and Values

//Longhand
const userDetails = {
  name: name, // 'name' key = 'name' variable
  email: email,
  age: age,
  location: location,
};

//Shorthand
const userDetails = { name, email, age, location };
Enter fullscreen mode Exit fullscreen mode

That's It 😎.

Thanks for reading! My name is Shoaib Sayyed; I love helping people to learn new skills 😊. You can follow me, if you’d like to be notified about new articles and resources.

Top comments (21)

Collapse
 
jamesthomson profile image
James Thomson

All good tips for newbies, but personally I wouldn't recommend the 1st. I think it's important to be explicit when defining variables so others can quickly scan the code.

Collapse
 
patricnox profile image
PatricNox

If the vars are of the same value then I would only see it as a benefit as someone who reviews the code.

Collapse
 
jamesthomson profile image
James Thomson

Why would the vars all be the same value? Unless you had them all undefined: let x,y,z.

If you're assuming that let x, y, z = "post" assigns "post" to all, it doesn't, and so this reinforces my point.

Thread Thread
 
patricnox profile image
PatricNox

That would then be a matter of code inexperience rather than writing clean code.

function example(backgrounds) {
    let background;
    let array;
    let color = getUserBgColor();

    backgrounds.forEach(color => {
        if (color === 'red') {
            array.push(color);
        }
    })
    background = array[Math.floor(Math.random() * array.length)];
    return background;
}

compared to this

function example(backgrounds) {
    let background, array, color = getUserBgColor();
    backgrounds.forEach(color => {
        if (color !== 'red') {
            array.push(color);
        }
    }) 

    background = array[Math.floor(Math.random() * array.length)];
    return background;
}

It would also reduce amount of lines which could be a great refactor for a big file.
(In addition, the foreach loop would not need to have a space before it if the variable declares are set within the same line)

Thread Thread
 
jpantunes profile image
JP Antunes • Edited

I'm not following your train of thought here PatricNox... or did you change your mind between comments?
"If the vars are of the same value...."
"let background, array, color = getUserBgColor();"

Also, If the purpose of refactoring is to reduce the cognitive load and error surface area, then your example would probably be best written as:

function example(backgrounds, userBGcolour = 'red') {
  const array = backgrounds.filter(e => e === userBGcolour);
  const background = array[Math.floor(Math.random() * array.length)];

  return background
}

This assuming that I correctly guessed the behaviour and purpose for the "color" variable you define outside the forEach loop, and the other one inside it, as well as the magic string 'red'... which your colleagues should never have to do.

Thread Thread
 
jamesthomson profile image
James Thomson

When you work with and review thousands of lines of code per day you want clean legible code. Scanning code vertically is more efficient. Writing a couple extra lines greatly helps the reviewers and maintainers.

Thread Thread
 
jpantunes profile image
JP Antunes

Agreed, but I also want to point out that making extra lines of code that helps you reason better doesn't make the code more readable at all. In fact, it can make your code thousands of lines long when a a dozen might do the job with less bugs.

Thread Thread
 
jamesthomson profile image
James Thomson

We’re only talking variables here. Besides, with destructuring and using modules your files should never be that big.

Thread Thread
 
jpantunes profile image
JP Antunes

I think we are talking about different things. I replied to PatricNox's comment with an example that takes less LOCs and is imho less error prone. What were you replying to?

Thread Thread
 
jamesthomson profile image
James Thomson

This

Agreed, but I also want to point out that making extra lines of code that helps you reason better doesn't make the code more readable at all. In fact, it can make your code thousands of lines long when a a dozen might do the job with less bugs.

Thread Thread
 
jpantunes profile image
JP Antunes

Oh, that's not about variables at all, it's really about what happens inside a function and what should be outside it.

Both examples of uninitialised variable declarations let a, b, c = 1 or let a; let b; let c =1 or even let [a,b,c] = [,,1] are code smells imho, it just looks messy and error prone.

Thread Thread
 
jamesthomson profile image
James Thomson

Ah I see, then I think we are talking about different things. The max thread levels makes this confusing.

And I agree about undefined variable declarations.

Collapse
 
patricnox profile image
PatricNox • Edited

The object Destructuring (8) one was new to me, nice!

(4) can be tidy in small projects, but bigger ones where any coding standard should be followed then it would not be applicable. There's benefits to always use brackets, even though there's only one action within.

Collapse
 
joaquinwojcik profile image
Joaquin Wojcik

Just a thing about arrow functions:

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

Source: developer.mozilla.org/en-US/docs/W...

Collapse
 
matoval profile image
matoval

Object Destructuring is my favorite!

Collapse
 
notngan profile image
Ngan B. Nguyen

Some are just the new syntax in ES6. We can't call it "tricks" in my opinion (Template Literals, Arrow Function).

Collapse
 
ruslk profile image
ruslK

Nice, short, and useful!

Collapse
 
blindfish3 profile image
Ben Calder

Beginners beware: this is yet another post that mixes useful information with some bad practice..
Avoid #1 and don't ommit { }

Collapse
 
madza profile image
Madza

Love all the syntax features from ES6 and above. Tho there is still room for improvement, like more concise syntax for targeting DOM elements (like jquery does)

Collapse
 
jamesthomson profile image
James Thomson

That's a browser API consideration. ECMAScript (i.e. ES6) has no concept of a browser.

Besides that, have you used querySelector? You can do pretty much any similar jQuery selection with it.

Collapse
 
koresar profile image
Vasyl Boroviak

Tip 10

npm i lodash