Frontend Interview? You Must Know Tree Shaking!

Frontend Interview? You Must Know Tree Shaking!

Tree Shaking in JavaScript

Have you noticed this too? While scrolling through LinkedIn, you’ve probably seen countless candidates with the “Open to Work” badge on their profiles for months. The number of these green-bordered profile pictures keeps growing every day.

But have you ever wondered why?

Today, I will break down some key reasons behind this trend and share practical insights to help job seekers land a job faster.

One crucial thing to remember: You must understand and be able to explain everything you put on your resume. If you can’t, you will not pass the technical interviews.

Why Is the Tech Market Very?Slow?

Numbers don’t lie.COVID-19 was a turning point for the tech industry. Many new tech companies and startups emerged, leading to a rapid increase in job opportunities. Companies hired aggressively to keep up with demand.

However, this growth was unbalanced, and overhiring became a problem. Then, a global recession hit, and from 2022 onward, tech layoffs began. Thousands of professionals lost their jobs, including highly experienced individuals with strong backgrounds.

Now, companies have significantly changed their hiring process. In the past, one or two interviews were enough to get a job. Today, candidates go through three or four rounds. With so many skilled professionals in the market, companies are being more selective, trying to hire only the best.

As a result, the hiring process has slowed down, and to be honest, finding a job has become much harder. You can find more details about Tech Layoff in my previous article.

Today, let’s focus on an important frontend interview question.

Many candidates include statements like:

“Improved application performance by 30% through code refactoring, data reorganization, removing code duplication, and simplifying conditional expressions.”

It sounds impressive on a resume, but the real question is?—?can they actually explain it like an expert in an interview?

If an interviewer asks: “Which approach did you use to achieve this?”

One of the best ways to explain this is by discussing Tree Shaking in JavaScript. Let’s explain what is actually Tree Shaking.

Tree shaking is a term commonly used within a JavaScript context to describe the removal of dead code. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.It’s commonly used in modern bundlers like Webpack, Rollup, and ESBuild to optimize performance.
In modern JavaScript applications, we use module bundlers (e.g., webpack or Rollup) to automatically remove dead code when bundling multiple JavaScript files into single files. This is important for preparing code that is production ready, for example with clean structures and minimal file size.

Answer that Question Like an?Expert

“I optimized the application’s performance by implementing Tree Shaking, which helps eliminate unused code from the final JavaScript bundle. This was particularly effective in reducing the bundle size and improving load times. I analyzed the dependency tree using tools like Webpack and ensured that only necessary modules were included in the production build. Additionally, I refactored the code by removing redundant functions, simplifying complex conditionals, and restructuring data processing to reduce unnecessary computations. These optimizations collectively improved the application’s performance by 30%.”

Let’s make a simple example of using Tree Shaking with Webpack.

Step 1: Basic Project?Setup

  1. Create a project folder and initialize npm

First let’s create a directory, initialize npm, install webpack locally, and install the webpack-cli (the tool used to run webpack on the command line)

mkdir tree-shaking-example && cd tree-shaking-example
npm init -y        

2. Install Webpack and Babel

npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env        

The import and export statements have been standardized in ES2015. They are supported in most of the browsers at this moment, however there are some browsers that don't recognize the new syntax. But don't worry, webpack does support them out of the box.

Behind the scenes, webpack actually “transpiles” the code so that older browsers can also run it. If you inspect dist/main.js, you might be able to see how webpack does this, it's quite ingenious! Besides import and export, webpack supports various other module syntaxes as well, see Module API for more information.

Note that webpack will not alter any code other than import and export statements. If you are using other ES6 features, make sure to use a transpiler such as Babel via webpack's loader system.

Step 2: Create Sample JavaScript Files

math.js (Utility File with Unused Code)

export function add(a, b) {
  return a + b;
}

export function multiply(a, b) {
  return a * b;
}

// This function is never used in the project
export function subtract(a, b) {
  return a - b;
}        

index.js (Main File That Only Uses 'add' Function)

import { add } from "./math.js";

console.log("Result:", add(5, 10));        

Step 3: Configure Webpack for Tree?Shaking

Create a webpack.config.js File

const path = require("path");

module.exports = {
  mode: "production", // Enables tree shaking
  entry: "./index.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  optimization: {
    usedExports: true, // Enables Tree Shaking
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};        

Step 4: Build and Observe Tree Shaking in?Action

Run Webpack to bundle the project

npx webpack        
What Happens after running the webpack??
Since subtract() is never used, Webpack removes it from the final bundle.js.
Only the add() function is included, reducing bundle size and improving performance.

How Tree Shaking?Works?

> ES6 Module Analysis: Webpack scans your import/export statements.

> Dead Code Elimination: It removes functions that are not used in the final bundle.

> Minification: Additional optimization happens in production mode, shrinking the code further.

Conclusion

After spending a lot of time optimizing your resume for ATS, passing phone screenings, and clearing HR interviews, you’ve finally reached the technical interview stage. At this point, you must be fully prepared.

Everything on your resume should have a strong foundation, and you need to give clear and confident answers. If you can’t explain what you wrote, all your hard work could go to waste.

But remember, a rejection is not a failure. Every interview helps you learn and prepare better for the next one. Think of each interview as a step forward toward your goal.

Keep going, and success will come.

Good luck!

Let’s Connect?: Substack | LinkedIn

要查看或添加评论,请登录

Recep Taylanhan的更多文章

  • A Core Key to Effective Cross-Functional Teams: Communication

    A Core Key to Effective Cross-Functional Teams: Communication

    image from Unsplash Have You Ever Turned Back from the Edge of a Cliff? Have you ever been speeding down a road…

  • Why Top Tech Companies Using React.js ?

    Why Top Tech Companies Using React.js ?

    Frontend Interview Series -2 How One Second Could Cost Amazon $1.6 Billion In Sales If you are not a Medium member, you…

    1 条评论
  • How To Prepare For Tech Interviews?

    How To Prepare For Tech Interviews?

    “Focus on what you can control and leave the rest to God.” “Focus on what you can control and leave the rest to God.

  • Micro Management and Trust

    Micro Management and Trust

    Build Trust, Not a Toxic Environment Diminishing Employee Confidence and Motivation I have worked in the nonprofit…

    1 条评论
  • Leverage AI in Marketing

    Leverage AI in Marketing

    Marketing is essential because even the highest-quality and most valuable product cannot generate revenue without the…

  • How to Be an Effective Team Player in Agile Methodology

    How to Be an Effective Team Player in Agile Methodology

    I hope you're having a great weekend. I’m really excited to publish my weekly article every Saturday.

    1 条评论
  • How to Get Promoted To Senior Software Engineer: 5 Critical Steps

    How to Get Promoted To Senior Software Engineer: 5 Critical Steps

    Promotion Should Not Be the Only Goal Happy Weekend! First and foremost, I want to express my sincere gratitude to…

    4 条评论
  • 11 Keys For Being an Effective Engineer

    11 Keys For Being an Effective Engineer

    Let me explain the core skills of Effective Engineers. 1- Keep things simple Clear explanation and give real world…

  • My Journey at Chase

    My Journey at Chase

    ?? Today marks my 2nd anniversary at JPMorgan Chase! ?? These two years have been an incredible journey, offering many…

    8 条评论
  • Basic Rest API

    Basic Rest API

    1 条评论

社区洞察