Three useful hacks
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]
Short-circuits conditionals
If you have to execute a function just if a condition is true
, like this:
if(condition){
dosomething();
}
You can use a short-circuit just like this:
condition && dosomething();
Set variable default values using “||”
If you have to set a default value to variables, you can simple do this:
var a;
console.log(a); //undefined
a = a || 'default value';
console.log(a); //default value
a = a || 'new value';
console.log(a); //default value
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW