Last Updated: October 07, 2020
·
53.64K
· tk120404

Get Lazy in javascript coding

Lazy ways of coding in javascript.

Array Creation

Normal way

var a = new Array();

Lazy way

var a = [];

String to Number Conversion

Normal way

var num = parseInt('100');

Lazy way

var num = '100'*1;

Number to String Conversion

Normal way

var str = 100.toString();

Lazy way

var str = '' +100;
var str = +100;

Object creation

Normal way

var obj = new Object();

var obj = Object.create(null);

Lazy way

var obj = {};

8 Responses
Add your response

Nice. :)

Code is getting a bit unreadable, especially for newbies.

over 1 year ago ·

String to Number conversion: prepend a plus sign.

var num = +'100'
over 1 year ago ·

tx. updated.

over 1 year ago ·

I'm not sure most of this would be a good idea for myself looking this code a year later, let alone a junior dev trying to maintain it...

over 1 year ago ·

Principle of least surprise says:

// clear: this variable is a number.
var numberizedString = Number("100"); 
// easy-to-miss unary plus, easy to mistake as binary plus
var lazyWay = +'100'; 

// clear: this variable is a string
var stringifiedNumber = 100..toString(); 
// not obvious: we're concatenating an empty string? Why?
var lazyWay = '' + 100; 
over 1 year ago ·

The Number to String Conversion is not lazy

over 1 year ago ·

The prepended plus sign is also a nice lazy way to get the current time in milliseconds

var time = new Date().getTime();

vs

vat time = +new Date();
over 1 year ago ·

I am also hesitant about the number to string conversions. They are not that lazy but most important, it could confuse some inexperienced programmers. To make my code readable to others, I would accept (and encourage) the lazy way to create empty array and object, but not the type conversions suggested.

over 1 year ago ·