JavaScript or JS helps implement complex things on web pages. Many of the developers know the importance of a minified JavaScript file but few are aware of an optimized JavaScript code.
To evolve more and have a better exposure about JS, you might have to know ECMASCRIPT and the latest ES versions. Here are 16 ways that you can make use of modern JavaScript to improve the quality of your code.
It is a small hack to filter out bucket of elements from the array pool. This method creates an array filled with all array elements that pass a test (provided as a function). According to requirement create a callback function for non-required elements. The arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method.
In below example the bucket elements are null and are ready to get filtered out.
Example:
schema = ["hi","ihaveboyfriend",null, null, "goodbye"]
schema = schema.filter(function(n) {
return n
});Output: ["hi","ihaveboyfriend", "goodbye"]
This hack will save some time and lines of codes for developers.
The String.replace() function allows you to replace strings using String and Regex. The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. You can even explore other string methods too.
Basically this function replaces the string at its first occurrence. But to replace all using replaceAll() function, use /g at the end of a Regex:
Example:
var string = "login login";
console.log(string.replace("in", "out")); // "logout login"
console.log(string.replace(/in/g, "out")); //"logout logout"
With the help of breakpoints or debugging points you can set multiple barriers to rectify source of error at every barrier. Breakpoints are a faster and more hassle-free way to debug your JavaScript code. When the code hits the debugger statement execution stops, it will launch your browser’s developer tools and jump to the line where the debugger statement was found. The JavaScript Console tab is a valuable debugging tool too as it just works just like lint.
Press F11 for next call function and f8 to resume script execution.
You can also check what dynamic values are generated by a function, using console and can check output on different values.
#web-development #javascript #programming #developer