- Use of .call() function:
If you want to iterate over the properties of object.var listitems = document.querySelectorAll('li'); [].forEach.call(items, function(item) { //your code here })
Above code does the same as the code belowfor (i = 0; i < items.length; i++) { var item= items[i]; // your code here }
Reversing a string:var js = 'hello javascript'; var sj = [].reverse.call(hey.split('')).join(''); // "tpircsavaj olleh" console.log(sj);
- Always use var while declaring variable for the first time.
- Use === instead of == .
- undefined, null, 0, false, "", NaN are all false values.
- Use semicolon (;) for line termination.
- Get random item in an array.
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119]; var random = items[Math.floor(Math.random() * items.length)];
- Verify that the given argument is number
function isNumber(n){ return !isNaN(parseFloat(n)) && isFinite(n); }
- Get min and max of the array of numbers:
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; var maxInNumbers = Math.max.apply(Math, numbers); var minInNumbers = Math.min.apply(Math, numbers);
- Use the map() function method to loop through an array’s items
var squares = [1,2,3,4].map(function (val) { return val * val; }); // squares will be equal to [1, 4, 9, 16]
- Avoid using try-catch-finally inside a loop:
The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable. - If you want to know how much time is taken by a code, place console.time("time") and console.timeEnd("time") at beginning and end of the code respectively.
- Converting decimal to binary and vice versa:
Decimal to Binary(15).toString(2) // Will give 1111
Binary to DecimalparseInt('1111',2); // will give 15
Pages - Menu
Sponsored Links
December 5, 2017
Cool JavaScript Tricks
Today I would like to mention some of the JavaScript tricks that many JavaScript programmers do not know. They are cool to have in our code, but some are not practiced in real world. Here are few of them.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment