JavaScript Archives | Talent500 blog https://talent500.com/blog/category/frontend/javascript/ Sun, 13 Apr 2025 13:02:31 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 https://talent500.com/blog/wp-content/uploads/sites/42/2025/01/favicon.ico JavaScript Archives | Talent500 blog https://talent500.com/blog/category/frontend/javascript/ 32 32 How CSS and Voxel Art Combine to Create a Stacked Grid Rendering Engine https://talent500.com/blog/css-voxel-art-stacked-grid-rendering-engine/ https://talent500.com/blog/css-voxel-art-stacked-grid-rendering-engine/#respond Mon, 10 Mar 2025 10:30:22 +0000 https://talent500.com/blog/?p=41638 Voxel art, known for its blocky, pixel-like aesthetic, has traditionally been associated with 3D modeling and game design. However, combining […]

The post How CSS and Voxel Art Combine to Create a Stacked Grid Rendering Engine appeared first on Talent500 blog.

]]>
Voxel art, known for its blocky, pixel-like aesthetic, has traditionally been associated with 3D modeling and game design. However, combining voxel art with CSS introduces a unique way to create visually striking designs directly in the browser. By leveraging stacked grids in CSS, developers can build a rendering engine that mimics voxel art without relying on external libraries or 3D engines. This article explores how CSS meets voxel art, the techniques behind building a rendering engine with stacked grids, and the creative opportunities it unlocks.

What is Voxel Art?

Voxel art is a form of digital art that uses three-dimensional cubes (voxels) as building blocks to create intricate designs. Think of it as the 3D equivalent of pixel art. Each voxel represents a single point in 3D space, making it ideal for creating blocky, retro-style visuals often seen in games like Minecraft.

While voxel art is typically rendered using specialized software or game engines, this approach explores how CSS can replicate the same aesthetic through clever use of grids and layering techniques.

The Concept of Stacked Grids in CSS

What are Stacked Grids?

Stacked grids involve layering multiple grid containers on top of each other to simulate depth. Each grid layer represents a “slice” of the 3D space, with individual cells acting as voxels. By stacking these layers vertically and controlling their appearance through CSS properties like z-index and transform, developers can create the illusion of a 3D voxel-based structure.

Why Use CSS for Voxel Art?

Using CSS for voxel art offers several advantages:

  1. No External Libraries: Everything is built natively using HTML and CSS, reducing dependencies.
  2. Browser-Based Rendering: Designs can be rendered directly in modern browsers without additional tools.
  3. Interactivity: CSS animations and transitions enable dynamic effects like rotating or transforming voxel structures.

Building the Rendering Engine

Step 1: Setting Up the Grid Structure

The foundation of the rendering engine begins with defining a grid container for each layer:

xml<div class="grid-layer">
  <div class="voxel"></div>
  <div class="voxel"></div>
  <!-- More voxels -->
</div>

Each .grid-layer represents one slice of the 3D structure, while .voxel elements act as individual blocks within that slice.

In CSS, the grid is defined using display: grid along with grid-template-columns and grid-template-rows to control its dimensions:

css.grid-layer {
  display: grid;
  grid-template-columns: repeat(10, 20px);
  grid-template-rows: repeat(10, 20px);
}

Step 2: Adding Depth Through Layering

To simulate depth, multiple .grid-layer elements are stacked on top of each other using position: absolute and z-index. Each layer is offset slightly along the Z-axis using transform:

css.grid-layer:nth-child(n) {
  transform: translateZ(calc(var(--layer-depth) * n));
}

This creates the illusion of a 3D structure when viewed from above or at an angle.

Step 3: Coloring Voxels

Each .voxel can be styled individually to represent different colors or materials within the structure. Using pseudo-elements like ::before and ::after, developers can add shading or highlights to enhance the visual depth:

css.voxel {
  background-color: #3498db;
  box-shadow: inset -2px -2px rgba(0,0,0,0.2);
}

Challenges in Implementing Stacked Grids

While building a voxel rendering engine with CSS is innovative, it comes with its own set of challenges:

  1. Performance: Rendering multiple layers with hundreds of voxels can strain browser performance, especially on less powerful devices. Optimizing grid sizes and limiting unnecessary animations are essential for smooth performance.
  2. Complexity: Managing dozens of stacked layers requires meticulous organization in both HTML and CSS codebases. Naming conventions and reusable classes can help streamline development.
  3. Interactivity Limitations: While CSS animations provide basic interactivity, more complex behaviors like real-time user input require JavaScript integration.

Creative Possibilities with CSS Voxel Art

Despite its challenges, using CSS for voxel art opens up exciting creative opportunities:

  1. Interactive Designs: Developers can create interactive voxel-based designs that respond to user actions like hover or click events.
  2. Dynamic Animations: Animating entire structures or individual voxels adds life to static designs.
  3. Browser-Based Games: Simple games or puzzles can be built entirely within the browser using this technique.
  4. Educational Tools: The approach serves as an excellent teaching tool for understanding both CSS grid systems and basic principles of 3D rendering.

Expanding Functionality with JavaScript

While this approach relies heavily on CSS for rendering, integrating JavaScript can enhance functionality further by enabling dynamic updates or interactions in real time.

For example:

  • Adding user controls to rotate or zoom into structures.
  • Dynamically generating voxel layers based on user input.
  • Implementing collision detection for game mechanics.

Conclusion

Combining CSS with voxel art through stacked grids showcases how creative coding techniques can push the boundaries of web design. By leveraging native browser capabilities without external libraries or tools, developers can create visually stunning designs that blur the line between traditional web development and digital artistry.

While challenges like performance optimization remain, this approach offers endless possibilities for interactive designs, educational content, and even browser-based games—all powered by nothing more than HTML and CSS.

As web technologies continue to evolve, innovations like these highlight how versatile front-end development has become—transforming simple code into immersive visual experiences.

Read more such articles from our Newsletter here.

The post How CSS and Voxel Art Combine to Create a Stacked Grid Rendering Engine appeared first on Talent500 blog.

]]>
https://talent500.com/blog/css-voxel-art-stacked-grid-rendering-engine/feed/ 0
Optimizing JavaScript Bundles: A 33% Reduction in Size https://talent500.com/blog/optimizing-javascript-bundles-reduction/ https://talent500.com/blog/optimizing-javascript-bundles-reduction/#respond Fri, 10 Jan 2025 11:30:07 +0000 https://talent500.com/blog/?p=40963 When was the last time a website’s button shifted just as you were about to click it, causing you to […]

The post Optimizing JavaScript Bundles: A 33% Reduction in Size appeared first on Talent500 blog.

]]>
When was the last time a website’s button shifted just as you were about to click it, causing you to select the wrong option? Or perhaps you’ve experienced frustration waiting for a page to load? These issues become even more pronounced in rich, interactive applications. As front-end code grows to support complex features, the size of data sent to browsers increases, negatively impacting performance.

At Dropbox, the web performance engineering team has recognized these challenges and identified a significant factor contributing to them: the module bundler.

Miller’s Law suggests that the human brain can only process a limited amount of information simultaneously, which is why modern codebases, including Dropbox’s, are divided into smaller modules. A module bundler consolidates these various components—such as JavaScript and CSS—into bundles that browsers download when a page is accessed. Typically, this results in a minified JavaScript file encompassing most of a web application’s logic.

Dropbox’s initial module bundler was developed in 2014, coinciding with the rise of performance-oriented bundling methods popularized by tools like Webpack and Rollup. However, this early version lacked many performance optimizations and proved cumbersome for engineers, hindering both user experience and development speed.

As it became evident that the existing bundler was outdated, Dropbox opted for a replacement. This decision aligned perfectly with their migration to Edison—the new web serving stack—offering an opportunity to seamlessly integrate a modern bundler into their static asset pipeline.

Existing Architecture Challenges

While the previous bundler was efficient during build time, it resulted in large bundle sizes and posed maintenance challenges for engineers. The reliance on manual definitions for script bundling led to several issues:

  • Multiple Versions of Bundled Code: The custom architecture known as Dropbox Web Server (DWS) segmented each page into multiple pagelets (subsections), resulting in multiple JavaScript entry points per page. This setup occasionally caused inconsistencies due to differing backend code versions across pagelets.
  • Manual Code-Splitting: Code-splitting allows browsers to load only necessary parts of the codebase for specific pages. Without this feature in the existing bundler, engineers faced complexity in defining packages manually. The packaging map grew unwieldy, leading to unnecessary code being loaded.
  • Lack of Tree Shaking: Tree shaking is an optimization technique that removes unused code from bundles. The absence of this feature meant that many packages contained excessive unused code, prolonging load times.

Choosing Rollup

After evaluating various solutions over time, Dropbox determined that their primary requirements included automatic code-splitting and tree shaking capabilities. Rollup emerged as the most mature and flexible option available, making it an ideal choice for integration into their existing build pipeline.

Utilizing Rollup also minimized engineering overhead since teams were already familiar with its quirks from previous use in bundling NPM modules.

Rollout Strategy

Implementing a new module bundler safely required careful planning. Dropbox divided the rollout process into four stages:

  1. Developer Preview Stage: Engineers could opt-in to use Rollup bundles within their development environment for early QA testing.
  2. Dropboxer Preview Stage: Rollup bundles were served to all internal employees for initial feedback and performance data collection.
  3. General Availability Stage: Gradual rollout to all users occurred once Rollup packaging was thoroughly tested.
  4. Maintenance Stage: Addressing any technical debt accrued during the project while iterating on Rollup usage for ongoing optimization.

To facilitate these stages, Dropbox employed both cookie-based gating and their internal feature-gating system for quick toggling between Rollup and legacy packages.

Challenges Encountered

The simultaneous operation of two module bundlers proved more resource-intensive than anticipated. Issues arose with Rollup’s tree-shaking algorithm requiring substantial memory usage during analysis. Additionally, integrating Rollup into existing infrastructure limited caching capabilities, leading to timeouts during continuous integration (CI) builds.

Some bugs related to tree shaking were discovered during early testing phases but were resolved without impacting users. Furthermore, compatibility issues with strict mode in JavaScript required an extensive audit of the codebase.

Results Achieved

Upon completing the rollout of Rollup across all users, Dropbox achieved significant results:

  • A 33% reduction in JavaScript bundle sizes
  • A 15% decrease in total JavaScript script count
  • Improvements in time-to-visible content (TTVC)

Additionally, front-end development velocity improved due to automatic code-splitting, alleviating engineers from manual adjustments with each change. This transition modernized their bundling infrastructure and addressed years of accumulated technical debt.

The adoption of Rollup not only provided immediate performance enhancements but also paved the way for future optimizations within Dropbox’s architecture. By revealing bottlenecks such as render-blocking RPCs and inefficient loading processes, Rollup’s extensive plugin ecosystem offers opportunities for further advancements.

In summary, embracing Rollup as their primary module bundler has led to substantial gains in both performance and productivity for Dropbox while setting the stage for continued improvements down the line.

Read more such articles from our Newsletter here.

The post Optimizing JavaScript Bundles: A 33% Reduction in Size appeared first on Talent500 blog.

]]>
https://talent500.com/blog/optimizing-javascript-bundles-reduction/feed/ 0
Javascript for Web Development: An Introduction https://talent500.com/blog/javascript-for-web-development/ https://talent500.com/blog/javascript-for-web-development/#respond Wed, 23 Oct 2024 12:48:57 +0000 https://talent500.com/blog/?p=40593 There was a time when websites were primarily built using basic HTML and CSS which provided static content with minimal […]

The post Javascript for Web Development: An Introduction appeared first on Talent500 blog.

]]>
There was a time when websites were primarily built using basic HTML and CSS which provided static content with minimal interactivity. Fast forward to today and we find ourselves in an era where JavaScript frameworks and libraries have taken web development to the next level. Today developers can create complex applications more efficiently than ever before.

JavaScript has made web development much easier and if you are a seasoned web developer, you can’t imagine building websites without Javascript. Its real-time manipulation of the Document Object Model (DOM) enables developers to create responsive interfaces that react instantly to user actions.

In this detailed blog on JavaScript, we will look at how JavaScript is used in modern web development. So let’s get started.

What is JavaScript

JavaScript is just a programming language, but the beauty is that you can use it for frontend development, server-side development, mobile app development, and many other possibilities.

It all started as a basic scripting language that allowed you to manipulate HTML and CSS programmatically. Today, you can use it to build almost all kinds of software applications. HTML and CSS allow you to create the layouts and styles for your website while JavaScript brings them to life. You can control what actions to take when a user scrolls, hovers, or interacts with any part of your application.

One major advantage of JavaScript is that you don’t need to install any files to start working with it. You can run your program directly inside your browser. And not just that, if you want to run your code on your system, you can install Node.js or Bun.js, which provides a runtime environment for JavaScript. In browsers, we have the V8 engine, which allows you to compile and run your application.

The syntax of JavaScript is one of the most intuitive and straightforward syntaxes. For example, if you want to create a simple calculator, the code is shown in the above image.

Why do we use JavaScript for Web Development?

Without JavaScript your favourite shopping platform, OTT platform or social media platform, everything will no longer be user-friendly. JavaScript helps you build web applications that are interactive, dynamic, and responsive. Even a small interaction like adding items to a cart, or liking a social media post, JavaScript brings these experiences to life. It can make websites more easy to use.

Let’s explore its role across three major layers of the web development stack:

Front end development

 Every web application that you are using will be using JavaScript on the client side. JavaScript allows you to add client-side features like form validation, image carousals and dynamic content updates without reloading the page. Various 2D and 3D libraries allow you to simplify your workflow. For example, you can try Chart.js to draw 2D charts, graphs etc. and Three.js for creating 3D graphics and animations.

Several front-end libraries can also reduce the amount of work. For example, libraries like React.js can reduce the amount of work that you have to put in when using Vanilla JavaScript.

Backend development

 After Node.js came into existence, JavsScript developers did not need to depend on browsers for running their JavaScript code. They can directly run your code on your system. Thanks to these runtimes. Node.js and Deno are the most popular JavaScript runtimes.

Node.js, Bun.js or any other frameworks like Express.js allow you to write your server-side logic in the backend. You can handle HTTP requests, interact with databases and even build scalable backend systems using JavaScript.

This way you can use the same language on the frontend and backend allowing you to improve the overall developer experience. There are several backend frameworks apart from express, like Hono, EelysiaJS etc.

Fullstack development

 As we mentioned JavaScript can do great at both frontend and backend. This has resulted in a rise in the popularity of full-stack JavaScript frameworks like Next.js. Frameworks like Next.js allow you to handle server-side rendering to client-side interactivity. All this makes JavaScript an all-encompassing tool for building modern web apps.

You can also frameworks like React Native for building mobile applications using JavaScript.  With React Native you can build fully native mobile applications enabling cross-platform development for both iOS and Android.

What kind of Language is JavaScript?

Let’s now answer a fundamental question: which type of language is JavaScript?

When we talk about languages like C or Java we know they are strictly typed languages. Strictly typed languages are those languages that have strong type definitions like int, char, string etc.  In JavaScript, we don’t have to explicitly mention the type as it is a loosely typed language. The type of a variable is determined at runtime rather than at compile time.

JavaScript is also a multi-paradigm language meaning that it supports various programming styles which allows you to use the best approach depending on the need.

Imperative Programming

You can think of imperative programming as the step-by-step instruction to get a desired result. The programmer explicitly tells the computer what steps to take.

Functional Programming

JavaScript allows functions to be treated as first-class citizens and enables functional programming techniques. This means that functions in JavaScript can be assigned to variables and can be passed as arguments as well as returned from other functions just like any other data type.

Object-Oriented Programming

JavaScript supports object-oriented principles. Object-oriented programming (OOP) is a paradigm that structures code around objects which encapsulate both data and behaviour. Objects are a foundational part of JavaScript and you can use them to model real-world entities with properties (data) and methods (behaviour)

Asynchronous programming

 Apart from the other paradigms, JavaScript is known for its ability to handle asynchronous code. It allows you to have non-blocking operations and enables the execution of tasks concurrently rather than sequentially.

JavaScript is a single-threaded language. It can execute only one command at a time. In an ideal scenario, we would want to perform other processes in parallel. JavaScript uses the event loop to manage asynchronous operations.  Instead of waiting for time-consuming tasks like fetching data from an API or reading files, JavaScript can delegate these tasks to the browser or runtime environment. This allows the main program to continue running while the asynchronous task is being processed in the background.

The above code is a callback function and it will only be executed after two seconds but it does not halt the program.

Getting Started with JavaScript

Let’s now look at some of the basic concepts in JavaScript.

Variables and Data Types

 In JavaScript, there are mainly 3 ways to declare variables: let const and var.

  • Let: Let allows block scope variable declarations which means the variable is only accessible within the block it was defined.
  • Const: const is used to declare variables whose value should not be reassigned after their initial assignment. Const also has a block scope.
  • Var: Var has functional scope and it is the traditional way of declaring variables.

Variables and Data Types

Javascript has several built-in data types: They are divided into primitive and non-primitive data types. Examples of Primitive datatypes are String, Number, Boolean, BigInt etc. An example of a Non-primitive data type is Objects.

Functions

Functions are the blocks of code for performing a specific task. It can take arguments as inputs and return the output

Functions

Objects in JavaScript

Objects are the most fundamental concept in JavaScript. You can say that almost everything in JavaScript is an object.  An object consists of properties and methods.

Objects in JS

Once you are confident in JavaScript, you can start learning Typescript. Static typing can help you prevent numerous bugs and scaling problems in large codebases. TypeScript adds static typing to JavaScript. It can enhance your development experience by allowing for early error detection during compile time rather than runtime. TypeScript also improves code readability and maintainability.

Keep in mind that while there are many JavaScript frameworks, they will come and go. Don’t feel pressured to chase every trend. Focus on building a strong foundation. Since JavaScript has a huge ecosystem, if you ever get stuck, you can rely on developer forums like Stack Overflow or other helpful sites

Conclusion

Thanks for checking out this blog. In this detailed post on JavaScript, we’ve discussed everything you need to know before getting started. We covered various important concepts in JavaScript like functions, objects, data types, and more.

These foundational concepts will enable you to write effective JavaScript code and build dynamic web applications. Learning JavaScript is a no-brainer because there are countless opportunities for JavaScript developers. As you learn more, you’ll realize the possibilities with JavaScript are endless.

Read more articles about Javascript here.

 

The post Javascript for Web Development: An Introduction appeared first on Talent500 blog.

]]>
https://talent500.com/blog/javascript-for-web-development/feed/ 0
Demystified the call() method in JavaScript https://talent500.com/blog/demystified-the-call-method-in-javascript/ https://talent500.com/blog/demystified-the-call-method-in-javascript/#respond Mon, 27 Nov 2023 11:36:59 +0000 https://talent500.com/blog/?p=39220 The call() method in JavaScript allows us to invoke a function with a specified value for this keyword and arguments […]

The post Demystified the call() method in JavaScript appeared first on Talent500 blog.

]]>
The call() method in JavaScript allows us to invoke a function with a specified value for this keyword and arguments provided individually. It is useful for explicitly setting the context for a function or passing arguments one by one. It is also a frequently asked question in interviews. That’s why it’s very essential to know about this method. Now let’s get into the blog the right way.

What is call() method

The call() method invokes a method (or a function) from the owner object. An object can invoke a method that belongs to another object using the call() method. Let’s take an example: 

I’ve created an object called creator1. Inside this object, there are 3 properties, and the last one is a method (function) of the object. So, how do I call this function that is kept inside this object?

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

  intro() {

    console.log(`${this.name} is a ${this.niche}.`);

  },

};

It is so simple, We can call this function using the dot (.) operator followed by parentheses ().

creator1.intro(); // Ajay Yadav is a Front-end developer.

Now let’s suppose there is another object called creator2. And if we want to access the same method or function of the first creator1 object, then how can we do it?

Well, here we can leverage the power of the call() method without having it in the second creator2 object. But before implementing it, let’s see the syntax.

Syntax of the call() method

Here is the syntax of the call() method:

functionName.call(thisArgs, Arg1, Arg2, Arg3,…,ArgN);

Syntax explanation:

  • functionName: A function that is kept inside the owner object.
  • thisArgs: It’s a new object in which we are going to use the owner object’s method.
  • Arg1, Arg2, Arg3,…,ArgN: These are the arguments passed into the method of the owner object.

NOTE: Functions are first-class-citizens in JavaScript. That’s why we can assign a function to a variable as a value but without parentheses. Such as:

const sum = function (a, b) {

  return a + b;

};

const assignedFunction = sum;

How to implement the call() method

Coming back to the previous example, To extract the method of the object, we need to keep it in another variable. And we already know that we can assign a function to a variable as a value.

  1. So, first of all, we need to assign the method of the owner object into a separate variable, but without parentheses. We are not going to call the function instead, we are storing the function as a value in a variable. Such as:

creator1.intro; // It’s a function as a value.

  1. Now we have to invoke the call() method using the dot(.) operator followed by the name of the function with parentheses. Like:

creator1.intro.call(); // Invoking the call() method.

  1. And in the next step, we need to pass the new object in which the owner object’s method is being used as the argument of the call() method.

creator1.intro.call(creator2); // Pointing the “this” keyword to the creator2 object.

  1. Finally, if the method of the owner object received any parameters, then it needed to pass them as the second, third, … arguments of the call method.

creator1.intro.call(creator2, arg1, arg2,…, argN); // Passing arguments.

Since in our case, there are no requirements for any arguments to the call() method, that’s why we did not pass any second arguments to it.

Here is the complete code:

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

  intro() {

    console.log(`${this.name} is a ${this.niche}.`);

  },

};

creator1.intro(); // Ajay Yadav is a Front-end developer.

let creator2 = {

  name: “Gulam Anas”,

  niche: “Flutter developer”,

};

creator1.intro.call(creator2); //Now the “this” keyword is pointing to the “creator2” object.

creator2.intro(); // Gulam Anas is a Flutter developer.

Pass an argument to the call() method

Let’s suppose I want to pass 24_000 as the argument to the object’s method. In this example, 24_000 is an argument that is passed to the intro() function.

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

  intro(followers) {

    console.log(

      `${this.name} is a ${this.niche} and he has ${followers} followers.`

    );

  },

};

let creator2 = {

  name: “Gulam Anas”,

  niche: “Flutter developer”,

};

creator1.intro.call(creator2, 6_000); //Now the “this” keyword is pointing to the “creator2” object.

We can also pass more than one argument by the call() method to the object’s method, here is how:

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

  intro(followers, platform) {

    console.log(

      `${this.name} is a ${this.niche} and he has ${followers} followers on ${platform}.`

    );

  },

};

let creator2 = {

  name: “Gulam Anas”,

  niche: “Flutter developer”,

};

creator1.intro.call(creator2, 6_000, “Twitter”); //Now the “this” keyword is pointing to the “creator2” object.

Let’s improve the code

Since functions are first-class-citizen in JavaScript that’s why we can store them into a variable. Now we do not need to use the dot (.) operator twice. So, the intro() function is now assigned to the creatorMethod variable. Like:

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

  intro(followers, platform) {

    console.log(

      `${this.name} is a ${this.niche} and he has ${followers} followers on ${platform}.`

    );

  },

};

const creatorMethod = creator1.intro; // But without parenthese.

let creator2 = {

  name: “Gulam Anas”,

  niche: “Flutter developer”,

};

creator1.intro.call(creator2, 6_000, “Twitter”); //Now the “this” keyword is pointing to the “creator2” object.

creator1.intro(24000, “Twitter”) === creatorMethod(24000, “Twitter”) ?

Is it both declarations are the same thing? What do you think?

Well, NO…

const creatorMethod = creator1.intro; // Assign the method to a variable.

creatorMethod(24000, “Twitter”); // But in case “this” is not pointing to anywhere, in result undefined.

creator1.intro(24000, “Twitter”); // “this” points to the “creator1” object.

Let’s discuss more about it:

creator1.intro(24000, “Twitter”);

When you call creator1.intro(24000, “Twitter”);, you are directly invoking the intro method on the creator1 object. In this context, the this keyword inside the intro method refers to the creator1 object, and the method executes successfully.

creatorMethod(24000, “Twitter”);

However, when you assign the creator1.intro method to the creatorMethod variable and then try to call creatorMethod(24000, “Twitter”);, the context (the object to which this refers) is lost.

In this case, creatorMethod is treated as a regular function, and the this keyword is no longer associated with any object. Therefore, the code will not work as expected because of this.name and this.niche inside creatorMethod will not refer to any specific object, and it will result in an error.

But to make the creatorMethod call work properly, you can use the call() method here as well, as you did in your creator2 object.

creatorMethod.call(creator1, 24000, “Twitter”);

Separate everything, then apply call()

There is no need to put a method or function inside an object; instead, any function can be used as a method of the object.

According to me, we can say that the call() method defines the direction of the this keyword.

// Separate function

const intro = function (followers, platform) {

  console.log(

    `${this.name} is a ${this.niche} and he has ${followers} followers on ${platform}.`

  );

};

// Object 1

let creator1 = {

  name: “Ajay Yadav”,

  niche: “Front-end developer”,

};

// Object 2

let creator2 = {

  name: “Gulam Anas”,

  niche: “Flutter developer”,

};

// Using the call(), the “this” keyword points to the desired object according to our needs.

intro.call(creator1, 24000, “Twitter”);

intro.call(creator2, 6000, “Twitter”);

Conclusion

To conclude, the call() method is a crucial part of JavaScript, as it allows us to control the context in which functions are executed. Its importance lies in its ability to improve code readability, maintainability, and the overall design of JavaScript applications. As developers continue to explore the intricacies of the language, mastering the use of call contributes to a more comprehensive understanding of JavaScript’s capabilities.

Also, if you are looking for a JavaScript or React job, please search for them on Talent500.co

The post Demystified the call() method in JavaScript appeared first on Talent500 blog.

]]>
https://talent500.com/blog/demystified-the-call-method-in-javascript/feed/ 0
A Complete Guide to Loops and their Types in JavaScript https://talent500.com/blog/a-complete-guide-to-loops-and-their-types-in-javascript/ https://talent500.com/blog/a-complete-guide-to-loops-and-their-types-in-javascript/#respond Tue, 25 Apr 2023 11:27:29 +0000 https://talent500.com/blog/?p=37050 JavaScript is a versatile programming language that allows developers to create interactive and dynamic web applications. One of the fundamental […]

The post A Complete Guide to Loops and their Types in JavaScript appeared first on Talent500 blog.

]]>
JavaScript is a versatile programming language that allows developers to create interactive and dynamic web applications. One of the fundamental programming concepts in JavaScript, as in many other languages, is the use of loops. 

Loops are a powerful tool that allows developers to repeat a block of code multiple times, which can save time and reduce the amount of code needed. 

In JavaScript, there are several types of loops that can be used depending on the situation and the desired outcome. In this article, we will explore the different types of loops in JavaScript and how they can be used effectively in web development. Whether you are a beginner or an experienced developer, understanding these loops can help you write more efficient and effective code. 

So, let’s dive in and explore the different types of loops in JavaScript.

Overview

A loop in JavaScript allows us to execute a block of code repeatedly. It is used to automate repetitive tasks and perform complex operations with ease. Loops are an essential part of any programming language, including JavaScript, and play a vital role in developing dynamic and interactive web pages.

JavaScript provides several loops, including for loops, while loops, do-while loops, for-in loops, etc. Each type of loop has its own unique syntax and functionality, making it suitable for specific use cases.

Let’s suppose we have four HTML elements and we want to listen to some events in each of the boxes. Then, how can we achieve this goal?

Yes, in this case, we can use the power of loops instead of listening to events in each of the boxes individually. We can listen to events on all of the boxes by looping through the HTML elements.

HTML Code:

    <div>Box-1</div>

    <div>Box-2</div>

    <div>Box-3</div>

    <div>Box-4</div>

In the above code snippet, there are four HTML elements, and we want to listen to a click event for all the boxes. So instead of listening to events individually, we can select all HTML elements using JavaScript selectors, and it returns a NodeList (in other words, a list of HTML elements).

  const box = document.querySelectorAll(“div“);

  console.log(box); //NodeList (like an array)

In the above code snippet, I have selected all div HTML elements in JavaScript using the querySelectorAll() method, which returns a NodeList.

 

Now, this NodeList can be easily iterated using the built-in JavaScript loops, I am going to use a type of loop that is called forEach. Have a look at the below code snippet and codepen link as well. Do not worry; we are going to take a closer look at this below-loop code later in this article.

 

  const box = document.querySelectorAll(“div“);

  console.log(box); //NodeList(like an array)

  box.forEach(function (element) {

  box.addEventListener(“click“, function () {

       alert(“Button clicked!“);

    });

 });

 

Play with the codepen link: Click here

 

As you can see, loops help us to write quick and concise code. If there are no loops in JavaScript, then we need to listen to those events individually, which is time-consuming and inefficient at the same time. That’s why in this blog we are going to see the different types of loops in JavaScript.

For Loop

For loop allows us to repeat a block of code a specific number of times. It’s commonly used for iterating over arrays and other collections of data, and it can be customized with initialization, condition, and increment/decrement statements.

This is the following syntax of the for loop:

      for(initialization; condition; increment/decrement){

        // Lines of code to be executed.

      }

Where, 

  • Initialization: This statement is executed before the loop starts. It is usually used to declare and initialize a counter variable.
  • condition: The condition statement is evaluated before each iteration of the loop. If the condition is true, the code block is executed. If the condition is false, the loop exits and jumps to the next line of code.
  • increment/decrement: The increment or decrement statement is executed after each iteration of the loop. This is usually used to update the counter variable.

 

Suppose we have an array of objects (see the below code) and want to display this data on a web page in a tabular form. So instead of displaying individually, we can use a loop to show this data on a page.

Why am I using this type of format as an example? Because when we fetch data from the remote server or APIs, they will provide data similar to this format. That’s why I am using an example to mimic the data coming from an API.

 const userData = [

 { id: 1, user: “Ajay“, userAddress: “Patna“ },

 { id: 2, user: “Pranav“, userAddress: “Banglore“},

 { id: 3, user: “Anas“, userAddress: “Delhi“ },

];

console.log(userData); //Array of objects

Now we have an array, and there are three items kept inside this array. The index of the first object is 0, for the second object it is 1, and for the last object, it is 3. Also, each object has three key-value pairs: id, user, and userAddresses, as you can see in the above code snippet.

Now we can easily display this data on the web pages in tabular form using for loops, as shown in the below image. However, this can be done using the map() method as well; I have covered this topic in detail. So please refer to this article from talent500.


HTML Code

   <h1>Fetching user data from the remote server…</h1>

    <hr />

    <table>

      <thead>

        <tr>

          <th>Id</th>

          <th>Name</th>

          <th>Address</th>

        </tr>

      </thead>

      <tbody class=“dynamic“>

        <!– <tr”>

          <td>dummy</td>

          <td>dummy</td>

          <td>dummy</td>

        </tr> –>

      </tbody>

    </table>

 

JavaScript code:

 const userData = [

  { id: 111, user: “Ajay“, userAddress: “Patna“ },

  { id: 112, user: “Pranav“, userAddress:“Bangalore“ },

  { id: 113, user: “Anas“, userAddress: “Delhi“ },

      ];

      console.log(userData); //Array of objects

      let data = “”; //Empty data

      for (let i = 0; i < userData.length; i++) {

        data += ` <tr>

          <td>${userData[i].id}</td>

          <td>${userData[i].user}</td>

          <td>${userData[i].userAddress}</td>

        </tr>`;

      }

      document

        .querySelector(“.dynamic“)

        .insertAdjacentHTML(“beforebegin“, data);

 

In the JavaScript code, I looped through all objects inside the array and displayed the dynamic data on the web page.

 

Play with the codepen link: Click here

While loop

A while loop is another type of loop in JavaScript that allows a block of code to be executed continually while a particular condition remains true. The syntax of a while loop in JavaScript is as follows:

      while (condition) {

        // Lines of code

      }

The condition is an expression that is evaluated at the start of each iteration of the loop. If the condition evaluates to true, the code inside the loop will be executed. After the code is executed, the condition will be evaluated again, and if it still evaluates to true, the code is executed again. This process continues until the condition is evaluated as false.

Let’s iterate the above array of objects using a while loop.

      let data = “”; //Empty data

      let item = 0; // Let suppose the length of the array = 0

      while (item < userData.length) {

        data += ` <tr>

          <td>${userData[item].id}</td>

          <td>${userData[item].user}</td>

          <td>${userData[item].userAddress}</td>

        </tr>`;

        item++;

      }

 

The JavaScript code is used to iterate through an array of user data and generate an HTML table row (tr) for each element of the array.

 

First things first, I have initializes an empty string called data that will store the HTML table rows as they are generated.

 

Then I created a variable called an item that was initialised with 0. which will be used as an index to iterate through the userData array.

 

Now, the userData array is going to be iterated one by one using a while loop, that will iterate over each element in the userData array until the item index is equal to the length of the array.

 

Then,  generates an HTML table row (tr) for the current element in the userData array and appends it to the data string. The table row includes three table cells (td) that display the ‘id’, ‘user’, and ‘userAddress’ objects properties of the current element in the array. 

 

Finally, item++ increments the item index by 1 to move to the next element in the userData array. Once the while loop completes, the data string will contain all the HTML table rows generated from the userData array, which can be inserted into an HTML table to display the user data.

 

Play with the codepen link: Click here

Do-while Loop

A do-while is also a type of loop that executes a block of code at least once, and then repeatedly executes the block of code as long as a specified condition is true.

Here, the following sytax of the do-while loop:

      do {

        //code block to be executed

      } while (condition);

 

The block of the do statement will be executed first. Then, the while statement is evaluated. If the condition is true, the code block is executed again. If the condition is false, the loop ends and the program continues with the next statement.

 

      const userData = [

        { id: 111, user: “Ajay“, userAddress: “Patna“ },

        { id: 112, user: “Pranav“, userAddress: “Banglore“ },

        { id: 113, user: “Anas“, userAddress: “Delhi“ },

      ];

      let i = 0,

        data = “”;

      do {

        data += ` <tr>

          <td>${userData[i].id}</td>

          <td>${userData[i].user}</td>

          <td>${userData[i].userAddress}</td>

        </tr>`;

        i++;

      } while (i < userData.length);

      document

        .querySelector(“.dynamic“)

        .insertAdjacentHTML(“beforebegin“, data);

 

One of the main advantages of a do-while loop is that the code block is guaranteed to be executed at least once, regardless of the initial condition. 

 

This can be useful in situations where we want to ensure that a certain block of code runs at least once before checking a condition.

Play with the codepen link: Click here

 

forEach Loop

A forEach loop is a higher-order function that allows us to iterate over the elements of an array and perform a specific action on each element.

 

The forEach loop takes a callback function as its argument, which is executed for each element of the array. Here is the following syntax of the forEach loop:

 arr.forEach(function (currentValue, index, array) {

   // code to execute for each element

  });

 

The arr is the array that the loop is iterating over and forEach loop takes a callback function that is executed for each element of the array. The callback function takes three parameters:

  • currentValue: The current element represents each element in the loop.
  • index: It is the index of the current element of the array.
  • array: It is the original array that is being iterated over.

I have already shared an example of the forEach() method with you in the first section of this article, but you can also see the below example as being more simple.

      const arr = [10, 20, 30, 40, 50];

      arr.forEach((item) => console.log(item * 2));

 

In the above code snippets, there is an array called arr, and this array is iterating using the forEach method. This method takes a callback function that will execute for all the items in the array.

The item parameter represents each element of the array, and then we can do any operations using this item element.

Play with the codepen link: Click here

For-in Loop

A for-in loop is used to iterate over the properties of an object. It allows us to execute a block of code for each property in the object. Here is the syntax of this loop:

   for (key in object) {

       // code to be executed

     }

Syntax explained:

  • key: This is a key that is used to hold the name of each property in the object as the loop iterates over them. We can choose any valid variable name as the key of the object.
  • in: This is a keyword used to separate the variable from the object and indicates that the loop will iterate over the properties of the object.
  • object: This is the object that the loop will iterate over. It can be any object that has properties.

See the below code for more clarity:

      const user = { name: “Ajay“, Add: “Patna“, PhNo: “+91 432423432“ };

      for (const key in user) {

        console.log(key); //Returns the property name of the object.

        console.log(user[key]); //Returns the values of the object’s properties.

      }

Play with the codepen link: Click here

For-of Loop

A for-of is also a type of loop which provides an easy way to iterate over items of an iterable object. It is a more straightforward and expressive way to iterate over iterable objects.

Here is the syntax of the for-of loop:

      for (item of iterable) {

        // code to be executed for each element of iterable

      }

Syntax explained:

  • item: This is a variable that will be assigned to each element of the iterable object during each iteration of the loop. 
  • iterable: This is an object that is iterable, which means it has a collection of elements that can be accessed one by one using the for-of loop.

Here is the real-world example of for-of loop:

      const userData = [

        { id: 111, user: “Ajay“, userAddress: “Patna“ },

        { id: 112, user: “Pranav“, userAddress: “Banglore“ },

        { id: 113, user: “Anas“, userAddress: “Delhi“ },

      ];

      let data = “”;

      for (const item of userData) {

        data += ` <tr>

          <td>${item.id}</td>

          <td>${item.user}</td>

          <td>${item.userAddress}</td>

        </tr>`;

      }

In the above code snippets, the userData object will be iterated using the for-of loop, which returns an individual object each time. We can then easily append this data to the web page.

Play with the codepen link: Click here

Conclusion

In conclusion, JavaScript provides several types of loops, as we saw in the above discussion, which is used for iterating over collections of data or repeating a specific number of times. Iterable objects can be arrays, strings, maps, sets, and other objects. One more thing: there are multiple array methods in JavaScript that act like a loop, meaning they also execute callback functions like the forEach() loop. So please take care of these things as well.

Also, if you are looking for a JavaScript job, so please search them on talent500.com

The post A Complete Guide to Loops and their Types in JavaScript appeared first on Talent500 blog.

]]>
https://talent500.com/blog/a-complete-guide-to-loops-and-their-types-in-javascript/feed/ 0
5 Best websites to learn JavaScript coding for beginners https://talent500.com/blog/5-best-websites-to-learn-javascript-coding-for-beginners/ https://talent500.com/blog/5-best-websites-to-learn-javascript-coding-for-beginners/#respond Mon, 10 Apr 2023 07:41:38 +0000 https://talent500.com/blog/?p=33302 According to Atwood’s Law, “Any application that can be written in JavaScript, will eventually be written in JavaScript.” It proved accurate […]

The post 5 Best websites to learn JavaScript coding for beginners appeared first on Talent500 blog.

]]>
According to Atwood’s Law, “Any application that can be written in JavaScript, will eventually be written in JavaScript.”

It proved accurate as JavaScript is one of the major programming languages for building web apps. If you are beginning your journey as a developer, you should focus on learning JavaScript for web development. Even if you are an experienced programmer who never worked with web applications, learning this programming language will broaden your horizons. Once considered a strictly client-side language, Node.js now allows JavaScript to run both the front-end and back-end applications. Fortunately, there are several resources for beginners to learn JavaScript.

Here, we have compiled a list of the five best websites to learn JavaScript coding.

1. Udemy Free JavaScript Tutorials

Udemy is one of the best online resources for developers to learn and upskill. The website hosts free and premium online courses and tutorials in all technologies, including JavaScript, Java, Python, Spring, REST, Selenium, etc.

We recommend you use these tutorials for learning JavaScript as they are comprehensively structured for beginners to follow.

The Complete JavaScript Course 2022: From Zero to Expert!

The Complete JavaScript Course 2022: Build Real Projects

The Web Developer Bootcamp

While these courses are not free, their quality makes them a worthwhile investment. But, beginners can start with this free course first:

JavaScript Essentials

It teaches you the basic concepts of the languages and gives an overview of API design through a simple web project.

You may also like to read: Upskill With These Emerging Technologies to Propel Your Career

2. Pluralsight.com

Another great website to learn IT technologies. On Pluralsight, you will find many courses to learn programming languages like JavaScript. But it takes things a step further by allowing beginners to practice while they learn.

The site acquired CodeSchool, a live code editor that developers can use to write code through a browser to see how they worked. The best course on the site to learn JavaScript is the JavaScript Fundamentals by Liam Mclennan. While several free courses are available on Pluralsight, you should take its premium membership for the best courses. A membership gives you access to over 5000+ online courses, interactive quizzes, exercises, and certification material.

3. Coursera JavaScript foundation courses

Like Udemy, Coursera is an excellent online learning platform that offers quality JavaScript tutorials and courses. Founded by Stanford professors Andrew Ng and Daphne Koller, the platform grew fast and became one of the leading online degree platforms for IT professionals.

Learning JavaScript on Coursera will be a different experience. For instance, the course’s progress in a curriculum is similar to universities and you get a certification on completion. The website offers courses enabled by renowned universities like Stanford, University of London, Imperial College of London, University of Michigan, and Colorado.

Some of the best courses to learn JavaScript on Coursera are:

Programming Foundations with JavaScript, HTML, and CSS

Interactivity with JavaScript

HTML, CSS, and JavaScript for Web Developers

Beginners can get a good grasp of JavaScript with these courses. Furthermore, on completing courses, Coursera offers you a certification that you can showcase on your LinkedIn profile.

4. Freecodecamp.org

This website is a community-driven learning platform for beginners to learn how to code for free, build real-world projects, and land a job as a developer.

Freecodecamp.org has a massive repository of interactive tutorials and practice courses for learning JavaScript and other web development concepts. Many coders find this website a lot more interactive as it provides them with tools to learn through doing. You will also be able to connect with fellow learners and experienced programmers who mentor beginners. You will find over 2000 JavaScript courses on this website that are entirely free. Apart from that, Freecodecamp has a robust Facebook Group and Medium blog where they share articles and resources on trending topics and technologies.

You may also like to read: Best free professional coding resources to try in 2023

5. Codecademy

Many first-time coders learn JavaScript from Codecademy as it offers a learning curriculum different from other websites listed here. The website has designed a crisp and easy-to-follow JavaScript course that helps beginners learn the essential concepts of the programming language at an accelerated pace.

The Introduction of JavaScript Course teaches developers both the programming language’s front-end and back-end aspects. The course is self-paced, so beginners can pause in between or revisit a concept later. This is why this JavaScript course for beginners has over 5 million enrolled students.

In this free course, developers get introduced to the most common concepts of JavaScript, such as functions, scopes, conditionals, arrays, and iterations. Then the course moves on to intermediate-level skills such as APIs and frameworks. Finally, you put your learnings to the test by building games and interactive websites.


Conclusion

JavaScript is the language of the web. If you want to get into web development, you must learn the concepts of the language well. Also, companies expect both front-end and back-end developers to know at least one JavaScript framework. The websites we listed here are the best resources to get started with JavaScript.

Talent500 is the platform for competent developers to discover career redefining opportunities with fast-growing global startups and Fortune 500 companies. Join us today!

 

Related Articles

Most Popular Articles

Our Other Articles

 

The post 5 Best websites to learn JavaScript coding for beginners appeared first on Talent500 blog.

]]>
https://talent500.com/blog/5-best-websites-to-learn-javascript-coding-for-beginners/feed/ 0
What is new in Next JS 13? https://talent500.com/blog/what-is-new-in-next-js-13/ https://talent500.com/blog/what-is-new-in-next-js-13/#respond Mon, 09 Jan 2023 08:48:55 +0000 https://talent500.com/blog/?p=35722 What is new in Next JS 13? Next.JS is a JavaScript framework that enables you to build superfast and user-friendly […]

The post What is new in Next JS 13? appeared first on Talent500 blog.

]]>
What is new in Next JS 13?

Next.JS is a JavaScript framework that enables you to build superfast and user-friendly static websites, as well as dynamic web applications using React. Compared to other competitors in the market, Next.JS offers many advantages.

Over 2,400 individual developers, as well as the core team and business partners like Google and Meta, contributed to the creation of Next.JS. One of the most well-liked techniques for building the Web is Next.JS, which receives over 4.2 million npm dowaàanloads weekly and 96,300 GitHub stars.

As per npmjs, Next.JS garners close to 4,214,306 weekly downloads, whereas React, its parent, has 19,247,427 weekly downloads. 

                  Source: https://npmtrends.com/next-vs-react

At the recent Next.JS conference, Next.JS 13 was released. Many new features are included, including routing, a new way to fetch data (React suspense), Vercel fonts, OG image generation, and layouts.

In this detailed blog, we are going to cover all the new changes that have been introduced in Next.JS 13. 

So let’s get started!

 

Is Next.JS 13 something we should know?

Next.JS has been a popular React-based framework for a long time. Vercel, the Next.JS creators, recently announced that Next.JS 13 is now live. Some of the advantages of using Next.JS have been listed below.

Great SEO: Using Next.JS will improve your SEO results a lot. Because Next.js websites are fast, easy to scan and provide a great user experience, Google will favor them above others.

Lesser loading time: Because static websites are fast by nature, Next.JS web apps and websites will perform well.

Image optimization. Next.JS has built-in image components and automatic image optimization, which will optimize all the images used in it.

Fast Refresh: Next.JS is a developer-friendly tool; one reason for this is that changes made during development are immediately visible on the website; there is no need to reload the entire server.

Great developer experience: This is the most appreciated part of Next.JS. We will spend more time writing features for our application than working on build tools and configuration.

Automatic code splitting: Each page in your Next.js is code split automatically. This means that your application’s bundle size will not increase as it adds more and more pages.

There are several more reasons why Next.JS is preferred over its competitors, like Gatsby.

 

What are the changes in Next.JS 13?

Next.JS 13 has introduced many new features that have the potential to be really game-changing and incredibly fast. Some APIs have been added to the stable core and are now recommended for use, while others are still under the experimental label.  Let’s look at the most interesting features of the new release.

Turbopack – A Rust-powered successor to Webpack

Until now, Next.JS used Webpack as a module bundler under the hood, but in version 13, they introduced Turbopack, a rust-based successor to Webpack, which is a game changer.

This is unquestionably one of the best developments for Next.JS and Turbopack.  The next-generation bundler for the Web will be a brand-new build tool called Turbopack, which is being led by Tobias Koppers, the man who created Webpack. It was built from the ground up, with rust. 

Source: https://turbo.build/pack

Turbopack is blazingly fast. Turbopack takes up to 1.8 seconds during startup compared to Webpack, which takes 16.5 seconds. Using Turbopack alpha with Next.JS 13 makes your app update 700x faster than Webpack, 10x faster than Vite, and 4x faster than Webpack cold starts. This is something huge for the entire ecosystem.

According to the Turbopack team, Turbopack has incremental behavior and adaptable bundling strategies; Turbopack provides a fast and flexible development experience for apps of any size.

Although it is currently in alpha, Webpack has a massive ecosystem of plugins that can make migration difficult for existing apps. Since this feature is experimental, we can only use it in the development environment, and it is not supported for production builds as of now.

 

New Routing System

Next.JS has a built-in routing system, and when we add new files to the pages folder, it will automatically create routes in our application. 

With the introduction of the app directory, Next.JS is enhancing the routing and layout experience and aligning with the future of React. The app directory file-system-based router is an upgrade to the Next.js page routing system. This feature is currently in beta, and more features are likely to come soon.

The app directory includes support for:

  • Layouts: Easily share user interface (UI) between routes while maintaining state and preventing costly re-rendering.
  • Server Components: Making server-first the default for the most dynamic applications.
  • Streaming: Show instant loading states and stream in UI units as they are rendered.
  • Support for Data Fetching: The async Server Components and extended fetch API supports component-level fetching.

All of these bring new possibilities for improving the performance of the app as well as the framework.

 

Data Fetching

One of the features offered by the app directory is a powerful new method of data fetching built on top of React Suspense for Data Fetching.

This is significant because it allows us to completely replace previous Next.js APIs like getStaticProps and getServerSideProps and write a plain JavaScript function that uses fetch and then awaits the result of that function directly. 

The new data fetching system works in the app directory and is built on top of the fetch() Web API.  You can use async/await to asynchronously fetch data in server components created with JavaScript await syntax, with performance benefits such as automatic caching.

 

The Image Component

The powerful new Image component in Next.js 13 makes it simple to display images without layout shifting and allows you to perform on-demand file optimization for better performance.

According to the Vercel team, the new Image component has various merits, like:

  • It now ships lesser client-side JavaScript
  • Now, styling and configuration options are simpler than before.
  • More accessible and it requires alt tags by default
  • Faster because native lazy loading doesn’t require hydration
  • Align with the Web platform,

 

Updates to next/link

The new next/link component no longer needs manually adding an <a> tag as a child!

import Link from “next/link”

//Next.js 12: <a> has to be nested inside <Link> for client-side navigation to work.

export default function Test() {

    return (

        <Link href=”/”>

        <a>Home</a>

        </Link>

    )

    }

//Next JS 13: <Link> always render <a>

export default function Test() {

    return (

        <Link href=”/”>

        Home

        </Link>

    )

    }

A new font system – @next/font

The Next.js team has unveiled a totally new font system. With performance and privacy in mind, you can use all Google fonts with this new system. 

Some of the advantages of this new font system include:

  • It will automatically optimize all of the fonts.
  • It removes the hazard of external network requests for improved privacy and performance
  • During build time, CSS and font files are downloaded and self-hosted along with the rest of your static assets.
  • While still ensuring great performance and no layout shift, you can customize every aspect of the font loading process.
  • Custom fonts are also supported.

 

Open Graph Image Generation

To generate dynamic social cards, the Vercel team introduced the @vercel/og library that works seamlessly with Next.js. A social card is a description, image, and title that appears when you share your website link on another social platform. Social cards are important as they can result in higher conversion rates.

With this library, a dynamic social card can be created that can be personalized and computed on the fly.

import { ImageResponse } from “@vercel/og”;

export default function () {

  return new ImageResponse(

    (

      <head>

        <title>Title</title>

        <meta property=’og:title’ content=’Title’ />

        <meta property=’og:description’ content=’Description’ />

        <meta property=’og:image’ content=’https://example.com/image.png’ />

      </head>

    )

  );

}

 

What are the breaking changes in the Next 13?

When there is a significant update, we need to migrate to the most recent version by following a few steps. The situation with Next 13 is also the same. The following lists a few of Next 13’s ground-breaking changes.

  1. The bare minimum React version for Next.JS 13 is React v18.2.0.
  2. Since Node 12.x has reached end-of-life, the minimum Node.js version has been increased from 12.22.0 to 14.6.0.
  3. The next/image import was renamed to next/legacy/image. The next/future/image import was renamed to next/image.

 

import Image1  from “next/image”

import Image2  from “next/future/image”

// Changes to 👇🏻👇🏻👇🏻

import Image1 from “next/legacy/image”

import Image2 from “next/image”

4. The Routes are now no longer prefetched when the User-Agent is set to bot.

5. The next/link child can no longer be <a>.

export default function Page() {

return(

        <Link href=”/about”>

            <a>About</a>

        </Link>

    )

}

// 👇🏻👇🏻👇🏻👇🏻

export default function Page() {

    return(

        <Link href=”/about”>

          About

        </Link>

    )

}

6. The deprecated target option of next.config.js has been removed.

7. Internet Explorer has been removed from the list of supported browsers in favor of more recent ones. You can still use Browserslist to change targeted browsers.

    1. Chrome 64+
    2. Edge 79+
    3. Firefox 67+
    4. Opera 51+
    5. Safari 12+

We have seen the notable features of Next. JS 13 and now we can look into how we can actually migrate to Next 13.

 

Migrating to NextJS 13

In order to use NextJS 13, we need to have a minimum Node.JS version of v14.6.0. You can upgrade to the latest version, which is 18.12.1, or version 14.6.0 itself.

To update to Next.js version 13, run the following command using your preferred package manager:

npm install next@latest react@latest react-dom@latest eslint-config-next@latest

# or

yarn add next@latest react@latest react-dom@latest eslint-config-next@latest

# or

pnpm update next@latest react@latest react-dom@latest eslint-config-next@latest

After upgrading the versions, you can start upgrading to the latest new features in Next 13 such as using the updated Image component, Link component, Script component, Font optimization, etc.

Wrapping It Up!

Congratulations on reaching this far! You’re a fantastic reader!!

In this detailed blog on Next.js, we looked at the new changes that have been introduced in Next.js. Next.js is one of the popular front-end frameworks and aids in building the Web, and it’s constantly evolving. 

We have covered all the important new features that are included with NextJS 13. Not only that, but we have also covered the breaking changes and steps to migrate our Next app.

You now have a thorough understanding of everything that Next 13 has to offer.

Happy Nexting!

 

 

The post What is new in Next JS 13? appeared first on Talent500 blog.

]]>
https://talent500.com/blog/what-is-new-in-next-js-13/feed/ 0
Skills you need to get a job as a JavaScript developer https://talent500.com/blog/skills-you-need-to-get-a-job-as-a-javascript-developer/ https://talent500.com/blog/skills-you-need-to-get-a-job-as-a-javascript-developer/#respond Mon, 09 Jan 2023 05:40:52 +0000 https://talent500.com/blog/?p=35676 Skills you need to get a job as a JavaScript developer   JavaScript is one of the most widely used […]

The post Skills you need to get a job as a JavaScript developer appeared first on Talent500 blog.

]]>
Skills you need to get a job as a JavaScript developer

 

JavaScript is one of the most widely used programming languages. Originally used as a scripting language, JavaScript is now used in a wide range of industries, such as web development, app development, machine learning, robotics, augmented reality and virtual reality, 3D modeling, game development, and more. 2022 marks JavaScript’s tenth consecutive year as the most commonly used programming language. according to the Stackoverflow survey of 2022.

source

Throughout this detailed blog, we will discuss the various skills JavaScript developers need to have in order to get hired in 2023 and beyond. So let’s get started!

HTML & CSS

A JavaScript developer should be proficient in HTML and CSS. Despite the fact that JavaScript is independent of HTML and CSS, working with JavaScript almost certainly involves the use of some HTML and CSS.

JavaScript is unquestionably the most used browser-related programming language, and HTML and CSS are what give a webpage its structure, style, and layout.  Having a good knowledge of HTML and CSS can help us ace our career as a JavaScript front-end developer.

JavaScript, a dynamic scripting language, enables you to create mobile apps and interactive websites. JavaScript is a simple programming language that communicates with application program interfaces (APIs). There are several browser APIs with which we can interact with the help of JavaScript. This ability enables front-end developers to quickly and easily create complex interactions on their websites, resulting in the best possible user experience.

 

CSS framework and libraries

CSS frameworks & libraries are code libraries that developers use to make designing websites easier and more efficient. CSS frameworks are collections of pre-written CSS code that can be added to a website in order to style the pages without having to write CSS code from scratch. CSS frameworks typically include HTML and CSS code for typography, forms, buttons, navigation bars, tables, etc.

Some of the most popular CSS frameworks are:

Tailwind CSS: Tailwind CSS is one of the most widely used CSS frameworks. Each month, nearly 13 million people download this utility-first framework. Designing your website is flexible and free. The advantage of Tailwind CSS is that it can be customized to meet individual requirements. You can override Tailwind CSS’s default configuration. The utilities and components of Tailwind can be easily customized.

 

Bootstrap: Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. It includes HTML, CSS, and JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components. There are many other options for CSS frameworks and libraries, in fact, there are many animation libraries and utility libraries that you can learn and it is a good skill to have.

 

Understanding how JavaScript works

Frameworks and libraries come and go, but the fundamentals never change. If the fundamentals are understood, it is simple to build any type of application and learn to use any framework or library. Despite the importance of JavaScript in web and mobile development, many hiring managers are unaware of what they require in a JavaScript developer. 

Here are 10 important and must-know topics for you that will be handy.

  • Scope
  • Hoisting
  • Callbacks
  • Promises
  • Asynchronous JavaScript
  • Closure
  • Modular programming
  • Regex
  • Concurrency model and event loop
  • Writing clean and self explanatory code

 

Browser APIs

Browsers provide a variety of APIs for interacting with web applications. 

Using web APIs, we can easily implement certain features with fewer lines of code, such as:

  • making network requests like fetching the data
  • managing client-side storage
  • retrieving device media streams, etc.

Some of the important APIs are listed below:

  1. Fetch API: This API allows users to fetch resources (including those across networks).
  2. Canvas API: The Canvas API allows graphics to be drawn using JavaScript and the HTML <canvas> element. It can also be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.
  3. Geolocation API: The Geolocation API allows web applications to receive a user’s location. User permission is required to report location information for privacy reasons.
  4. There are many other useful APIs that the browser provides.

 

Data Structures and Algorithm

Currently, many companies conduct DSA-based interviews, so knowing how to store, retrieve, search, insert, and remove data efficiently is essential. We should also understand which type of data structure is suitable for a particular set of data. Algorithms are defined, step-by-step instructions for producing a result or output. The algorithms assist you in developing an efficient and valid formula for performing any data set operation. Searching, sorting, traversing, and other basic algorithms are essential for any developer.

 

JavaScript Frameworks and Libraries

The number of JavaScript libraries is currently 1,444,231, but more will be added in the future. There are some front-end libraries and frameworks that have gained popularity in the community and on the job market. The following are some of the top libraries and frameworks you might need to know.

React JS: React JS is a widely preferred frontend JavaScript library used in nearly 50 million projects every month. Backed by Facebook, React has had its dominance in the web development space for over nine years. Most of the big tech companies use React, like Facebook, WhatsApp, Instagram, Twitter, Binance, and the list goes on.

Angular: Angular is a framework and platform that uses HTML and TypeScript to build single-page client apps. The Angular framework is written in TypeScript. You import TypeScript libraries into your applications to implement core and optional functionality. Angular is backed by Google, and it is one of the best choices for web application development.

Vue.JS: Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web. One of the well-known web development frameworks is this one. The view layer is the main focus of VueJS, considering the MVC architecture. It can be seamlessly integrated into large front-end development projects.

The list goes on with several other popular libraries like Svelte, Remix, NextJS, Gatsby, Laravel, and so on.

 

NodeJS

Node.JS is a free and open-source Javascript runtime environment. It is multi-platform and works with Windows, Linux, Unix, Mac OS, etc.  Node.js is designed to build scalable network applications. Now that NodeJS is available, JavaScript can be used outside of a browser. 

Node JS has been the foundation for a number of frameworks. ExpressJS is one of the most well-liked NodeJS frameworks. Express is a minimal, open-source, and flexible Node.js web app framework designed to make developing websites, web apps, & APIs much easier. It is a web framework that enables you to organize a web application to manage various HTTP requests at a particular url.

 

Package manager

A programming language’s tool for setting up project environments and quickly importing external dependencies is called a package manager. The package manager allows you to install and uninstall dependencies for your project without having to create anything from scratch. Some of the most popular package managers for Javascript are:

Npm: Npm is a JavaScript package manager that is supported by npm, Inc. Node.js’s package manager by default is npm. Node.js is a JavaScript runtime environment. It consists of a command-line client, also known as npm, and the npm registry, an online repository for both free and paid private packages.

Yarn: In 2016, Facebook created a software packaging system called Yarn for the Node.js JavaScript runtime environment. In order to address issues with consistency, security, and performance with large codebases, Facebook, Exponent, Google, and Tilde collaborated to develop Yarn, an alternative to the npm package manager.

PNPM: PNPM is an alternative package manager for Node. js which stands for “Performant NPM”. The main objective of PNPM is to keep all the packages in one place (centralized) and make them available to other projects via hard links when necessary.

 

Module bundlers

A module bundler is a supporting tool that takes logical JavaScript files and their dependencies and bundles them into a single file.  When your project grows too big for a single file or you’re working with libraries that have a lot of dependencies, it is ideal to use a Module bundler.

Some of the popular module bundlers are:

Webpack: Webpack is a free and open-source module bundler for JavaScript. Although it is designed primarily for JavaScript, it can also modify front-end assets like HTML, CSS, and images if the appropriate loaders are also present. Webpack creates static assets that represent modules with dependencies.

Vite: Vite is a modern front-end build tool that provides an extremely fast development environment and bundles your code for production. The environment provided by Vite has several features, including instant server start, faster hot module replacement, optimized build, support for TypeScript, JSX, CSS, and more.

There are many more module bundlers and development tools that you can look into further.

 

TypeScript

TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. It is designed for the development of large applications and translates to JavaScript. As it introduces optional types to JavaScript, our code will be less error-prone. Many companies said shifting their codebase from JavaScript to TypeScript helped them to have 50% fewer bugs.

Git and GitHub

Git is free and open source software for distributed version control: tracking changes in any set of files, typically used for coordinating work among programmers collaboratively developing source code during software development, according to wikipedia. To put it simply, we can keep track of our project and take a snapshot at a specific point, as well as go back and forth.

Github, on the other hand, is a platform for hosting code for version control and collaboration. It allows you and others to collaborate on projects from anywhere.  It includes access control, bug tracking, software feature requests, task management, continuous integration, and wikis for each project, in addition to Git’s distributed version control.

 

Testing

The purpose of software testing is to ensure that a piece of software or code works as intended. In order to avoid problems caused by bugs, every project must undergo testing. So, a developer should be able as well as the ability to debug and test code.  

It is not necessary for a JavaScript developer to do this. In order to ensure quality, understanding how end-to-end and component testing work is a huge advantage. Cypress, Selenium, and others are some of the most popular testing tools in the market.

 

Wrapping It Up!

Congratulations on reaching this far! You’re an excellent reader! Even though there are many topics a developer should know, you can always learn on the go. It is important to be open to learning and the more you learn, the more money you will earn.This detailed blog discussed various skills that a JavaScript developer should possess in order to be job-ready. You can start your career as a JavaScript developer by following this blog.

Happy Coding!

 

The post Skills you need to get a job as a JavaScript developer appeared first on Talent500 blog.

]]>
https://talent500.com/blog/skills-you-need-to-get-a-job-as-a-javascript-developer/feed/ 0
How to Bundle JavaScript With Rollup https://talent500.com/blog/how-to-bundle-javascript-with-rollup/ https://talent500.com/blog/how-to-bundle-javascript-with-rollup/#respond Tue, 03 Jan 2023 06:08:04 +0000 https://talent500.com/blog/?p=35573 How to Bundle JavaScript With Rollup Introduction Rollup.js focuses largely on JavaScript (although there are plugins for HTML templates and […]

The post How to Bundle JavaScript With Rollup appeared first on Talent500 blog.

]]>
How to Bundle JavaScript With Rollup

Introduction

Rollup.js focuses largely on JavaScript (although there are plugins for HTML templates and CSS). It offers a bewildering number of options, but it’s simple to get started and bundling is quick.

Other bundler choices, such as webpack, Snowpack, and Parcel, claim to magically manage everything: HTML templating, image optimization, CSS processing, JavaScript bundling, and more. This works well when you’re satisfied with the default settings, but changing customizations can be tricky

Prerequisites

  • Basic knowledge of JavaScript.
  • Being Familiar with ES2015 modules doesn’t hurt, either.
  • Installing npm on your machine.

What Is Rollup?

Rollup is a next-generation JavaScript module bundler. Create your app or library with ES2015 modules, then effectively bundle them into a single file for usage in browsers and Node.js. It’s identical to Browserify and webpack.

Using Rollup to Process and Bundle JavaScript Files

Step 1: Create a compiled JavaScript and CSS project.

You need to have some code to work in order to get started. You can get an app available on GITHUB to work on.

The structure of the folder looks like this:

learn-rollup/

├── build/

│ └── index.html

├── src/

│ ├── scripts/

│ │ ├── modules/

│ │ │ ├── mod1.js

│ │ │ └── mod2.js

│ │ └── main.js

│ └── styles/

│ └── main.css

└── package.json

By running the following command you can install the app we’ll be working with into your terminal.

# Move to the folder where you keep your dev projects.

cd /path/to/your/projects

# Clone the starter branch of the app from GitHub.

git clone -b step-0 –single-branch https://github.com/jlengstorf/learn-rollup.git

# The files are downloaded to /path/to/your/projects/learn-rollup/

 

Create a configuration file after Installing Rollup

With following command, Get started with installing Rollup:

npm install –save-dev rollup

You need to create a new file called rollup.config.js in the learn-rollup folder and add the following.

export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

};

 

Test the Rollup configuration

You can test Once we’ve created the config file, we can test that everything is working by running the following command in our terminal:

./node_modules/.bin/rollup -c

A folder called as build in your projects will be created with a js subfolder which contains generated main.min.js file.

You can see the bundle that was created properly by opening build/index.html in the browser:

The example shows how the project will look like.

 

Look at the Bundled Output

(function () {

  ‘use strict’;

  /**

   * Says hello.

   * @param  {String} name a name

   * @return {String}  a greeting for `name`

   */

  function sayHelloTo(name) {

const toSay = `Hello, ${name}!`;

return toSay;

  }

  /**

   * Adds all the values in an array.

   * @param  {Array} arr an array of numbers

   * @return {Number} the sum of all the array values

   */

  const addArray = (arr) => {

const result = arr.reduce((a, b) => a + b, 0);

return result;

  };

  // Import a couple modules for testing.

  // Run some functions from our imported modules.

  const result1 = sayHelloTo(‘Jason’);

  const result2 = addArray([1, 2, 3, 4]);

  // Print the results on the page.

  const printTarget = document.getElementsByClassName(‘debug__output’)[0];

  printTarget.innerText = `sayHelloTo(‘Jason’) => ${result1}\n\n`;

  printTarget.innerText += `addArray([1, 2, 3, 4]) => ${result2}`;

})();

//# sourceMappingURL=data:application/json;charset=utf-8;base64,…

 

Step 2: To use a new Javascript features set up the Babel

We now have a code bundle that will work in modern browsers, but it will break if the browser is more than a couple versions old in some cases — not ideal.

Install the required modules

First, we must install the Babel Rollup plugin and the corresponding Babel preset.

Installing Rollup’s Babel plugin

npm install –save-dev rollup-plugin-babel

Installing the Babel preset for transpiling ES2015

npm install –save-dev babel-preset-es2015

Installing Babel’s external helpers for module support

npm install –save-dev babel-plugin-external-helpersCreate a .babelrc.

Next, in the root directory of your project (learn-rollup/), create a new file called.babelrc. Add the following JSON inside:

{

  “presets”: [

[

   “es2015”,

   {

     “modules”: false

   }

]

  ],

  “plugins”: [“external-helpers”]

}This tells Babel which preset it should use during transpiling.

 

Update rollup.config.js

To make this work, we need to alter rollup.config.js.

We import the Babel plugin inside, then add it to a new configuration variable called plugins, which will store an array of plugins.

// Rollup plugins

import babel from ‘rollup-plugin-babel’;

export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

  plugins: [

babel({

   exclude: ‘node_modules/**’,

}),

  ],

};

We set an exclude config property to ignore the node modules directory to avoid transpiling third-party scripts.

 

Check the bundle output

We can recreate the bundle now that everything is installed and configured:

./node_modules/.bin/rollup -c

When we look at the output, we see that it is basically the same. However, there are a few significant differences: Take a look at the addArray() method, for example:

var addArray = function addArray(arr) {

  var result = arr.reduce(function (a, b) {

return a + b;

  }, 0);

  return result;

};

 

Step 3: Adding ESLint to check for common JavaScript errors

Using a linter for your code is usually a good idea since it promotes consistent coding practices and helps discover tough errors like missing brackets or parentheses.

Modules Installation

To Install the ESLint Rollup plugin in order to use ESLint:

npm install –save-dev rollup-plugin-eslint

Generate a .eslintrc.json

To ensure that we only obtain the errors we desire, we must first setup ESLint. Fortunately, we can construct the most of this setup automatically by executing the following command:

$ ./node_modules/.bin/eslint –init

? How would you like to configure ESLint? Answer questions about your style

? Are you using ECMAScript 6 features? Yes

? Are you using ES6 modules? Yes

? Where will your code run? Browser

? Do you use CommonJS? No

? Do you use JSX? No

? What style of indentation do you use? Spaces

? What quotes do you use for strings? Single

? What line endings do you use? Unix

? Do you require semicolons? Yes

? What format do you want your config file to be in? JSON

Created .eslintrc.json file in /Users/jlengstorf/dev/code.lengstorf.com/projects/learn-rollup Successfully

If you answer the questions as indicated above, the result in.eslintrc.json will be as follows:

{

  “env”: {

    “browser”: true,

    “es6”: true

  },

  “extends”: “eslint:recommended”,

  “parserOptions”: {

    “sourceType”: “module”

  },

  “rules”: {

    “indent”: [“error”, 4],

    “linebreak-style”: [“error”, “unix”],

    “quotes”: [“error”, “single”],

    “semi”: [“error”, “always”]

  }

}

Tweak .eslintrc.json

However, in order to avoid errors in our project, we must make the following changes:

  1. Use 2 spaces instead of 4.
  2. Use a global variable called ENV later.

Make the necessary changes to your.eslintrc.json — the globals property and the indent property — as follows:

{

  “env”: {

    “browser”: true,

    “es6”: true

  },

  “globals”: {

    “ENV”: true

  },

  “extends”: “eslint:recommended”,

  “parserOptions”: {

    “sourceType”: “module”

  },

  “rules”: {

    “indent”: [“error”, 2],

    “linebreak-style”: [“error”, “unix”],

    “quotes”: [“error”, “single”],

    “semi”: [“error”, “always”]

  }

}

 

Update rollup.config.js

Next, add the ESLint plugin to the Rollup configuration by importing it:

// Rollup plugins

import babel from ‘rollup-plugin-babel’;

import eslint from ‘rollup-plugin-eslint’;

 export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

  plugins: [

eslint({

      exclude: [‘src/styles/**’],

}),

babel({

      exclude: ‘node_modules/**’,

}),

  ],

};

 

Check the console output

At first, when we run ./node_modules/.bin/rollup -c, nothing seems to be happening. That’s because as it stands, the app’s code passes the linter without issues.

$ ./node_modules/.bin/rollup -c

/Users/jlengstorf/dev/code.lengstorf.com/projects/learn-rollup/src/scripts/main.js

12:64 error Missing semicolon semi

✖ 1 problem (1 error, 0 warnings)

 

Step 4: Adding Plugins to handle non-ES modules

If any of your dependencies use Node-style modules, this is critical. You’ll receive require errors if you don’t have it.

Add a Node module as a dependency.

It would be simple to get through this sample project without mentioning a third-party module, but it will not suffice in real-world projects. So, in order to make our Rollup configuration genuinely functional.

For simplicity, add a simple logger to the code using the debug package. Start by installing it:

 

npm install –save debug

Then, inside src/scripts/main.js, add some simple logging

// Import a couple modules for testing.

import { sayHelloTo } from ‘./modules/mod1’;

import addArray from ‘./modules/mod2’;

// Import a logger for easier debugging.

import debug from ‘debug’;

const log = debug(‘app:log’);

// Enable the logger.

debug.enable(‘*’);

log(‘Logging is enabled!’);

// Run some functions from our imported modules.

const result1 = sayHelloTo(‘Jason’);

const result2 = addArray([1, 2, 3, 4]);

// Print the results on the page.

const printTarget = document.getElementsByClassName(‘debug__output’)[0];

printTarget.innerText = `sayHelloTo(‘Jason’) => ${result1}\n\n`;

printTarget.innerText += `addArray([1, 2, 3, 4]) => ${result2}`;

You will get a warning when you run rollup.

$ ./node_modules/.bin/rollup -c

Treating ‘debug’ as external dependency

No name was provided for external module ‘debug’ in options.globals – guessing ‘debug’

And if we check our index.html again, we can see that a ReferenceError was thrown for debug.

The third party node modules won’t load properly with Rollup by default.

Installing the modules

You need to add two plugins to Rollup to work around this problem:

  1. rollup-plugin-node-resolve,
  2. rollup-plugin-commonjs

With the following command Install both plugins

npm install –save-dev rollup-plugin-node-resolve rollup-plugin-commonjs

Update rollup.config.js

Next step is to add and import the plugins to the Rollup config:

// Rollup plugins

import babel from ‘rollup-plugin-babel’;

import eslint from ‘rollup-plugin-eslint’;

import resolve from ‘rollup-plugin-node-resolve’;

import commonjs from ‘rollup-plugin-commonjs’;

export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

  plugins: [

resolve({

   jsnext: true,

   main: true,

      browser: true,

}),

    commonjs(),

eslint({

      exclude: [‘src/styles/**’],

}),

babel({

      exclude: ‘node_modules/**’,

}),

  ],

};

 

Check the console output

check the browser again to see the output after rebuilding the bundle with ./node_modules/.bin/rollup -c, then:

Step 5: Replace environment variables with a plugin

Add an ENV-based conditional in main.js

Let’s utilize an environment variable to disable our logging script while we’re not in production mode. Let’s update the way log() is started in src/scripts/main.js:

 

// Import a logger for easier debugging.

import debug from ‘debug’;

const log = debug(‘app:log’);

 

// The logger should only be disabled if we’re not in production.

if (ENV !== ‘production’) {

  // Enable the logger.

  debug.enable(‘*’);

  log(‘Logging is enabled!’);

} else {

  debug.disable();

}

However, after rebuilding our bundle (./node modules/.bin/rollup -c) and inspecting the browser, we observe that this causes a ReferenceError for ENV.

That should come as no surprise, given that we haven’t defined it anywhere. However, even if we attempt ENV=production./node modules/.bin/rollup -c, it still does not function. This is due to the fact that changing an environment variable in this manner only makes it available to Rollup, not the bundle formed by Rollup.

To feed our environment variables into the bundle, we’ll need to utilize a plugin.

Install the modules

Install rollup-plugin-replace first, which is effectively a find-and-replace application. It can perform a lot of things, but for our needs, we’ll just have it detect an instance of an environment variable and replace it with the actual value.

npm install –save-dev rollup-plugin-replace

Update rollup.config.js

let’s import the plugin and add it to our list of plugins inside rollup.config.js,.

// Rollup plugins

import babel from ‘rollup-plugin-babel’;

import eslint from ‘rollup-plugin-eslint’;

import resolve from ‘rollup-plugin-node-resolve’;

import commonjs from ‘rollup-plugin-commonjs’;

import replace from ‘rollup-plugin-replace’;

 

export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

  plugins: [

resolve({

   jsnext: true,

   main: true,

   browser: true,

}),

commonjs(),

eslint({

   exclude: [‘src/styles/**’],

}),

babel({

   exclude: ‘node_modules/**’,

}),

replace({

   exclude: ‘node_modules/**’,

   ENV: JSON.stringify(process.env.NODE_ENV || ‘development’),

}),

  ],

};

In our setup, we’ll look for every instance of ENV and replace it with the value of process.env. NODE ENV – the standard means of configuring the environment in Node apps — or “development.” Because ENV is not encased in double quotes, we use JSON.stringify() to ensure that the value is.

Set the exclude attribute to disregard our node modules directory and all the packages it contains to avoid conflicts with third-party code.

Check the results

Begin by rebuilding the bundle and testing the browser. The console log should appear, as previously. That’s excellent since it suggests our default value was used.

Let’s execute the command in production mode to observe where the power comes in:

 

NODE_ENV=production ./node_modules/.bin/rollup -c

When we restart the browser, nothing is reported to the terminal:

With no code modifications, using an environment variable disables logging.

 

Step 6: To compress and minify our generated script Add UglifyJS

The final JavaScript step in this tutorial will be to add UglifyJS to minify and compress the bundle. This may significantly reduce the size of a bundle by eliminating comments, reducing variable names, and generally mangling the code – rendering it incomprehensible for humans but much more efficient to distribute over a network.

Install the plugin

UglifyJS will be used to compress the bundle using rollup-plugin-uglify.

Install it with the following:

npm install –save-dev rollup-plugin-uglify

Update rollup.config.js

Next, let’s include Uglify in our Rollup configuration. However, for development legibility, let’s make uglification a production-only feature:

// Rollup plugins

import babel from ‘rollup-plugin-babel’;

import eslint from ‘rollup-plugin-eslint’;

import resolve from ‘rollup-plugin-node-resolve’;

import commonjs from ‘rollup-plugin-commonjs’;

import replace from ‘rollup-plugin-replace’;

import uglify from ‘rollup-plugin-uglify’;

export default {

  entry: ‘src/scripts/main.js’,

  dest: ‘build/js/main.min.js’,

  format: ‘iife’,

  sourceMap: ‘inline’,

  plugins: [

resolve({

   jsnext: true,

   main: true,

      browser: true,

}),

    commonjs(),

eslint({

      exclude: [‘src/styles/**’],

}),

babel({

      exclude: ‘node_modules/**’,

}),

replace({

   ENV: JSON.stringify(process.env.NODE_ENV || ‘development’),

}),

    process.env.NODE_ENV === ‘production’ && uglify(),

  ],

};

Check the minified bundle

After saving the settings, run Rollup with NODE ENV in production:

 

NODE_ENV=production ./node_modules/.bin/rollup -c

The result isn’t attractive, but it’s a lot smaller. Here’s a snapshot of build/js/main.min.js right now:

Conclusion

Rollup Revolution

Rollup.js takes some time to configure, but the result will be adequate for many of your applications. It’s great if you want a more customizable and speedier JavaScript bundler.

 

The post How to Bundle JavaScript With Rollup appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-bundle-javascript-with-rollup/feed/ 0
How to Build Secure Node.js Rest APIs https://talent500.com/blog/how-to-build-secure-node-js-rest-apis/ https://talent500.com/blog/how-to-build-secure-node-js-rest-apis/#respond Mon, 02 Jan 2023 11:17:01 +0000 https://talent500.com/blog/?p=35501 How to Build Secure Node.js Rest APIs Introduction Connectivity is a wonderful thing. Today, we are as linked to the […]

The post How to Build Secure Node.js Rest APIs appeared first on Talent500 blog.

]]>
How to Build Secure Node.js Rest APIs

Introduction

Connectivity is a wonderful thing. Today, we are as linked to the globe as a spider is to its web. The Internet and networking have brought the world to our fingertips; we are only a click away from everything we seek. We may publish a thought on social media, buy a refrigerator, book a flight, make a reservation, and much more from our PCs or gadgets.

Understanding APIs

An API acts as a messenger, taking your request to the system, telling it what to do, and returning a response from the system. API stands for Application Programmable Interface, and it is a language used by software to interact and chat with one another. An API’s basic functions include data access, complexity concealment, feature extension, and security.  


APIs are classified according to their utility. We concentrate on APIs, which allow diverse software and apps on our devices to connect with one another. REST and SOAP are the most widely used APIs for interacting with online services. First, you need to understand the distinction between the two and why Node.js Restful APIs are now preferred over the other.

What’s SOAP and REST?

Developers choose REST over SOAP because SOAP manipulates things so that they may be accessed remotely, whereas REST focuses on actions on the objects. Another benefit of the REST design is that it inherits HTTP operations, making it a good choice for Web APIs. When comparing REST to SOAP, speed and leniency are extra benefits. 

REST means Representational State Transfer. In layman’s terms, it means that no state exists between the server and the client. Except for the data, there are no web pages that need to be processed. This gives you the greatest independence that you will require. The only thing you have to do is enter some logic on a certain URL that is connected to a database and use its logic to process the complete data and deliver it back in JSON format. Your new client may be any of the following: – a C# Windows desktop program, a Java Android app, or an Arduino project 

This is exactly why REST is used. By making the connection completely stateless, REST makes this data available to any client that uses the HTTP protocol. You can now repeat the data to show it wherever you want.

Let’s Node it!

To begin, Node JS is a runtime environment in which JavaScript code may be executed, and with the introduction of Node.js, JavaScript became a full-stack programming language.

Node.js is an open source JavaScript runtime environment. It is built on the Chrome V8 engine, which is a chromium-browser machine code generation engine. Node.JS allows you to run the applications listed in JavaScript on the server. By 2014, Node.JS had established itself as one of the most comprehensive tools for back-end development. Node.JS has received widespread acclaim as a crucial component of the popular MERN and MEAN JavaScript-centred technology stacks that encompass the whole web development pipeline. 

Advantages of Node.js

Let’s have a look at the benefits of Node.js and why you should adopt it for next-generation web app development. 

  • Good for Microservice

Node.JS is a lightweight and scalable programming language. Another reason it is the most popular source for microservice designs. Node.JS, with the support of Node.JS modules, is ideal for developing microservice architectures.

  • Easy to Learn

Front-end developers will likely grasp Node.JS quickly because it has a large variety of javascript functionalities as well as libraries. Indeed, because of its ubiquity and large community support, javascript has a shorter learning curve for all newcomers or beginners who are new to the area of programming.

  • Fast

Node.JS is exceptionally fast due to Chrome’s V8 engine. Node.JS is extremely efficient at processing several concurrent requests at the same time, resulting in decreased CPU consumption.

  • Packages

Only a select few programming languages can rival Node.rich JS’s and well-organized ecosystem. Numerous tools and modules needed for JavaScript development are gathered by npm, the default Node.JS package manager and marketplace. Npm focuses completely on encouraging people to develop whole new packages with regular community help. This enables you to get ready-made answers to particular situations

  • Javascript on a Server

The full-stack development of javascript has benefited from Node.JS. Node.JS lets engineers use its libraries and has the benefits of javascript programming. High performance is achieved as a result of its small weight. Since only one language is used on both the front end and the back end of the application, everything is coordinated. If noted from a developer’s perspective, they can use node modules to reuse and exchange codes.

  • Support and Community

Since Node.JS is open-source, a sizable developer community develops to address issues on Github. You can always find more than one solution to all of your problems in a large society.

Let’s now look at how to create the Node.js Rest API example.

 

Getting Started:Node.js Rest APIs

A step-by-step tutorial for creating secure Node.js rest APIs in under five minutes.

Preparatory Instructions

You must download the most recent NodeJS release in order to get started. Make cautious not to get the most recent version, though. This is so that any features or bugs in the most recent version can be removed from the finished product.

After downloading the Node.js binaries, follow the instructions on the page specific to your platform to install them in your system.

Close any and all open or possible background-running instances of cmd to verify the installation procedure. Start a brand-new instance next.

Type the next 2 commands to see the NPM and Node versions that are installed.

npm -v
node -v 

Initializing a new app

There are three ways to construct an Express application in general.

Except for the second one, which will highlight Node js web API, we will explore three of them in brief below:

  • You can first construct the files by yourself. A simple Node app consists of one.js file and one package.json file. To be more specific, the package.json file contains several features and attributes.
    • The first one is the name of the app.
    • The second one is to display the version of your app along with the description and entry point.
    • you can run certain scripts if you wish to perform dependencies, repetitive tasks, author name, license, and devDependencies.

One critical element to remember is that package.json describes the app. When you submit your app, your dependencies will be registered in a way that saves unnecessary data transmission and duplication. A typical angular 6 app node module takes a long time to upload or download because it is roughly 230MB in size. It is preferable to leave these modules out to minimize misunderstanding. Use package.json to install modules anytime you need to run the app on a new machine or system from now on.

  • The following technique is to utilize an NPM utility. Though it takes time and is not the quickest option, it is the most basic. All you have to do is open your cmd in the location where you want to create your app. Then, to create your package, run npm init. json file as a whole.
  • The third way is straightforward, however it might be difficult for newcomers or beginners. This is because it generates various files that you may be unfamiliar with if you are new to NodeJS.

Furthermore, you must install the Express tool in order to generate a whole Express template rather than the package. json on its own.

npm install -g express-generator
This assists the express-generator tool in installing and creating a complete express app. As previously explained, NPM is a valuable and vital tool that you may need for module installation.

You may wish to utilize the javascript modules you install in the same application. For example, you will install mongoose so that you may query data from your MongoDB instance using mongoose methods. You can, on the other hand, install such tools and modules that can be used anywhere on your system. These tools or modules are present on the command line, but they are only available if they are installed globally. The -g flags indicate that you want to install the module globally so that you can use it anywhere on your system or computer. If you do not use the -g flag, the tool or module will be installed in that folder and will be unavailable outside of that scope.

 

Installing Express

For creating a package, we recommend utilizing the second technique. as indicated in the preceding json file

The next step is to install Express into the app.

Use the following command to install Express:

npm install express –save

Because you utilize the save flag, you may change the JSON file as well as add Express as a dependency. After finishing the installation, open your package. json will be searched for the Express that will be added as a dependency. You may then just forward your package. Send the json file and code to a buddy and instruct them to use npm to install dependencies on their machine. You may store data here. To install, your buddy must open cmd within the folder and run the command npm install.

Creating the app

You must now construct the app.js file. (You may call it whatever you like, but the default name is index.js.) After that, insert the following code:

var express = require(“express”);

var app = express();

app.listen(3000, () => {

 console.log(“Server running on port 3000”);

});

With this, you have created your first ever useless Express server.

Next, configure your app to listen on port 3000 and produce a callback. This step ensures that your server is currently listening on port 3000.

To summarize, you may now reach your app through http://localhost:3000. You cannot, however, gain anything since you have not set or adjusted your server to listen to any of the events.


Request handlers settings

The server’s primary function is to receive a request, process it, and produce a response. As a result, you should employ routes to handle these requests. Let us now create a standard GET request that will return a list of users.

Type the code given below under the var app=express():

app.get(“/url”, (req, res, next) => {

 res.json([“Tony”,”Lisa”,”Michael”,”Ginger”,”Food”]);

});

This simple function instructs the express app to utilize the URL handle “/URL” to activate the callback that follows it. Three arguments are used in this callback.

  • Req (the request body)
  • Res ( the response body)
    • .render() for rendering templates.
    • .json() for returning the JSON data.

 

Running your app

Type the command for running your app as given below:

node app.js

Your cmd will look like as shown when you run this command:

This also indicates that your program is now favorably executing on port 3000. To view the data, use your browser and navigate to http://localhost:3000/url.

You will notice something like this on your screen on entering. 

However, this is raw data. The data returned is an array of strings.

Conclusion

Simply request a certain endpoint and receive data in a stateless way. This is the most fundamental level of API that you must run in order to analyze and comprehend the operation of REST APIs. Hope this blog helps you understand why RESTful APIs are better implemented using Node.js and how easy it is to construct Node.js Rest APIs.

The post How to Build Secure Node.js Rest APIs appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-build-secure-node-js-rest-apis/feed/ 0
How to Perform JSON Schema Validation? https://talent500.com/blog/how-to-perform-json-schema-validation/ https://talent500.com/blog/how-to-perform-json-schema-validation/#respond Mon, 02 Jan 2023 10:42:48 +0000 https://talent500.com/blog/?p=35488 Due to the rise in API consumption, it is becoming tedious for QA teams to test the APIs. So before […]

The post How to Perform JSON Schema Validation? appeared first on Talent500 blog.

]]>
Due to the rise in API consumption, it is becoming tedious for QA teams to test the APIs. So before testing the API, most of the teams prefer to define the data your service will accept and the data format it will return. This process of validating the data format and defining it for the ease of validation is basically Schema Validation. 

In API Testing there are three types of validation, out of which one of the most important ones is Schema Validation. Sometimes after providing the detailed documentation of the APIs, the testing team identifies defects due to the structure of data. In some scenarios the response body from server is too large to put assertion and also diverse in nature to consider for response body validation

JSON Schema Validation comes to the rescue in the above mentioned problem statement, the structural differences can now be caught easily and can save a lot of your efforts and time in debugging and finding the issue. That’s the main reason why the popularity of JSON Schema has been at the top and also called as the King of API data formats.

Before we start  discussing JSON Schema validation, let’s first understand what JSON is, and then continue with the JSON Schema Validation. 

What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data and often used when data is sent from server to web pages. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others languages. These specific properties make JSON an ideal data-interchange language.

 Two most important things to learn from JSON are its syntax rules and the data types. JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object
  • an array
  • a boolean
  • null

JSON is one of the  most common formats for exchanging data over the internet. And even though most APIs work with JSON, there’s no guarantee that the consumer will be able to interact with data in this format. A schema aims to fix all those pain points.

What is JSON Schema?

 Schema is nothing but a JSON file. It will only have datatype information and the expected keys of the JSON. There won’t be any values present in the schema. 

JSON Schema is a JSON media type for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how to interact with it. JSON Schema is intended to define validation, documentation, hyperlink navigation, and interaction control of JSON data.

If we try to put it in simple terms, JSON Schema is basically a contract for JSON document that defines the expected data types and format of each field in the response. JSON Schema helps us in describing the existing data format and providing clear, human and machine readable documentation. As JSON Schema provides complete structural validation, it helps in automated tests and also validating the client-submitted data for verification.

JSON Schema Example

Let’s try to convert a JSON into schema to understand the basic concepts around JSON Schema properly.

[
    {
        “name”: “Testuser”,
        “location”: “India”,
        “experienceInYears”: 6
    }
]

 

The structure of this JSON response has some points to note, let’s understand it:

    • The API returns a top level array
    • Each array entry is an object (a user).
  • Each user has a name, location, and experienceInYears key.
  • The name and location are strings, while the experienceInYears is a number.

The following JSON Schema definition describes the response above:

 

{
    “$schema”: “https://json-schema.org/draft-04/schema#”,
    “type”: “array”,
    “items”: {
        “type”: “object”,
        “properties”: {
            “name”: {
                “type”: “string”
            },
            “location”: {
                “type”: “string”
            },
            “experienceInYears“: {
                “type”: “integer”
            }
        }
    }
}

 

If we go through the JSON Schema line by line, it details the type and structure of the entire body, as well as each individual field. 

To go over a few points: The $schema keyword states that this schema is written according to a specific draft of the standard and used for a variety of reasons, primarily version control.

  • The top-level type key tells us the API returns an “array”.
  • The items describe the shape of each array entry (each user).
  • The name and location fields are strings, while experienceInYears is an integer.
  •  

How to Perform JSON Schema validation

We can perform schema validation manually by using some websites and tools, you can also refer to the website HERE to validate schemas. In the above mentioned website  you can paste both the schemas and do a comparison, it will highlight the differences which can be reported further. As manual approach is not always convenient, so most of the QA team prefer to automate the Schema Validation, in this section we will try to  go through the steps to automate the schema validation using Rest Assured. For those who are new to API Automation, Rest Assured is a Java library that provides a domain-specific language for writing powerful, maintainable tests for RESTful APIs.

 

Step-01: Add dependency 

 

Step-02: Load expected schema

Load the expected “schema.JSON” in a file object.

You can create a schema from JSON using website HERE:

 

Step-03:  Validate using matchesJSONSchema

Validate the response body using the matchesJsonSchema method. 

Conclusion

 

JSON Schema validation is considered as one of the most efficient ways of ensuring your APIs are working as expected. In the above post we have discussed both manual and automation approaches of performing the schema validation, so let us know if you find it useful. Apart from the API Testing, JSON Schema also helps during the Contract Testing. In fact we can use JSON Schema along with a schema matcher in the integration tests. 

Those who are looking out of QA Automation jobs do mention Schema Validation in your skill set, and upload your resume at Talent500. You can find multiple opportunities in the jobs link here.

 

The post How to Perform JSON Schema Validation? appeared first on Talent500 blog.

]]>
https://talent500.com/blog/how-to-perform-json-schema-validation/feed/ 0
Deploy Your First Serverless Function Using JavaScript https://talent500.com/blog/deploy-your-first-serverless-function-using-javascript/ https://talent500.com/blog/deploy-your-first-serverless-function-using-javascript/#respond Thu, 22 Dec 2022 16:34:44 +0000 https://talent500.com/blog/?p=35464 Deploy Your First Serverless Function Using JavaScript The JavaScript powering front ends enables us to add back-end logic with serverless […]

The post Deploy Your First Serverless Function Using JavaScript appeared first on Talent500 blog.

]]>
Deploy Your First Serverless Function Using JavaScript


The JavaScript powering front ends enables us to add back-end logic with serverless functions. In this tutorial, Deploy your first serverless function. It is a powerful solution for adding additional functionality to Jamstack sites. We’ll go through some to create and deploy the first serverless function using Netlify Functions.

 

Write the first serverless function

Writing the serverless function will be your First step. 

  1. Create a folder called functions in an empty folder. 
  2. With the following code make a new file called my-first-function.js inside:

exports.handler = async () => ({

  statusCode: 200,

  body: ‘boop’,

});

That’s it – You have just written your first serverless function. The next section is about getting the function online.


Requirements of a serverless function:

The three required components are as follows:

  1. The file needs to export a function named handler — this is what exports.handler is doing on line 1 above.
  2. The function needs to return an object with a statusCode matching a valid HTTP response code.
  3. The response object also needs to include a body value, which is plain text by default.

Configuring your project for deployment with Netlify


We need only two lines of configuration which are needed to save in netlify.toml  at the root of the folder with Netlify Functions.

[build]

  functions = “functions”

It describes Netlify and that our functions live in the folder.


You need to Create the repo and push it to GitHub

Now here you are ready to get this function on the internet!

  1. Create a new repo on GitHub, then 
  2. Add and push our code to it:

# add your new repo as an origin

# IMPORTANT: make sure to use your own username/repo name!

git remote add origin git@github.com:yourusername/yourreponame.git

# add all the files

git add -A

# commit the files

git commit -m ‘my first serverless function’

# push the changes to GitHub

git push -u origin master

 

IMPORTANT: When you add the origin above, it is important to use your own username and repo name.

 

Creating a new Netlify site

You can create your site with the Netlify dashboard or through the CLI. As the CLI is powerful and convenient, use that for this site.

# install the Netlify CLI globally

npm install –global netlify-cli

# log into your Netlify account

netlify login

# initialize a new site

netlify init

 

The command mentioned above will set up a new Netlify site in your account connected to the GitHub repo which has just been created.

There will be several questions:

 The init command of Netlify guides us through taking a new site live.

We can get the URL from the terminal output once the site has been created. The created site name in the above snapshot was:

https://confident-nightingale-4e5a0b.netlify.com/

Netlify functions are often located at the URL endpoint /.netlify/functions/function-name> to reduce the likelihood of the route conflicting with other routes on your site. Because our function file is called my-first-function.js, you can find it on the web at https://confident-nightingale-4e5a0b.netlify.com/.netlify/functions/my-first-function. 

The browser shows “boop” returned from our serverless function. That’s it! You’ve successfully deployed your first serverless function.

Final Thoughts
This tutorial taught you the fundamentals of creating and delivering serverless functions using Netlify. You now have all of the building elements to create whatever you can think of utilizing serverless functions.

 

The post Deploy Your First Serverless Function Using JavaScript appeared first on Talent500 blog.

]]>
https://talent500.com/blog/deploy-your-first-serverless-function-using-javascript/feed/ 0