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 = {};
Written by Arjunkumar
Related protips
8 Responses
Nice. :)
Code is getting a bit unreadable, especially for newbies.
String to Number conversion: prepend a plus sign.
var num = +'100'tx. updated.
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...
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; The Number to String Conversion is not lazy
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();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.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside