1) Empty an array
var arr = [10 , 20 , 30 ];
arr.length = 0; // arr will be equal to [].
2) Truncate an array using length
Like the previous example of emptying an array, we truncate it using the length property.
var arr = [10, 20, 30, 40, 50, 60, 70, 80, 90];
arr.length = 4; // arr will be equal to [10, 20, 30, 40].
As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined as a value. The array length is not a read only property.
arr.length = 10; // the new array length is 10
arr[arr.length - 1] ; // arr [10, 20, 30, 40, 50, 60, 70, 80, 90, undefined];
3)Use logical AND/ OR for conditions
var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
4) Comma operator
var a = 10;
var b = ( a++, 99 );
console.log(a); // a will be equal to 10
console.log(b); // b is equal to 99
5) Swap variables
let v1 = 'value 1';
let v2 = 'value 2';
[v1,v2] = [v2, v1];
console.log(v1, v2);
No comments:
Post a Comment
Your feedback is always appreciated. I will try to reply to your queries as soon as time allows.Please don't spam,spam comments will be deleted upon reviews.