5 effective JavaScript debugging techniques

JavaScript is the web language used by over 90% of websites. Still, it has a reputation of being difficult to debug. JavaScript’s asynchronous nature makes it easy for developers to create complex web applications, but the same attribute makes it challenging to locate errors. Fortunately, knowing the right tools and understanding a few debugging tricks can make it easier to resolve bugs and errors.

Here we have put together a list of practical JavaScript debugging techniques you should keep in mind.

Use debugger

For many JavaScript developers, the debugger is their favorite debugging tool. When writing extensive code with complex logic, experienced programmers place a debugger in the code line that they anticipate will produce an error. When such code is run in Chrome, the Developer Tool will automatically stop when it encounters a debugger keyword.

You can also wrap the debugger in conditions to run them in a particular event like this:

if (thisThing) {
debugger;}
Learn more about debugger keywords here.

Learn to use the console.trace

JavaScript has many frameworks such as Node.js, Vue.js, and React. These frameworks make it easy to produce code quickly. In a project, you will have many views, triggers, and too many events. When working with a framework, most of these events will be hidden in an abstract layer, so it will be challenging to identify what caused a particular function call.

JavaScript is not very structured, and it is hard to get a clear overview of what happened and when. This is why JavaScript developers should use the console.trace method.

Let’s assume in the following code, you want to see the entire stack trace for the function call funcZ:

var car;
var func1 = function() {
func2();
}

var func2 = function() {
func4();
}
var func3 = function() {
}

var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}

   this.funcY = function() {
           this.funcZ();
   }

   this.funcZ = function() {
           console.trace(‘trace car’)
   }

}
func1();
var car;
var func1 = function() {
func2();
}
var func2 = function() {
func4();
}
var func3 = function() {
}
var func4 = function() {
car = new Car();
car.funcX();
}
var Car = function() {
this.brand = ‘volvo’;
this.color = ‘red’;
this.funcX = function() {
this.funcY();
}
this.funcY = function() {
this.funcZ();
}
this.funcZ = function() {
console.trace(‘trace car’)
}
}
func1();

This will be the output at Line 33:

As you can see that the trace clearly indicates func1 called func2, which is further called func4. Then the func4 created an instance of variable Car calling the function car.funcX, and so on. This is a simple script, so it is easier to follow through the flow, but when the code block is a big console.trace method proves to be handy. You can easily trace all related functions to pinpoint the bug.

Use console.time() and console.timeEnd() to benchmark loops 

Not just JavaScript, but loops are trouble makers in every programming language. To create efficient and fast code, developers need to know how long any code segment takes to execute. Slow loops can degrade the performance of the entire JavaScript code. 

But you can benchmark loops to evaluate their performance. Here is a way to set up multiple timers using console.time() and console.timeEnd() methods.

console.time(‘Timer1’);

var items = [];

for(var i = 0; i < 100000; i++){

items.push({index: i});
}

console.timeEnd(‘Timer1’);

The output will be:

As evident, benchmarking loops in JavaScript can help you save time trying to troubleshoot performance issues.

Chrome Developer Tool for responsive test 

As most web applications are accessed through multiple devices, you have to make sure your JavaScript code works on all screen sizes. In an ideal world, developers would have every single device check the compatibility of their code. Unfortunately, in the real world, it is not feasible.

Chrome Developer Tool has the option to resize the viewport to check your code’s performance on any screen size. To use this feature, open the inspector in Chrome and click on the toggle device mode button as highlighted in the image:

Chrome Developer Tool for JavaScript

Using this tool, you can instantly check the media queries, forms, and dynamic code for various screen sizes.

Black box scripts for faster debugging 

Modern web applications use libraries and frameworks that are tested for bugs. But when you run any debugger tool, it will still check and try to debug all files, even those that have no relevance. It substantially increases the cost of debugging and takes longer too.

The solution lies in black-boxing the scripts you don’t need to debug. Fortunately, both Chrome and Firefox provide the option to blacklist scripts that you don’t want to debug.

In Chrome, open the inspector and right-click the JavaScript file you want to blacklist, and choose ‘black box script.’ You can learn more about Chrome Script Black Box here.

In Firefox, go to the debugger tab in the element inspector. Mark the scripts you want to blacklist, then click on the eye at the bottom-left corner. Learn more here.

Conclusion

Debugging is an active responsibility of developers. Its unstructured design makes it challenging to identify and resolve errors with JavaScript. The techniques shared above will help you create JavaScript debugging more efficiently.

Talent500 is one of the best platforms for developers to find remote work opportunities. Join us today to be discovered by the best companies.

Top JavaScript interview code-based questions

JavaScript is an undisputed leader in web application development. In the last two decades, the programming language has grown to the extent that 98% of websites use JavaScript.

Technological giants like Google and Facebook use JavaScript to build complex web applications because of the availability of vast open-source frameworks and libraries supporting JavaScript. Given the versatility of the language and its excessive use, any software developer can expect to face JavaScript code-based questions during interviews.

If you’re planning to become a JavaScript developer or interviewing as one, here are the essential code-based JavaScript questions.

1. Explain the output of the following JavaScript code

(function(){

  var a = b = 3;

})();

console.log(“a defined? ” + (typeof a !== ‘undefined’));

console.log(“b defined? ” + (typeof b !== ‘undefined’));

The output of the above code will be:

a defined? false

b defined? true

Explanation: Most JavaScript developers expect that the output of this code will be undefined because both a and b are defined within the enclosing scope of the function. Since the code begins with the var keyword, they assume ‘typeof a’ and ‘typeof b’ to be undefined.

That’s a mistake. It is because the statement var a = b = 3; is not shorthand for:

var b = 3;

var a = b;

But, it is shorthand for:

b = 3;

var a = b;

As a result, b ends up in a global variable available outside the scope of the enclosing function.

However, note that, in strict mode, the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined.

2. What will be the output of the code below, and why?

var myObject = {

   foo: “bar”,

   func: function() {

     var self = this;

console.log(“outer func: 

this.foo = ” + this.foo);

console.log(“outer func: 

self.foo = ” + self.foo);

     (function() {

console.log(“inner func: 

this.foo = ” + this.foo);

console.log(“inner func: 

self.foo = ” + self.foo);

     }());

   }

};

myObject.func();

The output of the code will be:

outer func: this.foo = bar

outer func: self.foo = bar

inner func: this.foo = undefined

inner func: self.foo = bar

As both this and self refers to myObject in the outer object, they can properly reference and access foo.

Back in the inner function, they no longer refer to myObject, which results in undefined this.foo in the inner function. However, the reference to the local variable self remains in scope and therefore is accessible.

3. Will the following two functions return the same output? Why or why not?

function foo1()

{

  return {

    bar: “hello”

  };

}

function foo2()

{

  return

  {

    bar: “hello”

  };

}

No, these two functions will not return the same output.

The following statements:

console.log(“foo1 returns:”);

console.log(foo1());

console.log(“foo2 returns:”);

console.log(foo2());

will return:

foo1 returns:

Object {bar: “hello”}

foo2 returns:

undefined

It is a tricky JavaScript code-based interview question because surprisingly foo2() returns undefined without any error being thrown.

The reason for this outcome is that in JavaScript, semicolons are technically optional. As a result, when the return statement is encountered in foo2(), a; is automatically inserted at the end of the return statement. Hence no error was thrown as the remainder of the code is perfectly valid.

This is why you should always follow the convention of placing an opening curly brace at the end of a code line in JavaScript rather than beginning on a new line. It is not just a stylistic preference but also essential to avoid unexplained bugs.

4. Write a simple JavaScript function (less than 160 characters) that checks whether a string is a palindrome or not. 

Here is the function that will check the input and return True if the string is a palindrome, otherwise, the output will be False.

function isPalindrome(str) {

  str = str.replace(/\W/g, ”).toLowerCase();

  return (str == str.split(”).reverse().join(”));

}

Some console output examples:

console.log(isPalindrome(“level”)); // logs ‘true’

console.log(isPalindrome(“levels”)); // logs ‘false’

console.log(isPalindrome(“A car, a man, a maraca”)); // logs ‘true’

5. Consider the following JavaScript code:

for (var i = 0; i < 5; i++) {

  var btn = document.createElement(‘button’);

btn.appendChild(document.createTextNode(‘Button ‘ + i));

btn.addEventListener(‘click’, function(){ console.log(i); });

document.body.appendChild(btn);

}

What will be logged into the console when the user clicks Button 4 and why?

Also, provide an alternative JavaScript implementation of the same.

No matter what the user clicks on the keyboard, the number 5 will be displayed every time. It is because by the time the onclick method is invoked, irrespective of what button is clicked, the for loop has already been completed and the variable i is assigned a value of 5.

As an alternative, we need to write a function to capture the value of i at each pass when the for loop executes and pass the value into a newly created function object. Here is the alternative code:

for (var i = 0; i < 5; i++) {

  var btn = document.createElement(‘button’);

btn.appendChild(document.createTextNode(‘Button ‘ + i));

btn.addEventListener(‘click’, (function(i) {

   return function() { console.log(i); };

  })(i));

document.body.appendChild(btn);

}

Conclusion 

JavaScript code-based questions can be a bit tricky. It would help if you focused on understanding the basics of the JavaScript components to tackle such interviews. Here are some more technical JavaScript interview questions.

Talent500 is the platform to discover job opportunities with global companies. Join our elite pool of talent, and sign up here.

 

10 Useful JavaScript plugins & data table libraries

Data tables are efficient tools for visualizing and processing data in JavaScript applications. As a JavaScript developer, a crucial part of your job will be to create data tables for data-driven websites and applications. Creating data tables manually is redundant as JavaScript has several data table plugins and libraries.

Designing data tables is an elaborated process. You have to develop a table layout, integrate it with the data source, and determine the interaction of data tables with other components. Manually creating an HTML table will be time-consuming and tedious. JavaScript data table libraries offer automation and significantly reduce the chances of errors.

This article will cover the ten most helpful JavaScript data table plugins and libraries you can use.

1.  jQueryDynatable

One of the widely used JavaScript data libraries is Dynatable. It is a powerful plugin for automatically generating data tables; it is developer-focused. You can create highly customizable tables with Dynatable as it offers complete freedom to render the design, filter results, and customize data table searches. 

Dynatable can be used for data-centric websites, allowing intelligent sorting out of the box. It will enable users to sort data in ascending and descending order for any number of columns. The plugin is licensed under the Affero General Public License and is available for $95 to $950.

 

2. Stacktable

This free JavaScript data table plugin is licensed under the MIT free source license. Stacktable.js is a highly robust jQuery plugin for creating highly responsive tables. For mobile-friendly data-driven websites, Stacktable is used to stack tables. With Stacktable, you can implement highly responsive tables that stack rows and fundamental values over each other. This creates a side-by-side layout for simplicity. 

The limitation of using Stacktable is there are few options, and the documentation is also limited. If you are developing a project on a budget and want to make standard table elements mobile-friendly, this is one of the JavaScript plugins to try. 

 

3. Material-table

Material-table is one of the most popular JavaScript data libraries, primarily because of its material-styled user interface. On GitHub, Material-table is one of the highest-rated JavaScript data table libraries. You can easily incorporate it in the most complex applications and websites as it supports custom column rendering, detailed panel view for rows, CSV export, and several UI elements. There is extensive documentation available to help developers exploit its features. 

 

4. W2Ui

W2Ui is not just a JavaScript data table library but is a complete JavaScript UI library. It requires jQuery to function and has clearly defined declarative syntax, designed to create a clear distinction between application data and its logic layer. This approach offers immense performance benefits making the application faster. W2Ui is only 97kb in size, providing much quicker load time and execution than other JavaScript data libraries on the list. 

One of the most significant advantages of using W2Ui is that it can handle multiple data representation requirements of web applications. Using this JavaScript library, you can also create popups, tables, forms, and sidebars. 

 

5. AnyGrids

Suppose you want a vanilla library for quickly creating interactive JavaScript data tables. It can create data tables from JS arrays, JSON formatted data, and Ajax data sources. AnyGrids is a free JavaScript plugin you can install for your projects using npm or script tag. 

Like other JavaScript data table plugins on the list, it also offers sorting, filtering, and data grouping options. With AnyGrids, you can expand the table rows with custom data render such as bar, pie, or linear sparklines, do column calculations, and create pagination. 

 

6. Backgrid.js

If you want a JavaScript plugin to build semantic data grid widgets that you can easily style, Backgrid is a library you must try. It is a lightweight and modular JavaScript plugin that you can use to create data tables to display data visually. Backgrid.js has options to customize and style the layout of tables, allowing customized API to export data. It is an MIT license, free to use JavaScript data library.

 

7. Handsontable

If you want to create data tables that allow users to have the same experience as MS Excel, Handontable is the JavaScript data library you need to use. It will enable developers to work with rows and columns, much like Excel sheets. It offers one of the most comprehensive APIs of all data table JS plugins. While you can use the library for free for non-commercial purposes, you will need a developer’s license for commercial use. 

 

8. ngx-datatable

When working with complex and large data for an angular web application, you can use ngx-datatable to represent the data in tables. A lightweight and flexible JavaScript data library, ngx-datatable is built for modern web browsers. It offers all basic table functionalities such as sorting, filtering, and paging.

 

9. FooTable

FooTable is a jQuery table plugin that is focused on mobile-friendly data tables. It has no bootstrap involvement and is governed by two principles: hides columns after the declared breakpoint in the CSS and insert expandable rows to reveal data hidden in cells at the breakpoint. It is one of the most basic JavaScript plugins for creating responsive data tables. For styling, you can use bootstrap as it is designed to be compatible with bootstrap grids. 

 

10. KendoReact

A JavaScript data library built for React offers virtualization, globalization, and other table functions such as pagination, filter, group, edit, resize and reorder. There is an option to develop data tables in controlled and uncontrolled mode. It also allows the export of data in Excel and PDF format. It is one of the best JavaScript plugins for data table generation with zero dependencies. We recommend it for React applications because its UI components are 100% optimized for React.

 

Conclusion 

These ten are the most reliable options among the available JavaScript plugins and libraries for data table generation. You can easily create, organize, and process existing data using these libraries and plugins.

Talent500 is trusted by some of the biggest brands to hire, build, and manage their remote teams. Sign up here to join the elite Indian frontend developers pool and get hired by the best companies

Cheat sheet for JavaScript interviews

JavaScript with HTML and CSS is the building block of the World Wide Web. Over 98% of websites use JavaScript as the dominant client-side programming language to control the behavior of web pages. Given its features and capabilities, JavaScript is one of web development’s most popular programming languages.

Any JavaScript interview can go from a preliminary evaluation of your fundamental skills to a comprehensive, in-depth benchmark of your programming skills.

This article includes the ultimate cheat sheet for JavaScript interviews and some commonly required quick, tested, and ready-to-use code snippets.

1. Explore the “this” keyword 

In JavaScript, the “this” is a reserved keyword we cannot use as an identifier. This keyword changes its behavior according to the use case. While the strict mode is set “this” as undefined, you can change its context by using call, apply, and bind functions.

With the call, apply, and bind functions, you can change the behavior of “this” to create a more generic function. Here is an example:

const name = “Hey”function foo() {

   ‘use strict’

  console.log(this.name)

}const context = {

   name: “Hello World!”

}foo.call(context) // Hello World!

foo.apply(context) // Hello World!

foo() // Cannot read properties of undefined (reading ‘name’)

Closely look at the call and apply. While they might seem similar, the former accepts the parameters as individual arguments while the latter expects them as an array. The bind changes the context of “this” and returns a new function.

2. Prototypes

A JavaScript prototype is an object associated with every function and object by default. However, a function’s prototype property is accessible and adaptable in the code, but the object’s prototype property is not visible.

An essential use of the prototype object is to create an ienumerable object to which additional properties can be attached, and it can be shared across all the instances of its constructor function.

Here’s an example code:

// constructor function

function Person () {

   this.name = ‘John’,

   this.age = 23

}

// creating objects

const person1 = new Person();

const person2 = new Person();

// adding property to constructor function

Person.prototype.gender = ‘male’;

// prototype value of Person

console.log(Person.prototype);

// inheriting the property from prototype

console.log(person1.gender);

console.log(person2.gender);

Output:

{ gender: “male” }

male

male

3. Function currying and callbacks

Currying and callbacks are essential processes in JavaScript. We use currying to transform a function with multiple arguments into a sequence of nesting function calls. The outcome of currying is a new function that expects the following statement inline.

A callback is a function that is passed into another function as an argument. Callbacks are first-class action features invoked inside the outer function to complete a particular task.

Code example:

function simpleFunction(param1, param2, param3, …..) => function curriedFunction(param1)(param2)(param3)(….)function calculateVolume(length) {

   return function (breadth) {

     return function (height) {

       return length * breadth * height;

     }

   }

}

console.log(calculateVolume(4)(5)(6)); // 120

4. Higher-order function

JavaScript allows you to pass a series of functions as an argument to another function and return a function. It is achieved through higher-order functions. They are usually used in complex applications where the returned function can consist of multiple properties or constants for further computations.

The higher-order function can be of multiple types, such as:

//Assign a function to a variable originalFunc

const originalFunc = (num) => { return num + 2 };

//Return the function’s body as a string

newFunc.toString(); //'(num) => { return num + 2 }’

//Add our own isMathFunction property to the function

newFunc.isMathFunction = true;

//Re-assign the function to a new variable newFunc

const newFunc = originalFunc;

//access the function’s name property

newFunc.name; //’originalFunc’

//Pass the function as an argument

const functionNameLength = (func) => { return func.name.length };

functionNameLength(originalFunc); //12

//Return the function

const returnFunc = () => { return newFunc };

returnFunc(); //[Function: originalFunc]

5. Patterns

For any JavaScript developer, it is essential to master patterns to optimize their code. JavaScript offers many kinds of patterns, but the most important ones are:

Mixin: this script pattern is used to extend the functionality of an object using list methods.

Factory: a class type that can create one or many different objects. It is dominantly used in unit testing to generate mock data.

Facade: it is used for the abstraction of a complex logic by wrapping it in the class. An example of a facade is the service that stays between the component and API layer.

Singleton: it is a class that can call the method directly without creating any object.

MVC, MVVM: JavaScript also allows the two most commonly used architectural patterns, Model View Controller and Model View ViewModel.

Conclusion 

Given the versatility and scope of JavaScript, it is beneficial to have access to cheat sheets that can help you quickly familiarize yourself with some crucial programming language features. This JavaScript cheat sheet for interviews is just the beginning; many more JavaScript resources exist to explore.

Talent 500 is the platform for JavaScript developers to explore career redefining opportunities with fast-growing start-ups and Fortune 500 companies. Sign up here to know more.

 

Top 6 mistakes made by Javascript developers

JavaScript is an essential technology for front-end development. Websites, mobile applications, and even smart devices use this language. There are several benefits of using JavaScript for development. Websites built in this language are highly responsive, making them accessible on any screen. For mobile applications, JavaScript offers flexibility to integrate complex functionalities. 

Furthermore, hundreds of advanced JavaScript frameworks, libraries, and development tools can benefit the developers. JavaScript is an essential language for web developers. While it is relatively simple, JavaScript developers must be aware of some language pitfalls. This article will detail the top 6 mistakes made by JavaScript developers.

 

1. Incorrect references to ‘this’ keyword

One of the most common JavaScript mistakes is the keyword ‘this.’ Many developers wonder if the ‘this’ JavaScript keyword has the same literal meaning or is something else entirely. As JavaScript has grown sophisticated over the years, several self-referencing scopes within callbacks and closures are introduced into the language. The confusion around this/that keywords is better understood from this example:

Game.prototype.restart = function () {

 

this.clearLocalStorage();

  this.timer = setTimeout(function() {

  

this.clearBoard(); // what is “this”?

  }, 0);

};

 

Running the above code will result in ‘Uncaught TypeError: undefined is not a function error.

In the above code example, the ‘this’ keyword is used to invoke setTimeout(), but it is invoking window.setTimeout(). This is causing the anonymous function using the setTimeout() to be associated with the window object without any clearBoard() method.

A conventional solution experienced JavaScript programmers use to avoid this mistake is to use the ‘this’ keyword regarding a variable; the closure can inherit that. Here’s how:

Game.prototype.restart = function () {

this.clearLocalStorage();

  var self = this; // save reference to ‘this’, while it’s still this!

  this.timer = setTimeout(function(){

  self.clearBoard(); // oh OK, I do know who ‘self’ is!

  }, 0);

};

 

2. Using magic values

Not only in JavaScript but using magic values is a common malpractice in many programming languages. 

A magic value is a constant value that abruptly appears within the JavaScript code, only the developer who wrote the code knows why it is there. 

This makes JavaScript code unmaintainable as no one can understand what that random value represents; even sometimes, the coder who added the value cannot recall the reason. 

For instance, check out this code excerpt:

const specialFn = (r) =>{

  const fnValue= 2*3.1416*r // no idea why this value is used

  return fnValue

}

console.log(specialFn(4))

 

How the code should be: 

const PI = 3.1416

const specialFn = (r) =>{

  const fnValue = 2*PI*r // Calculation for circumference 

  return fnValue

}

console.log(specialFn(4))

This practice must be followed with all methods, functions, variables, and values. 


3. Not “static typing” JavaScript code 

A JavaScript developer should write Static Typed code. A type is a syntax format to write JavaScript code with predefined syntax, hierarchy, and structure. 

Typescript is one of JavaScript’s most popular static typing styles to help programmers write maintainable and quality code. Typescript is a superset of JavaScript, implying it is JavaScript but with some added syntax features. 

When you write static-type JavaScript code, you can easily avoid some of the most common typos and syntax errors.

 

4. Assuming JavaScript has block-level scope

A beginner JavaScript developer can think that the language creates a new scope for each block of code, but it is simply not true. While many other programming languages like Python and Java have this functionality, JavaScript does not offer block-level scope. 

 

For instance, in this code block: 

for (var i = 0; i < 10; i++) {

  /* … */

}

console.log(i);  

What do you assume will be the output here? 

The code will not throw an error or undefined output but will return 10. 

Why? 

In most other languages, this code block will throw an error because the scope of variable ‘i’ would be only within the for loop block. But in JavaScript, there is no such restriction and the variable ‘i’ remains in scope outside the for loop. 

 

5. Anomalous behavior of Boolean Functions 

One of the advantages of JavaScript is that it automatically coerces any value referenced in a Boolean context into a Boolean value. But this convenience comes at a cost for JavaScript developers. Let’s see how. 

// All these statements are True

console.log(false == ‘0’);

console.log(null == undefined);

console.log(” \t\r\n” == 0);

console.log(” == 0);

// And these do too

if ({}) // …

if ([]) // …

 

But the last two statements are empty, which any developer will intuitively think to return false, but as both {} and [] are coerced to a Boolean value in JavaScript, they will return True.

 

6. Not using “strict mode”

The “strict mode” in JavaScript is voluntary to ensure better quality code by enforcing stricter parsing and error handling. It also makes the code more secure. While not using strict mode is not a “mistake” per se, it is a practice that makes you a better JavaScript developer. 

The strict mode JavaScript code prevents accidental globals, makes debugging more manageable, and makes eval() safer. 

 

Conclusion 

Being a proficient JavaScript developer is not only about learning the language’s concepts but also about being familiar with the common mistakes and best practices. It helps write concise and quality JavaScript code.

Talent500 is a platform for JavaScript developers to get career redefining opportunities with some of the best companies. Join us here.

4 advanced JavaScript tips & tricks for programmers

JavaScript is responsible for all the interactivity on a webpage. The language enables web browsers to create a dynamic and interactive user experience. Companies use JavaScript to develop robust and highly efficient frameworks and systems.

It is why the demand for JavaScript developers is high. But to be a proficient JavaScript developer, you must learn how to write optimized JavaScript code. Optimized code combines cleverly programmed logic and a few tips and tricks to improve the performance and speed of code execution.

Here are some advanced JavaScript hacks for programmers to optimize and improve the performance of their JS code.

1. Use array filter 

In JavaScript, you often need to use arrays. This little hack will allow you to bucket out elements from the array pool based on a preset condition that you pass as a function. You can create a callback function for non-required elements according to the use case.

Here is an example where we separate the null elements from the other aspects of the array.

schema = [“hi”,”Hello World!”,null, null, “goodbye”]

schema = schema.filter(function(n) {

 return n

 });

Output: [“hi”,” Hello World!”, “goodbye”]

This JavaScript trick will save you time and some lines of code while improving the performance of the code.

2. Using length to delete empty in an array

While you can resize and empty an array, the conventional way of writing a dedicated function works on the array, but there’s a more thoughtful way to achieve this.

You can achieve the same goal by use of array.length.

Here is an example to delete n elements using array.length.

array.length = n

code:

var array = [1, 2, 3, 4, 5, 6];

console.log(array.length); // 6

array.length = 3;

console.log(array.length); // 3

console.log(array); // [1,2,3]

You can also use the array.length to empty the array using array.length = 0, like this:

Example:

var array = [1, 2, 3, 4, 5, 6];

array.length = 0;

console.log(array.length); // 0

console.log(array); // []

It is the most preferred way to resize/unset an array, and experienced programmers use it to ensure that their code is optimized and there are no stray elements in the array.

3. Nested ternary operator

We can simplify the use of multiple conditional expressions in our JavaScript code with the use of nested ternary operation.

condition: ? expressionIfTrue : expressionIfFalse

instead of

if else-if else.

The problem with using too many if else-if else in the JS code is that the complicated nesting not only increases the execution time, such code is not clean and is hard to read and maintain.

Let’s understand the nested ternary operator with an example.

Support you have a blog home page where you want to itemsPerPage number of posts per page. Now here are three scenarios that are possible:

  • If the number of articles is less than the itemsPerPage, the value of the pages variable should be 1.
  • If the number of articles is more than the itemsPerPage, then the value of our pages variable should be equal to the itemsPerPage.
  • If the number of articles is less than the itemsPerPage, the value of our pages variable should be the same as the number of pages.

This can be easily implemented with a nested ternary operator like this:

const articles = Array.from({ length: 120 }, (_, index) => index);

const paginate = (items, itemsPerPage = 10) => {

  const pages =

   itemsPerPage > items.length

    ? 1

    : Math.ceil(items.length / itemsPerPage) > itemsPerPage

    ? itemsPerPage

    : Math.ceil(items.length / itemsPerPage);

  return Array.from({ length: pages }, (_, index) => {

   const start = index * itemsPerPage;

   return items.slice(start, start + itemsPerPage);

  });

};

console.log(paginate(articles));

4. Easy way to invert an integer 

One of the most commonly asked JavaScript questions in interviews is how you can reverse a positive or negative integer within reasonable limits.

It’s not just a tricky JavaScript question but also has applications in the real world, like in eCommerce and wallet applications.

First, you can check if the input is within the valid limits. If it is, then we take the absolute value of input and divide it by the integer 10 in each loop until the number is zero. We store the last digit of the number in each loop. Then we multiply each value by 10 and add it to the last digit. This is how we reverse the given integer.

Here’s the code:

const reverseInteger = (input) => {

  const checkNumber =

   input > 2 ** 31 || input < -(2 ** 31) || typeof input !== ‘number’;

  if (checkNumber) return 0;

  let number = Math.abs(input);

let result = 0;

  while (number !== 0) {

   let lastDigit = number % 10;

   result = result * 10 + lastDigit;

   number = Math.floor(number / 10);

  }

return input < 0 ? -result : result;

};

console.log(reverseInteger(15345345345534534535334523));

console.log(reverseInteger(-15345345345534534535334523));

console.log(reverseInteger(123));

console.log(reverseInteger(‘123’));

console.log(reverseInteger(-456));

console.log(reverseInteger(0));

But there is an easier way to do the same. We can convert number to string and do all the operations with strong methods, like this:

const reverseInteger = (input) => {

  const checkNumber =

   input > 2 ** 31 || input < -(2 ** 31) || typeof input !== ‘number’;

  if (checkNumber) return 0;

const reversedInteger = parseInt(

  Math.abs(input).toString().split(”).reverse().join(”)

  );

return input < 0 ? -reversedInteger : reversedInteger;

};

console.log(reverseInteger(15345345345534534535334523));

console.log(reverseInteger(-15345345345534534535334523));

console.log(reverseInteger(123));

console.log(reverseInteger(‘123’));

console.log(reverseInteger(-456));

console.log(reverseInteger(0));

Conclusion 

Start improving your JavaScript skills with these optimizations. As you gain experience, you will learn more ways to optimize your code.

Talent500 is the platform for Indian developers to explore global job opportunities. Sign up here and get discovered by Fortune 500 companies and the best startups.

 

5 useful JavaScript hacks for developers in 2022

Front-end development uses multiple technologies, but JavaScript is at the core of all front-end projects. Websites and apps depend on JavaScript for dynamic content generation and interactivity. The programming language empowers over 98% of the internet, which is why it’s a great addition to your resume.

As JavaScript rapidly evolves, front-end developers must keep track of the new features and libraries. In this article, we list incredible JavaScript hacks that you can use to improve your code.

1. Nullish coalescing operator (??)

Introduced in the ES2020, the ?? operator is called the Nullish coalescing operator. It works the same as the || operator and is used to determine that the value to the operator’s left is null or undefined before returning it to the right.

While the behaviour of the ?? operator is similar to the || operator, but it’s stricter. The || operator takes the right operant in the case of false values such as False or 0. The nullish coalescing operator (??) takes the right value only when the left side is set to null or undefined. Therefore, 0 || 1 will return 1 while 0 ?? 1 results in 0.

Here’s an example:

const response = {

  settings: {

   nullValue: null,

   height: 400,

   animationDuration: 0,

   headerText: ”,

   showSplashScreen: false

  }

};

const undefinedValue = response.settings.undefinedValue ?? ‘some other default’; // result: ‘some other default’

const nullValue = response.settings.nullValue ?? ‘some other default’; // result: ‘some other default’

const headerText = response.settings.headerText ?? ‘Hello, world!’; // result: ”

const animationDuration = response.settings.animationDuration ?? 300; // result: 0

const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false

Apart from Internet Explorer, all modern web and mobile browsers support ?? operator.

2. On-demand loading import modules using dynamic import ()

JavaScript allows loading dependencies using the import statement initialization like this:

import defaultExport from “module-name”;

import * as name from “module-name”;

//…

However, using such static import statements that depend on the type = “module” script tag has several drawbacks, such as:

A statically imported module can slow down the loading or execution of the code

It can take up a lot of system memory

It loads every time even when it is required less frequently

One programming hacks to use here is to load modules on-demand based on conditions. It can be used when the statically imported module is not needed immediately or only when certain conditions are triggered.

You can use the dynamic introduction of import () in JavaScript functions and classes. There are two forms to import modules dynamically:

// Form 1

import(‘/modules/my-module.js’)

 .then((module) => {

 // Do something with the module.

 });

 // Form 2

let module = await import(‘/modules/my-module.js’);

3. Replace substrings faster with String.prototype.replaceAll() 

JavaScript developers often use dynamic functions where they have to replace a string or part of a string. The traditional way is to use the String.prototype.replace() method to replace substrings, but it is not efficient. This method only replaces the first occurrence of the substring and not all.

Another important JavaScript hack is to use the String.prototype.replaceAll() method for replacing substrings. It replaces all the occurrences of a substring in the entire code.

Here is an example of the use of String.prototype.replace() and String.prototype.replaceAll() methods to replace all a with Ahui:

// before

console.log(‘a’.replace(/a/g,’Ahui’)) //a

// After simplification

console.log(‘a’.replaceAll(‘a’,’Ahui’)) //Ahui

4. Use Proxy instead of Object.defineProperty

In JavaScript, Object.defineProperty is the static method used to define a new property directly on an object or modify the existing property and return the object. However, one helpful JavaScript hack is to use Proxy instead of Object.defineProperty.

Here are the benefits of using Proxy instead of Object.defineProperty:

  • While Object.defineProperty can proxy only a particular property of an object, the Proxy can proxy the whole object.
  • Unlike Object.defineProperty, Proxy can listen to the new properties added to an object.
  • Object.defineProperty needs to do all the recursions once when all the properties inside the object are to be recursively proxied. However, a Proxy can only be recursive when called. It is not ideal but much better than Object.defineProperty.
  • A proxy can listen to the changes made to an array, but Object.defineProperty cannot.

Here is an example of how to use Proxy:

function reactive(obj) {

  return new Proxy(obj, {

   get(target, key) {

    // Can do dependency collection

    track(target, key)

    return target[key]

  },

  set(target, key, val) {

    target[key] = val

    // trigger dependency

    trigger(target, key)

  }

  })

}

The proxy method acts as a constructor that takes two arguments to generate an object from scratch – a target and a handler.

5. Convert an if/else into a one-line 

The most common practice of using an if-else statement in JavaScript is like this:

if (1 < 2) {

console.log(“True.”);

} else {

console.log(“False”);

}

But there is a powerful programming hack to achieve the same result using a ternary operator and to simplify the code.

Here’s the same code using a ternary operator:

1 < 2 ? console.log(“True.”) : console.log(“False.”);

The ‘:’ is the syntax for the ternary operator and is written like this:

condition ? exprIfTrue : exprIfFalse

Conclusion

We hope these five JavaScript hacks will help you be more productive. They can help you make your JavaScript code much more concise and cleaner. Here are some more JavaScript resources from our blog.

Talent500 is where talent meets opportunity. Join us today to find career-redefining job opportunities with global companies.

 

5 common mistakes to avoid when using React in 2022

Since Facebook released React in 2013, it has become one of the most widely used JavaScript frameworks. According to Statista, React is the world’s second most used web development framework. As the popularity of JavaScript remains high, React utilizes its capabilities to provide the most comprehensive tool sets to build web and mobile applications.

As a React developer, you have the opportunity to be part of a technology that has immense growth potential shortly. More and more web developers are adopting this JavaScript framework. Backed by Facebook and a vast developer community, React is a framework to master if you want to become a web developer.

However, there are some common mistakes that you must avoid. Here we take a look at the most common React mistakes developers commit.

1. Not creating enough components

A common mistake any React developer can make is not creating enough components. React is a highly versatile language, and if you are creating a few significant components, you’re missing its reusability. While it is not wrong to produce large components that execute many tasks, it is recommended that you create smaller components, more preferably, one component corresponding to one function. This approach saves time and is a significant benefit when debugging the code. Any errors can be easily spotted as you know which components are associated with which functions.

Here is an example of a TodoList component broken down to single functions:

// ./components/TodoList.js

 import React from ‘react’;

 import { useTodoList } from ‘../hooks/useTodoList’;

import { useQuery } from ‘../hooks/useQuery’;

import TodoItem from ‘./TodoItem’;

import NewTodo from ‘./NewTodo’;

const TodoList = () => {

  const { getQuery, setQuery } = useQuery();

  const todos = useTodoList();

  return (

   <div>

    <ul>

     {todos.map(({ id, title, completed }) => (

      <TodoItem key={id} id={id} title={title} completed={completed} />

     ))}

     <NewTodo />

    </ul>

    <div>

     Highlight Query for incomplete items:

     <input value={getQuery()} onChange={e => setQuery(e.target.value)} />

    </div>

   </div>

  );

};

 export default TodoList;

2. Modifying the state directly

Another common mistake React developers commit is modifying the state directly. As a rule of thumb, in React, the state must always be immutable; otherwise, there will be performance issues that will be difficult to fix.

Here’s a code:

const modifyPetsList = (element, id) => {

  petsList[id].checked = element.target.checked;

setPetsList(petsList);

};

Here we want to update the checked key of an object in the array based on the state of the checkbox, but there is an issue. React cannot observe and trigger the re-rendering of the object because it has been changed with the same reference.

Either you can use the setState() method or the useState() hook to fix the issue. These methods will ensure that React acknowledges the changes made to the object and that your DOM is correctly re-rendered.

3. When rendering the list, do not use the key

If you are a beginner or used our React developer toolkit to learn the language, you must have come across the prompt when you render a list according to the method described in the documentation.

For example, rendering these arrays:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number) => <li>{number}</li>);

will display this prompt on the console “a key should be provided for list items.”

The solution is obvious here. We have to follow the prompts and add the key attribute to each item like this:

const numbers = [1, 2, 3, 4, 5];

const listItems = numbers.map((number, index) => <li key={index}>{number}</li>);

The key helps React identify which elements have changed, which is why you need to assign a unique value to the key. In the above example, we have used the index as the key value.

However, we do not recommend you to use the key and ignore the prompt.

This is because the value of the key will change every time an item is added or removed from the array. It will result in performance degradation.

4. Using Redux too much

Redux is becoming very popular among React developers, primarily working on large apps. It is helpful as it helps manage global state, but you don’t have to use it to manage every state in your React apps.

If your applications do not use parallel-level components that need to exchange information, then there is no need to use Redux. Instead, you should use a local state method or useState when you use form components or want to check the state of an element every time it is accessed.

5. Incorrect use of boolean operators

In JSX/TSX syntax, React developers often use boolean values to control rendered elements utilizing the && operator like this:

const count = 0;

const Comp = () => count && <h1>Chris1993</h1>;

While we want that page to display empty content at this time, it will actually display 0 on it.

The error is because the falsy expression causes elements after && to be skipped. However, the value of the falsy expression is returned.

The correct way to write the condition without relying on the JavaScript’s boolean value to compare:

const count = 0;

const Comp = () => count > 0 && <h1>Chris1993</h1>;

Now the page will display empty content.

Conclusion 

Now that you have learned some common React mistakes, keep them into account when creating your next React app. Gradually you can inculcate these best practices and soon they will become a learned behavior and improve your code quality.

And if you are an experienced React developer, join Talent500. We are a global remote team-building platform that Fortune500 companies and fast-growing startups use to hire talent.

 

5 most frequently asked JavaScript interview questions

JavaScript is the core of front-end development. JavaScript interview questions are asked to gauge the technical abilities of front-end developers. If you plan to start your career as a front-end developer, you are up for an exciting domain that frequently witnesses innovations and technological advancements.

Your skills as a front-end developer will be tested on how well versed you are with JavaScript. In this article, we are sharing the most frequently asked JavaScript interview questions.

1. What is the drawback of using a bar with typeof bar === “object” to determine if bar is an object? How can the drawback be avoided?

While typeof bar === “object” is a reliable way of checking if bar is an object, the problem arises because null is also considered an object in JavaScript.

That’s why the following code will return true, unlike most JavaScript developers anticipating it to return false.

var bar = null;

console.log(typeof bar === “object”); // logs true!

As long as you are aware of this nature of JavaScript, you can easily avoid the problem by proactively checking if bar is null:

console.log((bar !== null) && (typeof bar === “object”)); // logs false

This statement eliminates the problem, but the important point is to know that the above solution will return false if the bar is a function. In most cases, it is a required behavior, but if you want to return true for functionals, you can make a change like this:

console.log((bar !== null) && ((typeof bar === “object”) || (typeof bar === “function”)));

2. What will be the output of the following code, and why?

var myObject = {

   foo: “bar”,

   func: function() {

     var self = this;

    console.log(“outer func: 

this.foo = ” + this.foo);

    console.log(“outer func: 

self.foo = ” + self.foo);

     (function() {

      console.log(“inner func: 

this.foo = ” + this.foo);

console.log(“inner func: 

self.foo = ” + self.foo);

     }());

   }

};

myObject.func();

This is another commonly asked JavaScript interview question. The output of the code will be:

outer func: this.foo = bar

outer func: self.foo = bar

inner func: this.foo = undefined

inner func: self.foo = bar

In the outer function, myObject is referred to by both this and self, which is why both can adequately refer to and access foo. While, in the inner function, this no longer refers to myObject and results in undefined output. However, the reference to the local variable self remains in scope and therefore is accessible.

3. What is a scope, and what are its types? 

In JavaScript, a scope determines how an object, a variable, or a function can be accessed in a particular section of your code. 

Scopes are of two types in JS: 

  • Global scope: It is defined outside the function and can be accessed from any code section. For example: 

var name = ‘LambdaTest’;

console.log(name); // logs ‘LambdaTest’

function newLogName() {

console.log(name); // ‘name’ is accessible here and everywhere else

}

newLogName();

  • Local scope: Here, variables are defined inside the function, scoped in the function only, and cannot be used outside. 

// Global Scope

function sampleFunction() {

// Local Scope #1

function oldFunction() {

// Local Scope #2

}

 }

// Global Scope

function newFunction() {

// Local Scope #3

}

// Global Scope

4. What will be the output of the code below ? Explain your answer

console.log(0.1 + 0.2);

console.log(0.1 + 0.2 == 0.3);

This developer interview question is a bit tricky to answer. You can’t be sure of what the outcome will be. The code might print out 0.3 and true, or it might not. The reason being in JavaScript, all the numbers are treated as floating point precision which is why they may not always output the expected result.

The above example is a classic case of how JavaScript handles numbers. The code will surprisingly print:

0.30000000000000004

false

The easiest solution to this problem is to use a special constant Number.EPSILON to compare the absolute difference between two numbers:

function areTheNumbersAlmostEqual(num1, num2) {

       return Math.abs( num1 – num2 ) < Number.EPSILON;

}

console.log(areTheNumbersAlmostEqual(0.1 + 0.2, 0.3));

5.What is prototype property?

Prototype property in JavaScript is used for implementing inheritance. Each function in JS has a default prototype property value which is null. Methods and properties are added to the prototype to make it worthwhile for the instances. This is how a JavaScript function is made robust and available for multiple instances. 

This JavaScript interview question is better explained with the following code to calculate the perimeter of a rectangle: 

function Rectangle(x, y) {

this.x = x;

this.y = y;

}

Rectangle.prototype.perimeter = function() {

return 2 * (this.x + this.y);

}

var rectangle = new Rectangle(4, 3);

console.log(rectangle.perimeter()); // outputs ’14’

Conclusion 

These are some critical JavaScript interview questions that you must understand. JavaScript is an essential language for developers. Beginners can start learning JavaScript from these websites.

Talent500 helps developers find the best opportunities with global companies. Sign up today and get ready to be discovered by the best companies.

 

5 beneficial one-line codes for JavaScript

JavaScript is undoubtedly the crucial pillar of web development. If you build all the functionalities in your web applications using JavaScript from scratch, then you need to know some syntax and built-in methods. These JavaScript one-liners are highly functional and can quickly reduce the number of lines in your code.

In this post, we are exploring the simple JavaScript one-line code statements that can simplify your code to a great extent. Let’s look at the most commonly used JavaScript one-liners.

1. Shuffle array

One of the developers’ most important JavaScript skills is working with arrays. You will often have to shuffle the array for several applications like eCommerce product sorting, database management, and random number generation. You don’t need to use iterations and for loops to shuffle an array every time. It can be done with this JavaScript one-liner:

const shuffleArray = (arr) => arr.sort(() => Math.random() – 0.5);

The code has a complexity of O(n log n), which makes code execution faster.

Example code:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(shuffleArray(arr));

2. Detecting dark mode 

Nobody can question the rising popularity of dark mode. It is a recommended feature for apps on devices that support dark mode. If you have wondered how developers can achieve this functionality, the following single-line JavaScript code makes it a walk in the park. You can easily detect dark mode with this code:

const isDarkMode = () => 

window.matchMedia && window.matchMedia(“(prefers-color-scheme: dark)”).matches;

In practical application, this method is used as follows:

console.log(isDarkMode());

Unlike other methods of detecting dark mode in JavaScript, the matchMedia method is most widely supported. It has 97.19% support on all modern browsers.

3. Generate random color 

If your JavaScript application uses random color generation, you no longer have to rely on long and tedious functions to generate colors. You can achieve the same functionality with an inbuilt JavaScript function called generateRandomHexColor.

Here’s how you can use the code:

const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;

It is also one of the most commonly used JavaScript one-liners, making it much easier to generate colors randomly without needing to separate function calls. It is also a much more efficient way to achieve the goal.

4. FizzBuzz

Often asked as a tricky JavaScript interview question, the challenge here is to print numbers from 1 to 100, but for all the multiples of 3, the program must print “Fizz,” and for all the multiples of 5, it should print “Buzz.”

Believe it or not, achieving the goal with a JavaScript one-liner is possible.

for(i=0;++i<10;console.log(i%5?f||i:f+’Buzz’))f=i%3?”:’Fizz’

It is often asked in the interview to evaluate a JavaScript developer’s understanding of the concepts to the core.

Example output of the above code:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

5. Removing duplicates in an array 

One of the unique features of JavaScript is that it only stores special items in the sets. This feature can be advantageous for developers who can use it to remove duplicate entries in an array. However, it is essential to note that this method only works for sorting primitive data in an array. 

While for more complex applications, you might have to write multiple lines of code to remove array sorting objects with duplicate values, for more straightforward applications, you can use this single line of JavaScript code to remove duplicates.

const removeDuplicates = (arr) => […new Set(arr)]

Here’s the code in action:

removeDuplicates([31, 56, 12, 31, 45, 12, 31])

//Output

[ 31, 56, 12, 45 ]

6. Copy to clipboard 

For web applications, copy to clipboard is an expected feature, especially if they are data-driven. It allows users to share text from one application to another conveniently. You don’t need to write fancy functions. JavaScript has inbuilt functionality to achieve the same. Just use this JavaScript one-liner:

const copyToClipboard = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text);

// Using it in your code:

copyToClipboard(“Hello World!”);

An important point to note here is that this method currently works for 93.08% of global users, which is why you must check the browser compatibility of your end users before using this API.

7. Detecting a palindrome 

In JavaScript, palindromes have useful applications such as DNA marking, biological sequencing, and compression algorithms. While all these uses may require you to write hundreds of lines of code to be effective, for easy use, you can detect a palindrome by using this line of code:

const isPalindrome = str => str === str.split(”).reverse().join(”);

Here’s an example code:

result = isPalindrome(‘abcba’);

console.log(result)

//Output

true

result = isPalindrome(‘abcbc’);

console.log(result)

//Output

false

Conclusion 

Hope we have helped you become a better programmer by sharing these clever JavaScript online liners. There are many more such tricks that you will learn as you get experience, but the above ones will get you started.

Talent500 is the platform for JavaScript developers to find the best career opportunities. Sign up here to know more.