Three useful hacks for JavaScript

2
303

Getting array items from behind to front

If you want to get the array items from behind to front, just do this:

var newArray = [1, 2, 3, 4];

console.log(newArray.slice(-1)); // [4]
console.log(newArray.slice(-2)); // [3, 4]
console.log(newArray.slice(-3)); // [2, 3, 4]
console.log(newArray.slice(-4)); // [1, 2, 3, 4]

Shorter conditions:

If you wanna execute a function depends from true. You can use this way:

if(condition) {
 doSomething();
}

or:

condition && dosomething();

Set default values to variable by using “||”

var a;

console.log(a); //undefined

a = a || 'default value';

console.log(a); //default value

a = a || 'new value';

console.log(a); //default value

 

 

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here