6 VS Code extensions to boost productivity as a React developer

Every developer wants to write better code quicker. Unfortunately, keeping the code clean and clear is difficult, especially when working with a JavaScript framework like React. Importing, concatenating, and refactoring code requires formatting and reorganizing. It slows down the React developers and affects their productivity. Fortunately, there are ways to work more efficiently by following predefined rules for structuring the project, components, write styles, and test functions.

The VS Code is one of the most widely used IDE or code editors from which React developers can benefit. As some tremendous VS Code extensions are available, it is easier for developers to automate several parts of the coding process that boost their productivity.

We share some of the best VS Code extensions you can use to write cleaner code much quicker.

1. Settings Sync

Before you start creating a more productive environment by installing extensions left and right, you must ensure you can take the VS Code settings to the device you use.

Settings Sync is the VS Code extension you must install to ensure that every customization you make to the VS Code can be synced to GitHub. It can sync everything from settings, and keyboard shortcuts, to VS Code extensions.

With this extension installed, you can access your preferred IDE from any device you want without losing the settings or extensions. It saves much time as you don’t have to manually set up the development environment from scratch on a new device.

2. Prettier and Eslint

The two VS Code extensions that every React developer must use are the Prettier and Eslint. These tools help you write a cleaner and well-formatted code and check it for common mistakes.

Prettier is a formatter that organizes your JavaScript code in an easy-to-read and maintained format. You can download it directly from the VSCode marketplace library here. Eslint is a linter that automatically catches and fixes coding errors like missing ; or }. This linter is available here.

After download and installation, you can create two config files (.prettierrc and .eslintrc.JSON) to define the rules of how your code should look or how to check it for errors. If you are using other plugins for code formatting or linting, you have to define them in the eslint config file to ensure that there are no conflicts. These extensions highlight the errors within the code so that you can easily format or correct the errors they can’t.

3. VS Code React Refactor

Code refactoring is a common task when you are working on a project and want to change an existing function. With VS Code React Refractor, you can easily select the code lines you want to refactor, and this VS Code extension will extract those lines into a new component.

It is one of the best extensions to refactor your React code or create new components based on predefined templates. You can install this extension directly from the VS Code marketplace. Another reason to use this refactor plugin is to accelerate the coding process without spending too much time trying to format or create new components.

4. Bracket Pair Colorizer

It’s pretty evident why this VS Code extension is a popular choice of coders. This VS Code extension gives the opening and closing brackets matching colors, making it much easier to debug the code. You can install the extension from here.

It also makes the code much more readable as it is easier to understand which brackets belong together. You can further extend the functionality of the Bracket Pair Colorizer by configuring custom bracket characters to add a background color to highlight the active scope enclosed within brackets.

5. GitLens

While using Git as a standalone tool in combination with VS Code is an obvious move, with GitLens, you can supercharge the functionality of Git for VS Code and access a lot of untapped information regarding repositories directly from the IDE.

You can easily view who, how, and why lines of code have changed over time. Furthermore, it also allows you to view code authorship using Git blame annotations and CodeLens. This VSCode extension is a must if you work on collaborative code. It offers rich visualizations, powerful comparison commands, and the ability to customize any setting as per your project requirement. Install GitLens from here.

6. ES7+ React/Redux/React-Native snippets

You can install this VSCode extension here. It is a great plugin with React, React Native, and Redux that use ES7+ syntax. This extension can create any element – new components, functions, classes, methods, and more. Furthermore, it makes it easier and faster to write hooks like useEffect and useCallback. ES7+ React/Redux/React-Native snippets are highly customizable and inherently support Prettier.

Conclusion 

We hope these VS Code extensions will help you significantly boost your productivity without impinging your code quality. Not just React developers, but JavaScript developers working with other frameworks can also use these extensions.

For more resources, you can refer to our React developer toolkit, which lists several learning and upskilling resources for React developers. You can also join our elite pool of talent here to find the best job opportunities.

 

4 tips to transition from beginner to an intermediate frontend developer

Let’s say you’ve built a few web apps and websites. Now you have mastered the basics of HTML, CSS, and JavaScript. Technically, you are not a beginner frontend developer anymore, but also not at a stage where you can be labeled as an intermediate developer.

You might be wondering about what it takes to transition to an intermediate front-end developer role at this junction. We will focus on that in this article– a roadmap to becoming an intermediate developer when you are in a junior developer role.

Let’s get started.

1. Stop being dependent on third-party code 

When you start as a beginner frontend developer, you might have used third-party libraries, frameworks, and plug-ins in your projects. There is no harm in using third-party resources in your project, but from a learner’s perspective, they limit your understanding of a project.

The first step towards transitioning into an intermediate frontend developer role is to minimize third-party code use. This will force you to work on creating reusable code blocks and have an in-depth understanding of application elements like APIs, manipulating DOM, and handling requests. This approach will slow down your productivity. 

However, the goal here is not to build things faster but to focus on understanding every fundamental building block of front-end development. Before you use any library or plug-in for functionality, try making the same with vanilla code. Once you can build components from scratch, you will find that it is infinitely easier to work on any development project without relying much on assistance from senior developers.

Learn more about becoming a better programmer ASAP.

2. Learn regex

A crucial skill for intermediate frontend developers is regex. To take a mid-level developer job, you have to learn the regex of your language of choice. It is a skill that will open a new world of opportunities such as web scraping, data filtering, data analysis, and many more. Another use of learning regex is that it allows you to write complicated logic for strings. That’s how you can create much more compact string functions.

In web development, regex is commonly used for various applications such as form validation, verifying the format of strings, and data extraction.

The general syntax for a regex expression is something like this:

/<tag(.*?)>|<\/tag>/gi

Here (.*?) it is used to capture a group of strings that will match any content between the tag. The () creates the capture group while ‘.’ is used to match any special character while the * matches the previous character and ? tells *the minimum number of times it should match the characters.

The ability to do things faster is something employers expect from an intermediate front-end developer. Learning regex will allow you to find and change strings and code in any IDE much quicker. There are many resources on the internet to learn the regex , but we recommend Mozilla’s regex cheat sheet.

3. Avoid assuming your way is the only correct way

The only way to future-proof your career as a frontend developer is to keep learning and adopting new technologies and developments as they happen. While it is not a good idea to be distracted by new things all the time, you must keep a close eye on trends and updates in your industry to ensure you are not falling behind the competition.

As a developer, you have to be on the lifelong learning path. It is why you must not be rigid and believe there is only a particular way of doing something. Being open and adaptable is a quality that will make your transition to an intermediate or a senior developer role easier.

There is no ultimate technology in frontend development. Whether it’s JavaScript, PHP, Angular, React, TypeScript, Ruby, or any other programming language, they all have upsides and downsides. If you fall into the trap of believing that your way of doing things is the only correct way, you will ignore a more efficient way of solving problems. This will affect your growth and promotion to a senior level.

4. Be patient, and practice often

It is a common mistake that beginner front-end developers commit. They assume that moving to an intermediate developer role will reduce the workload. As a developer, you will always be tasked with building stuff. The only difference will be how efficiently and quickly you do the same things as you start gaining experience. For instance, a beginner frontend developer working on a massive website will likely use JavaScript frameworks like React and server-side cache scripting to boost the website’s performance. However, an intermediate frontend developer will achieve the same by utilizing a headless CMS to generate static HTML webpages that load instantly.

Programming is not a sprint but a marathon. To become a competent developer, you must accept that the more you know, the more you will realize how little you know. Trying new things and refining your technique is the sure shot at gradually moving to the intermediate developer position.

Conclusion

Intermediate frontend developers are tasked with almost the same assignments as beginner developers, but they have the additional responsibility of being self-driven. To transition from a beginner’s level to an intermediate level, you must practice and develop skills to tackle even more significant problems with minimal supervision.

Talent500 is the platform for Fortune 500 companies and fast-growing start-ups to hire top-notch developers. Sign up here to join our pool of talent.

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.

 

3 useful tips to clean up your React component types

React is created by Facebook to allow developers to have control over all the functions of JavaScript and have the freedom to code in any style. However, developers must follow some common patterns and conventions for reusability and maintainability. Writing clean React component code is a standardizing technique for a unified project structure.

React Components are independent and reusable bits of code that help make the code much more concise. They are similar to JavaScript functions, the only difference being that they work in isolation and return HTML. As a React developer, you will use the React component library often to write code faster and more efficiently.

This post looks at some of the best practices for writing clean React component types.

1. Write React components in TypeScript

TypeScript offers a type interface allowing developers to write better code without worrying about explicitly defining each variable type. It is the property of TypeScript to infer the style of the variable from its value. In the context of a React component, it can be used to write code without explicitly defining the variable type in the codebase. It helps clean up the component codebase.

Here is an example of how TypeScript can infer the return type of the React components without explicitly defining it; the resulting code is cleaner.

// Letting TypeScript inferring the type: (props: MyProps) => JSX.Element

const MyComponent = (props: MyProps) => <div>beep</div>;

// Explicitly defining a return type (3 similar options of writing the same as above)

const MyComponent = (props: MyProps): ReactElement => <div>boop</div>;

const MyComponent = (props: MyProps): JSX.Element => <div>boop</div>;

const MyComponent: FC<MyProps> = (props) => <div>boop</div>;

Some developers argue that using TypeScript to allow React component code to infer the return type can be risky. It is possible in more dynamic systems, so it is advised to check the inferred type to avoid making mistakes.

Since the release of React hooks in version 16.8, components can be written as functions because you can get the same functionality with much less code. The React.FC type from the @types/react package is used to mark a function as a component.

2. Use maps over if/else

When creating React components try to use maps over if/else statements wherever possible. The if/else statements create nesting within the code that makes the codebase challenging to read or maintain.

React component code can be greatly simplified with maps, and nesting can be avoided. Here is an example of a component using if/else:

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

export default function SampleComponent({ user }) {

   let Component = Student;

   if (user.type === ‘teacher’) {

     Component = Teacher

   } else if (user.type === ‘guardian’) {

     Component = Guardian

   }

 return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

The same React component when written using maps, the complexity of the code eases. Here’s how:

import React from ‘react’

const Student = ({ name }) => <p>Student name: {name}</p>

const Teacher = ({ name }) => <p>Teacher name: {name}</p>

const Guardian = ({ name }) => <p>Guardian name: {name}</p>

const COMPONENT_MAP = {

   student: Student,

   teacher: Teacher,

   Guardian: Guardian

}

export default function SampleComponent({ user }) {

   const Component = COMPONENT_MAP[user.type]

return (

     <div>

      <Component name={user.name} />

     </div>

   )

}

When you use maps, the components become more declarative and much easier for any developer to comprehend. Furthermore, it makes it easy to extend the logic or add more items to it.

3. Split larger components 

One of the best ways to write cleaner React components is to use the ‘separation of concern‘ method to split more significant components. In the context of React components, the separation of concern implies separating the parts of the components responsible for displaying the element tree from the ones responsible for fetching and mutating the data.

The hooks were introduced in React to facilitate separation of concern and allow developers to write cleaner code. In practical applications, it is used for wrapping the logic that manages API calls or global state connections with a custom hook.

Here’s an example of React component:

import React from ‘react’

import { someAPICall } from ‘./API’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const [data, setData] = useState([])

useEffect(() => {

    someAPICall().then((result) => {

      setData(result)

     })

   }, [])

function handleDelete() {

    console.log(‘Delete!’);

   }

function handleAdd() {

    console.log(‘Add!’);

   }

const handleEdit = () => {

    console.log(‘Edit!’);

   };

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

<div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Now, the same component is refactored with the code split using custom hooks:

import React from ‘react’

import ItemDisplay from ‘./ItemDisplay’

export default function SampleComponent() {

   const { data, handleDelete, handleEdit, handleAdd } = useCustomHook()

return (

     <div>

      <div>

        {data.map(item => <ItemDisplay item={item} />)}

      </div>

      <div>

        <button onClick={handleDelete} />

        <button onClick={handleAdd} />

        <button onClick={handleEdit} />

      </div>

     </div>

   )

}

Conclusion

As a React developer, understanding the ways of creating clean components enable you to write cleaner, readable, and maintainable code. It is one of the qualities we use to vet React developers when they join Talent500. For more React developer resources, check out this React developer toolkit.

We are a global remote team building platform startups, and Fortune 500 companies use. If you want to explore opportunities, join us here.

 

 

Important things every budding front-end developer should know

When you use a website or a mobile app, everything you see and interact with falls within the domain of front-end development. The role of a front-end developer is to design the look and feel of the application or website. It includes everything from interactivity, buttons, fonts, and colors to the general layout.

As a front-end web developer, you will be charged with creating a user experience as friendly and enticing as it can be across various platforms, browsers, and devices. And to achieve this goal, you will work with a combination of design, programming languages, and tools.

What are the everyday tasks of a front-end developer? 

The front-end development role demands creativity, technological intelligence, and emotional intellect to create interfaces that add value to the user experience. In this role, you will be tasked with:

  • Designing and overseeing the user experience of a website or an app
  • Use technologies like HTML, CSS, and JavaScript to create front-end
  • Include modern design patterns in your designs
  • Maintain and update UI/UX interfaces you design
  • Develop tools that can improve the website or app interaction
  • Test and debug code

More advanced tasks such as API creation, CSS preprocessors, and cloud-based CDN are added to the responsibilities as you progress in your role.

What do interviewers expect from a junior front-end developer?

While interviewing a junior front-end developer, interviewers do not expect them to know everything. For a junior position, you won’t have to possess the depth of knowledge but the skills that show your creativity and ability to adopt technology and deliver solutions. Usually, employers look for the following traits in a junior front-end developer:

  • Confidence in building simple things
  • Ability to effectively break more significant problems into smaller ones
  • Utilize Google to find optimum solutions for more minor problems
  • Willingness to learn and commitment to work hard
  • Knowledge of essential front-end technologies to start projects
  • Ability to continue making progress in chunks

You must also know data structures and algorithms when interviewing with project-based companies. To learn more, check out top interview questions for front-end developers.

Skills every front-end developer must have 

Level 1: Basic programming skills

Three core programming languages that you must master as a front-end developer: HTML, CSS, and JavaScript.

HTML is the most basic language for creating the layout of web pages or app interfaces. Hyper Text Markup Language (HTML) is the building block for any website or app. Browsers interpret HTML to understand how to display a web page or app.

CSS or Cascading Style Sheets is a decorative tool that adds visual elements to the HTML code. It is used to implement everything from font styles to colors and icons.

JavaScript is used by 98% of all the websites on the internet and is touted as the ‘language of the internet.’ The scripting language turns static web and app pages into dynamic and interactive content. You must have command over JavaScript and its frameworks to get hired.

Level 2: Front-end development frameworks and libraries

Frameworks and libraries are essential to quickly create websites and apps without writing features and capabilities from scratch. They are templates that provide existing code to work with that you can build upon to do your projects. Here are essential frameworks a front-end web developer must know.

Bootstrap: A free and open-source CSS framework, Bootstrap was created by Twitter to help front-end developers quickly design mobile-friendly websites and apps. It has many reusable code blocks written in HTML, CSS, and JavaScript that you can directly include in your projects.

React: Created by Facebook, React is a highly robust JavaScript library that builds incredibly fast UIs. React.js has a 40.14% market share and is the most widely used JavaScript framework to build the view layer for mobile and web applications.

AngularJS: Mostly used for single-page web applications or SPAs, AngularJS is an open-source JavaScript library created and maintained by Google.

jQuery: It is a framework that front-end web developers use to convert multiple lines of code into methods that can be called with a single line of code. jQuery is used for various applications such as HTML/DOM manipulation, cross-browser JavaScript development, and AJAX interactions.

How do you become a front-end web developer?

You start by learning the basics as listed above and move on to practice Level 2 skills. As a front-end developer, you will define user experience by creating interactivity and design solutions for the web and app interfaces.

To get started, you can utilize the tips shared in our guide on how to land a high-paying front-end developer job.

Once you are confident that you have the necessary skills, you can explore full-time and freelance opportunities for front-end developers. Talent500 is the platform that top front-end developers use to find opportunities with fast-growing startups and Fortune 500 companies. You can join us here.

 

 

Top 4 algorithms to improve your JavaScript skills

JavaScript is a skill that makes a developer a valuable candidate for any front-end or back-end position. When more than 98% of websites use JavaScript, it is evident that no web development project can take place without JavaScript components. It is required for any interaction between the user and a web page.

Suppose you are building a website to display the score of an ongoing sports tournament. As a developer, you can take two approaches here. First, manually update the value on the server, and users have to refresh the browser screen for score updates. Second, the viewer screen updates automatically every time there is an update in the value on the server. 

Without a doubt, the latter approach is preferable. This is what JavaScript can achieve. It can significantly automate the functionalities and components of a web application.

To truly utilize the functionality of JavaScript, you must master some algorithms. This article will list the top four algorithms a JavaScript developer should know.

1. Linear search

One of the simplest JavaScript algorithms is linear search used for searching a data set. This algorithm starts from the 0th element, comparing the user’s input to return the positional value of the element finally.

It is often used to find missing elements in an array using JavaScript code. Here’s an example:

Find the missing number in this array:

Input: [1, 2, 3, 4, 6, 7, 8, 9, 10]

Algorithm:

const find_missing = function(input) {

  let n = input.length + 1; let sum = 0;

  for (let i in input) {

   sum += input[i];

  }return Math.floor((n * (n + 1)) / 2) – sum;

};

Output: 5

2. Reversal algorithm 

It is the algorithm used in JavaScript to reverse an array. The reversal algorithm creates subarrays and changes them to perform the rotation of an array.

Array alignment is one of the essential JavaScript skills to master. You can achieve the same with the reversal algorithm. Here is an example of a realignment in JavaScript:

Input: [1,2,3]

Code:

const permute = function(nums) {

   let results = [];let go = (current) => {

    if (current.length === nums.length){

     results.push(current);

     return;

    }

    nums.forEach(n => {

     if (!current.includes(n)){

     go([…current, n]);

     }

    });

   }

   go([]);

   return results;

};

Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

The same algorithm can be used for string array alignment.

Here is an example of two input strings that we check for alignment using the reversal algorithm.

Input: s1 = “ab”, s2 = “eidbao”

Output: true

Input: s1 = “aa”, s2 = “eidbao”

Output: false

JavaScript code:

const checkPermutation = function(s1, s2) {

  const len1 = s1.length, len2 = s2.length;

  if (len1 > len2) return false;const count = Array(26).fill(0);

  for (let i = 0; i < len1; i++) {

   count[s1.charCodeAt(i)-97]++;

   count[s2.charCodeAt(i)-97]–;

  }

  if (!count.some(e => e !== 0)) return true;for (let i = len1; i < len2; i++) {

   count[s2.charCodeAt(i)-97]–;

   count[s2.charCodeAt(i-len1)-97]++;

    if (!count.some(e => e !== 0)) return true;

  }

  return false;

};

3. Number-to-word conversion 

This algorithm converts any given number into an English word string. It uses some predefined strings, and the output is generated using the values from these strings.

Input: 786

Output: Seven hundred and eighty-six

JavaScript code:

#include<iostream>

using namespace std;

string getUnit(int n) {

   //Return single digit to word

  string unit[10] = {“Zero”, “One”,”Two”, “Three”,”Four”,”Five”, “Six”,”Seven”,”Eight”,”Nine”};

  return unit[n];

}

string getTwoDigits(int n) {

  //Here n is 2 digit number

  string td[10] = {“Ten”, “Eleven”,”Twelve”,”Thirteen”, “Fourteen”,”Fifteen”,”Sixteen”,”Seventeen”,”Eighteen”,”Nineteen”};

  return td[n%10];

}

string getTenMul(int n) {

  //Here n is a multiple of 10

  string tm[8] = {“Twenty”, “Thirty”,”Fourty”, “Fifty”,”Sixty”, “Seventy”,”Eighty”,”Ninty”};

  return tm[n-2];

}

string getTenPow(int pow) {

  //The power of ten in words

  string power[2] = {“Hundred”, “Thousand”};

  return power[pow-2];

}

void printNumToWord(int n) {

  if(n >= 0 && n < 10)

    cout << getUnit(n) << ” “;   

//Unit values to word

  else if(n >= 10 && n < 20)

    cout << getTwoDigits(n) << ” “;    

//from eleven to nineteen

  else if(n >= 20 && n < 100) {

    cout << getTenMul(n/10)<<” “;

    if(n%10 != 0)

 printNumToWord(n%10); //Recursive call to convert num to word

  }else if(n >= 100 && n < 1000) {

    cout << getUnit(n/100)<<” “;

    cout <<getTenPow(2) << ” “;

if(n%100 != 0) {

     cout << “And “;

printNumToWord(n%100);

    }

}else if(n >= 1000 && n <= 32767) {

   printNumToWord(n/1000);

    cout <<getTenPow(3)<<” “;

    if(n%1000 != 0)

printNumToWord(n%1000);

  }else

printf(“Invalid Input”);

}

main() {

  int number;

  cout << “Enter a number between 0 to 32767: “; cin >> number;

  printNumToWord(number);

}

4. 4sum algorithm 

4sum is another important JavaScript algorithm that finds several uses in computational applications. It is used to find the four elements in an array whose sum equals the required answer.

JavaScript code example:

const fourSum = function(nums, target) {

  let result = [];

  let length = nums.length;

  if (length < 4) return result;

  nums = nums.sort((a, b) => a – b );for (let i = 0; i < length – 3; i++) {

   if (nums[i] === nums[i – 1]) continue;

   for (let j = i + 1; j < length – 2; j++) {

    if (j > i + 1 && nums[j] === nums[j – 1]) continue;let k = j + 1;

    let l = length – 1;while (k < l) {

     const sum = nums[i] + nums[j] + nums[k] + nums[l];if (sum === target) {

     result.push([nums[i], nums[j], nums[k], nums[l]])

     }if (sum <= target) {

      k += 1;

      while (nums[k] === nums[k – 1]) {

       k += 1;

      }

     }if (sum >= target) {

      l -= 1;

      while (nums[l] === nums[l + 1]) {

       l -= 1;

      }

     }

    }

   }

  }return result;

};

Conclusion 

Whether you are a front-end or a back-end developer, these are four important JavaScript algorithms to learn. They are widely used in web applications, from delivery tracking websites to ticket booking apps.

Talent500 has some great learning resources for JavaScript developers. And, if you are looking for job opportunities, sign up here.

 

Essential React design patterns for developers

React has kept its spot of being the most widely used JavaScript framework since its inception. It is used on 24% of the entire internet, making it a great JavaScript library to master. As a front-end developer, you must keep up with the evolution of technologies, but React is a framework that keeps steady with its reusable components. Learning React.js will benefit your career as it is there to stay.

Facebook, the creator of React, actively develops and maintains the library giving it the much-needed edge over other frameworks and libraries. React can use the design patterns to offer a robust development environment compared to other JavaScript libraries.

The importance of React design patterns 

Design patterns are essential concepts of project development. React and every other programming language has some design patterns that help prevent the commonly occurring problems in software development.

In simpler terms, React design patterns are the basic templates upon which you can build a program’s functionality according to the given requirements. Developers who understand design patterns can speed up the development process. Also, such software engineers will be able to write easier-to-read and maintain code.

This article will cover some basic React design patterns that developers must know.

The HOC (Higher Order Component) Pattern

When creating Reactive applications, you often have to use the same logic in various modules—for instance, using the same design elements for different Card Views or third-party subscription data components in the interface design.

Higher-order components are a popular React design pattern for creating logic shared between various components. With the HOC pattern, you don’t have to rewrite the code; you can extend the existing code’s functionality. HOC functions are considered pure functions as they do not have any side effects on the quality of the code.

A HOC function is a JavaScript function that takes a component as an argument and returns another component by adding additional data to the Component. This functionality is inherent to React as the programming language prefers composition over inheritance. Here’s an example of a HOC React design pattern:

import React, { Component } from “react”;

const higherOrderComponent = (DecoratedComponent) => {

  class HOC extends Component {

   render() {

    return <DecoratedComponent />;

   }

  }

  return HOC;

};

Many popular React frameworks use this design pattern, most notably Redux’s connection function. If your project is based on React or Redux, you can use a higher-order component design pattern to simplify your code and make it more maintainable.

React Hooks design patterns

Hooks were introduced in React version 16.8, and they revolutionized how developers build React components. The React Hook API lets components access the most commonly used React features like state, props, context, refs, and lifecycle. When you use the React Hook design pattern, you increase the potential of functional components as they are now as powerful as the class components.

A React Hook design pattern might seem similar to a Presentational and Container Components design pattern, but there’s a difference. 

Presentational and Container Component design patterns usually create massive logic split across different lifecycle methods. Such components are hard to read and maintain. React Hooks make functional components highly robust, and they can perform all the functions of containers but without their limitations.

Here’s an example of a container method:

import React, { Component } from “react”;

class Profile extends Component {

constructor(props) {

   super(props);

   this.state = {

    loading: false,

    user: {},

   };

  }

componentDidMount() {

  this.subscribeToOnlineStatus(this.props.id);

  this.updateProfile(this.props.id);

  }

componentDidUpdate(prevProps) {

   // compariation hell.

   if (prevProps.id !== this.props.id) {

   this.updateProfile(this.props.id);

   }

  }

componentWillUnmount() {

this.unSubscribeToOnlineStatus(this.props.id);

  }

subscribeToOnlineStatus() {

   // subscribe logic

  }

unSubscribeToOnlineStatus() {

   // unscubscribe logic

  }

  fetchUser(id) {

   // fetch users logic here

  }

  async updateProfile(id) {

   this.setState({ loading: true });

   // fetch users data

   await this.fetchUser(id);

   this.setState({ loading: false });

  }

  render() {

   // … some jsx

  }

}

export default Profile;

The code is not optimal. The setState() can only change the first level of any state object. Also, the inline action methods like the onHandleChange() increase the line of code. Related logic is repeated multiple times.

The same code using React hooks design pattern:

import React, { useState, useEffect } from “react”;

function Profile({ id }) {

  const [loading, setLoading] = useState(false);

  const [user, setUser] = useState({});

// Similar to componentDidMount and componentDidUpdate:

  useEffect(() => {

  updateProfile(id);

  subscribeToOnlineStatus(id);

   return () => {

   unSubscribeToOnlineStatus(id);

   };

  }, [id]);

 const subscribeToOnlineStatus = () => {

   // subscribe logic

  };

const unSubscribeToOnlineStatus = () => {

   // unsubscribe logic

  };

const fetchUser = (id) => {

   // fetch user logic here

  };

const updateProfile = async (id) => {

  setLoading(true);

   // fetch user data

   await fetchUser(id);

  setLoading(false);

  };

return; // … jsx logic

}

export default Profile;

Now you have direct access to the state of objects, and functional components can also use state. The useEffect method replaces lifecycle methods like componentDidMount and componentWillInmount, making code cleaner and concise.

Conclusion 

React design patterns can give you access to fantastic programming language features to create scalable, secure, and robust React apps. The above two React design patterns are generally used to write clean and maintainable React code. Also, don’t miss our React developer toolkit that lists additional resources React developers can use to upskill.

Talent500 is a platform for React developers to find opportunities at global companies. Join our elite pool of talent to get discovered by international companies. Sign up here.

 

 

10 buzzwords every frontend developer should include in their vocabulary

The frontend development domain is rife with peculiar buzzwords that can baffle untrained ears. If you are a frontend developer new to the field, it will help if you familiarize yourself with these developer buzzwords. Being familiar with the industry vocabulary is an indicator of your skill versatility and experience handling projects. It acts as proof of your expertise. You will not feel left out when conversations around these frontend developer buzzwords happen.

This post lists the most popular front-end developer buzzwords that will make your journey into the industry much more straightforward.

1. Agile

A major buzzword in the software development industry is Agile. It is a methodology that offered an improvement over the waterfall methodology resulting in faster iteration and release of products. Agile web development is more common in the startup world. In agile methodology, web development teams work according to weekly or biweekly sprints. Sprint is the development cycle with five phases – design, develop, test, deploy, and review. Here, you can learn more about how agile methodology improves the development process and time-to-delivery.

2. API

Application Programming Interface or API is another important developer buzzword for front-end developers to learn. The core functionality of an API is to allow two different programs to communicate with each other. With APIs, front-end developers can make certain parts of their design available to back-end developers. Based on an API, several tools and widgets can be built that can be connected to a particular website. A payment gateway API is an example of how eCommerce websites accept payments. Here are some important browser APIs that front-end developers must be aware of.

3. Adaptive design

Also known as responsive design, it is a way in which a website is designed to adapt to the screen size of a device without breaking. The adaptive design creates websites in several layouts to fit different device screens. You will be asked to develop adaptive website designs as a frontend developer. Mobile-first is also a term used for adaptive design.

4. Bootstrap

A free and open-source frontend framework, Bootstrap is widely used in website and web app design. Developed at Twitter by Mark Otto and Jacob Thornton, it brings consistency to your website design. Bootstrap is based on HTML and CSS. It uses the same technologies for design templates and elements like forms, typography, tables, buttons, modals, and more. Bootstrap is among the most common front-end developer buzzwords you will often hear in your career.

5. Cache

Website performance is augmented with the use of cache. A cache is temporary storage for data that the browser uses to store website data. When a user requests the same website data, it is fetched from the cache instead of sending a request to the server to download the resources again. It enables faster loading of web pages.

6. CI/CD

CI/CD stands for continuous integration and continuous delivery. It is a method to deliver apps frequently to the customers by introducing automation into the various stages of app development. The CI/CD is a solution where most problems arise from integrating new code into an existing code base. It helps development and operation teams to deploy app updates and features faster. Learn more about CI/CD here.

7. DOM

The Document Object Model or DOM is a cross-platform and language-independent interface used in web or app design. DOM treats XML or HTML documents as a tree structure wherein each node is an object representing a section of the document. Simply put, a DOM means any HTML or XML document in a logical tree for the browser to render. It is one of the most important developer buzzwords you must be aware of.

8. FCP 

First contentful paint or FCP measures how long it takes the browser to render the first piece of DOM content after a user visits a web page. It is also one of the metrics that Google uses to evaluate the performance of a web page. Images, non-white <canvas> elements, and SVGs on a web page are considered DOM content, while iframe content is treated as non-DOM content. As a front-end developer, it will be your responsibility to keep FCP low. Google has a great resource on FCP and how to improve FCP scores.

9. Information architecture

Information architecture is the practice of organizing and representing complex information clearly and logically. In the context of website and app design, it implies creating a user-friendly navigation structure. Front-end developers and back-end engineers are information architects, too, in how they structure their code.

10. Minification

The last, but not least, front-end developer buzzword on our list is minification. It is the process of minimizing the markup and code to reduce the file size. When creating web pages, a developer will use spacing, comments, and variables to make code more readable, but it also increases the file size. Once a web page is live, the developer removes the spaces and comments to minify the code files.

Conclusion 

This is no exhaustive list of the important front-end developer buzzwords, but it is enough to help you initiate the web developer talk. As you learn and grow in your career, you will come across many more developer buzzwords.

Are you a talented front-end developer looking for a job opportunity at a fast-growing startup or a Fortune 500 company? Talent500 can help. Join us here to know more.

 

3 React traps you should be wary of as a frontend developer

React is arguably the most used JavaScript framework for frontend development. It offers opportunities and options to developers that other frontend frameworks fail to deliver. For instance, React provides an easy way to handle DOM API which is usually abstracted beneath interfaces making it difficult to interact with them directly. This JavaScript framework provides developers with a virtual browser that is much more developer-friendly than real browsers. The virtual browser acts as the agent between developers and the actual browser.

React is developer-friendly in many more ways, but this article is on some common language pitfalls that developers should avoid. If you are new to React, we recommend you familiarize yourself with these React traps to avoid them easily.

Let’s see what frontend developers must know about these traps.

1. Empty data will still display 0

As a React developer, you must have written code to pull data from the server and display it as a list on the front end. If the data is empty then ideally, it must not be displayed on the screen:

Example code:

const App = () => {

  const [list, setList] = React.useState([]);

  // fetch data …

  return (

   list.length && (

    <div className=”name-list-container”>

    {list.map((name) => {

      return <div className=”name-list-item”>{name}</div>;

     })}

    </div>

   )

  );

};

However, the output of this code will display 0 when the list is an empty array. It can leave you scratching your head as to why it is doing so.

It is not a bug, but a default behavior in React caused by the operating mechanism of JavaScript itself. According to MDN docs, “in JavaScript logical AND (&&) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true. Otherwise, it will be false.

The AND operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.”

For example:

const a = 0;

const b = “fatfish”;

const c = 1;

const d = “medium”;

Output:

console.log(a && b); // 0

console.log(c && d); // medium

However, there are several ways to overcome this React trap. Here are some examples of how you can solve the problem by turning a into a Boolean using ternary expressions.

  1. Convert list.length to boolean

!!list.length && <Component list={list} />;

  1. Use ternary expressions and null

list.length ? <Component list={list} /> : null;

  1. Controlled by a specific logic

list.length >= 1 && <Component list={list} />;

2. Get tricked by the use of “||” and “&&” 

If you are using both AND “&&” and OR “||” operators in a statement, you have to be careful because most React developers mess up in such scenarios.

Let’s consider this code:

const App = (props) => {

  return (

   props.name || props.name2 && <div className=”user-info”>fatfish</div>

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

We want to show “fatfish” when the property name or name2 is passed a value. However, the outcome will be different because the code is not working as expected.

Why?

In JavaScript, the && operator has a higher priority, which is why the above code acts like this:

const App = (props) => {

  return (

   props.name || (props.name2 && <div className=”user-info”>fatfish</div>)

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

The right way to display “fatfish” when a value is passed to name or name2 is using the following code:

const App = (props) => {

  return (

   (props.name || props.name2) && <div className=”user-info”>fatfish</div>

  )

}

ReactDOM.render(<App name=”medium” />, document.getElementById(‘app’))

3. Using nested multi-layer ternary expressions

React might be robust but be careful if you use multiple ternary expressions nested in your React app. It might very well be a nightmare for you and any other developer. Such nested code is hard to read and debug.

For instance, here’s nested multi-layer ternary React code:

{

  isUserA ? (

   <ComponentA />

  ) : isUserB ? (

   <ComponentB />

  ) : (

   isUserC ? <ComponentC /> : null

  );

}

If you write React code like this, you need to change your style right now.

You can simplify the code with the use of an if-else.

Here’s the above code without nesting:

const renderCompnent = () => {

  let component = null

  if (isUserA) {

   component = <ComponentA />

  } else if (isUserB) {

   component = <ComponentB />

  } else if (isUserC) {

   component = <ComponentC />

  }

  return component

}

As you can see, with nested ternary, React code becomes easy to read. It is a skill that will serve you well in your career as your code will be easy to maintain and debug.

Conclusion 

React is here to stay, and so is JavaScript. You can stand out by mastering the nuisances of React framework that give other developers nightmares. We hope these three commonly faced React traps won’t bother you anymore.

Talent500 is the remote team-building platform Fortune 500 companies use to hire engineering talent. Join our elite pool of talent, and sign up here.

 

4 useful Typescript features for developers

Typescript’s influence is growing within the developer community. Microsoft created this programming language only a decade ago to overcome the deficiencies of JavaScript. Typescript is the superset of JavaScript that offers a class-based object-oriented programming approach that can also be static-typed like JavaScript.

The benefits of using Typescript cannot be overstated, as it can be used for creating JavaScript applications for the client and server side. One of the biggest problems this programming language solves is the ability to produce large systems based on JavaScript. However, to fully utilize the benefits of Typescript, you must know its essential features.

This article will cover Typescript’s four most important features that can empower your program performance at scale.

 

1. Generics

In JavaScript, there is no way to make methods or APIs reusable, but in Typescript, you can achieve that using Generics. It is one of the essential Typescript features to master, common to all dynamically typed programming languages.

Let’s see an example code snippet to understand Generics.

function addItem(item: string, array: string[]) {
array = […array, item];
return array;
 }

Here we have created a method to add defined types to an array. Suppose we want to create a similar function for the int type. Do we have two redo the same method?

No. Generics in Typescript allow us to reuse the code instead of writing it repeatedly. Here’s how:

function addItem<T>(item: T, array: T[]) {
array = […array, item];
 return array;
}
addItem(‘hello’, []);
addItem(true, [true, true]);

Here we use T for creating an array with any type. But what if we want to limit certain unwanted types from using T? For this function, we use the ‘extends’ keyword.

function addItem<T extends boolean | string>(item: T, array: T[]) {
array = […array, item];
return array;
}

addItem(‘hello’, []);

addItem(true, [true, true]);

addItem(new Date(), []);

// ^^^^^^^^^^

// Argument of type ‘Date’ is not assignable to parameter of type ‘string | boolean

In Typescript, Generics is a powerful concept that empowers developers to quickly build comprehensive and large-scale dynamic interfaces for their applications.

 

2. Unions

One of the most straightforward Typescript features to use is unions. They allow developers to combine multiple types into one. In large-scale applications, you often have to compose types by combining different variables.

According to Typescriptlang.org, “a union type describes a value that can be one of several types. We use the vertical bar (|) to separate each type.” Here is an example: 

function logIdentifier(id: string | number) {
 console.log(‘id’, id);
}

Unions are essential when you are working with nullable types. For instance, string type is used with undefined in the following code.

function logIdentifier(id: string | undefined) {
if(!id) {
console.error(‘no identifier found’);
} else {
   console.log(‘id’, id);
  }
}

Union is a robust Typescript feature that can provide a simpler alternative to Generics when the requirement is to express types/interfaces dynamically less. The benefit here is improved simplicity.

 

3. Tuples

Tuples are one of the essential Typescript features developers must be familiar with. A tuple type allows developers to create an array with a fixed number of elements whose types are known but not necessarily the same kind. In JavaScript, creating an array with two types of elements is difficult, but Typescript’s tuple feature makes it a lot easier.

There are two different ways to define a tuple – explicitly and implicitly.

Here is an example of an explicit tuple:

const array: [string, number] = [‘test’, 12];

An implicit tuple is defined as:

const array = [‘test’, 12] as const;

The difference between the two arrays is that the use of const in the implicit tuple makes it a read-only array. This is a preferable security feature.

You can also use label tuples like this:

function foo(x: [startIndex: number, endIndex: number]) {
 …
}

The benefit of using labels in tuples is that when you are destructuring, you don’t have to name the variables differently. They also make your code more readable and maintainable. However, remember that when you label one tuple element, you must also label the rest tuples.

 

4. Type Guards

Type guards are tools in Typescript that allow developers to narrow down the type of objects they use in the program. It implies you can go from a more general type to a more specific one. This allows Typescript developers to write better code faster.

There are multiple ways to create type guards. However, the most commonly used are user-defined type guards. They are easy to implement. All you have to do is to define a function whose return type is a type predicate. Remember that this function can only return true or false.

Here is an example of a code that uses a type of operator for the type guard function.

function isNumber(x: any): x is number {
return typeof x === “number”;
}
function add1(value: string | number) {
if (isNumber(value)) {
  return value +1;
  }
 return +value + 1;
}

Type guards are scoped, i.e., the value can be called only within the function they are used, and outside the code block, they will be unknown.

 

Conclusion 

We explored a few most critical Typescript features, but there are many more that you can use to create scalable systems. Try progressively adopting these features in your code, and you will realize how much cleaner, concise, and easier to maintain your code will become.

Talent500 is a platform for Fortune 500 companies and startups to hire talent and build remote engineering teams. Join us today and get discovered by the best companies.