DEV Community

Cover image for TIPS AND TRICKS FOR JAVASCRIPT BEGINNERS
Anil Loutombam
Anil Loutombam

Posted on

TIPS AND TRICKS FOR JAVASCRIPT BEGINNERS

In this article, I’ll share a set of JavaScript tips, tricks, and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.

Covered Topics are :-

1. References,
2. Objects,
3. Arrays

References

  • 1.1 Use const for all of your references; avoid using var.

Why? This ensures that you can’t reassign your references, which can lead to bugs and difficult to comprehend code.

// bad way to write
var a = 1;
var b = 2;
Enter fullscreen mode Exit fullscreen mode
// this is the good way to write avoid using var
const a = 1;
const b = 2;
Enter fullscreen mode Exit fullscreen mode
  • 1.2 If you must reassign references, use let instead of var.

Why? let is block-scoped rather than function-scoped like var.

// bad
var count = 1;
if (true) {
  count += 1;
}

// good, use the let.
let count = 1;
if (true) {
  count += 1;
}
Enter fullscreen mode Exit fullscreen mode
  • 1.3 Note that both let and const are block-scoped.
// const and let only exist in the blocks they are defined in.
{
  let a = 1;
  const b = 1;
}
console.log(a); // ReferenceError
console.log(b); // ReferenceError
Enter fullscreen mode Exit fullscreen mode

Objects

  • 2.1 Use the literal syntax for object creation.
// bad
const item = new Object();

// good
const item = {};
Enter fullscreen mode Exit fullscreen mode
  • 2.2 Use computed property names when creating objects with dynamic property names.

Why? They allow you to define all the properties of an object in one place.

function getKey(k) {
  return `a key named ${k}`;
}

// bad
const obj = {
  id: 5,
  name: 'Tony Stark',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'Tony Stark',
  [getKey('enabled')]: true,
};

Enter fullscreen mode Exit fullscreen mode
  • 2.3 Use object method shorthand.
// bad
const atom = {
  value: 1,

  addValue: function (value) {
    return atom.value + value;
  },
};

// good
const atom = {
  value: 1,

  addValue(value) {
    return atom.value + value;
  },
};
Enter fullscreen mode Exit fullscreen mode
  • 2.4 Use property value shorthand.

Why? It is shorter and descriptive.

const tonyStark = 'Tony Stark';

// bad
const obj = {
  tonyStark: tonyStark,
};

// good
const obj = {
  tonyStark,
};

Enter fullscreen mode Exit fullscreen mode
  • 2.5 Group your shorthand properties at the beginning of your object declaration.

Why? It’s easier to tell which properties are using the shorthand.

const anakinSkywalker = 'Anakin Skywalker';
const lukeSkywalker = 'Luke Skywalker';

// bad
const obj = {
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  lukeSkywalker,
  episodeThree: 3,
  mayTheFourth: 4,
  anakinSkywalker,
};

// good
const obj = {
  lukeSkywalker,
  anakinSkywalker,
  episodeOne: 1,
  twoJediWalkIntoACantina: 2,
  episodeThree: 3,
  mayTheFourth: 4,
};
Enter fullscreen mode Exit fullscreen mode
  • 2.6 Only quote properties that are invalid identifiers.

Why? In general, we consider it subjectively easier to read. It improves syntax highlighting and is also more easily optimized by many JS engines.

// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};
Enter fullscreen mode Exit fullscreen mode
  • 2.7 Do not call Object.prototype methods directly, such as hasOwnProperty, propertyIsEnumerable, and isPrototypeOf.

Why? These methods may be shadowed by properties on the object in question - consider { hasOwnProperty: false } - or, the object may be a null object (Object.create(null)).

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
/* or */
import has from 'has'; // https://www.npmjs.com/package/has
console.log(has(object, key));
Enter fullscreen mode Exit fullscreen mode
  • 2.8 Prefer the object spread operator over Object.assign to shallow-copy objects. Use the object rest operator to get a new object with certain properties omitted.
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
delete copy.a; // so does this

// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }

// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }

const { a, ...noA } = copy; // noA => { b: 2, c: 3 }
Enter fullscreen mode Exit fullscreen mode

Arrays

  • 3.1 Use the literal syntax for array creation.
// bad
const items = new Array();

// good
const items = [];
Enter fullscreen mode Exit fullscreen mode
  • 3.2 Use Array#Push instead of direct assignment to add items to an array.
const someStack = [];

// bad
someStack[someStack.length] = 'abracadabra';

// good
someStack.push('abracadabra');
Enter fullscreen mode Exit fullscreen mode
  • 3.3 Use array spreads ... to copy arrays.
// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];
Enter fullscreen mode Exit fullscreen mode
  • 3.4 To convert an iterable object to an array, use spreads ... instead of Array.from.
const foo = document.querySelectorAll('.foo');

// good
const nodes = Array.from(foo);

// best
const nodes = [...foo];
Enter fullscreen mode Exit fullscreen mode
  • 3.5 Use Array.from for converting an array-like object to an array.
const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 };

// bad
const arr = Array.prototype.slice.call(arrLike);

// good
const arr = Array.from(arrLike);
Enter fullscreen mode Exit fullscreen mode
  • 3.6 Use Array.from instead of spread ... for mapping over iterables, because it avoids creating an intermediate array.
// bad
const baz = [...foo].map(bar);

// good
const baz = Array.from(foo, bar);
Enter fullscreen mode Exit fullscreen mode
  • 3.7 Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects.
// good
[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;
});

// good
[1, 2, 3].map((x) => x + 1);

// bad - no returned value means `acc` becomes undefined after the first iteration
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
});

// good
[[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => {
  const flatten = acc.concat(item);
  return flatten;
});

// bad
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  } else {
    return false;
  }
});

// good
inbox.filter((msg) => {
  const { subject, author } = msg;
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee';
  }

  return false;
});
Enter fullscreen mode Exit fullscreen mode
  • 3.8 Use line breaks after open and before close array brackets if an array has multiple lines.
// bad
const arr = [
  [0, 1], [2, 3], [4, 5],
];

const objectInArray = [{
  id: 1,
}, {
  id: 2,
}];

const numberInArray = [
  1, 2,
];

// good
const arr = [[0, 1], [2, 3], [4, 5]];

const objectInArray = [
  {
    id: 1,
  },
  {
    id: 2,
  },
];

const numberInArray = [
  1,
  2,
];
Enter fullscreen mode Exit fullscreen mode

Summary

Alright, that were useful JavaScript tips and tricks. I hope you've learned something new and you can go ahead to improve your code. If you sight anything wrong just let me know!
Thanks for reading.

If you liked the post, You can follow up here for more.
Github.
Medium.
HackerRank.
LinkedIn.

Top comments (4)

Collapse
 
viniciusrio profile image
Vinicius Rio

This is very useful. I think that in two cases beginners may prefer the use of "new". It is more descriptive, as in the example: const items = new Array (), although '[]' says the table by typing less. Great tips!

Collapse
 
anilloutombam profile image
Anil Loutombam • Edited

Yes, beginners do prefer, in fact I was using the same, a few years back.

Collapse
 
vikramkadiam profile image
Vikram Kadiam

Good compilation !

Collapse
 
anilloutombam profile image
Anil Loutombam

Thank you