Useful JavaScript Tips and Tricks
Today I discuss about some useful JavaScript tips and tricks that you must be should know.
1. Scope, Block scope, Global variable
If you declare a variable in a function its scope/area only that function. You can’t access variable outside of the scope. If you want to access a variable outside of scope declared that variable outside of function. It’s called global declaration.
2. Closure
When you call or return a function from another function it makes a closed environment and store an external reference for future use it’s called Closure.
3. Asynchronous JavaScript setTimeout, setInterval
When we use setTimeout in a function it works his own time, below the example in myTask function we want to show output 100. Outside of the function there are two another output. You think the output will be 100, 200, 300 synchronously. But here not! We set time 2 sec for call myTask function. So the output will be 200, 300 and after 2 sec 100.
4. Find Largest element of an array
Here we have a numbers array where some elements. We want to find the largest element so what we can do? At first, we take first position element as max then throw loop and find total length. Then we store value in element variable and check. Then use a for loop and identify which value is large.
5. Remove duplicate item from array
Here we have a numbers array where some duplicate elements. We want to remove duplicate element from this array. so, what we can do? At first, we take an empty array uniqueNumber. then throw loop and find total length. Then we check index using if condition with -1 value and push to uniqueNumber array.
6. Reverse String
For reverse here we add a function reverseString where initial value is an empty string. Then using for loop and set char first then string in reverse variable. After return the reverse and we take a variable where write a sentence that we want to reverse then call reverseString function.
7. Check a number is Prime or not
Prime number is that number which is only divide by 1 or that number. Below an example display it.
8. Calculate Factorial in a Recursive function