avatarAsim Zaidi

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

11047

Abstract

/p><div id="c367"><pre><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> { <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { <span class="hljs-title function_">resolve</span>(<span class="hljs-string">"Success!"</span>); <span class="hljs-comment">// You could also reject with a new error on failure.</span> }, <span class="hljs-number">1000</span>); });

promise .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-comment">// Success!</span> }) .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">error</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(error); });</pre></div><p id="db67">In JavaScript, you can treat promises and promise returning functions as if they are synchronous, using the async/await syntax. This makes asynchronous code much easier to read and reason about.</p><div id="2135"><pre><span class="hljs-keyword">const</span> <span class="hljs-title function_">processData</span> = <span class="hljs-keyword">async</span> (<span class="hljs-params"></span>) => { <span class="hljs-keyword">try</span> { <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetchData</span>(); <span class="hljs-comment">// Waits until the Promise is resolved</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">"Processed:"</span>, data); <span class="hljs-comment">// Process and display the data</span> } <span class="hljs-keyword">catch</span> (error) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">"Error:"</span>, error); <span class="hljs-comment">// Handle any errors</span> } };</pre></div><h1 id="43bc">6. What is TypeScript?</h1><p id="bc16">TypeScript is a superset of JavaScript, developed and maintained by Microsoft. It has grown significantly in popularity in recent years, and chances are good that if you are a JavaScript engineer, you will eventually need to use TypeScript. It adds static typing to JavaScript, which is a dynamically typed language. Static typing helps developers catch errors early in the development process, improving code quality and maintainability.</p><p id="d889"><b>Key Features of TypeScript:</b></p><p id="6370"><b>Static Typing:</b> Define types for your variables and function parameters to ensure consistency throughout your code.</p><p id="545d"><b>Enhanced IDE Support:</b> Integrated Development Environments (IDEs) can provide better autocompletion, navigation, and refactoring, making the development process more efficient.</p><p id="4b1a"><b>Compilation:</b> TypeScript code is transpiled into JavaScript, making it compatible with any browser or JavaScript environment. During this process, type errors are caught, making the code more robust.</p><p id="4599"><b>Interfaces:</b> Interfaces allow you to specify abstract contracts that objects and functions must satisfy.</p><p id="6d40"><b>Compatibility with JavaScript:</b> TypeScript is highly compatible with existing JavaScript code. JavaScript code can be gradually migrated to TypeScript, making the transition smooth for existing projects.</p><div id="26a4"><pre><span class="hljs-keyword">interface</span> <span class="hljs-title class_">User</span> { <span class="hljs-attr">id</span>: <span class="hljs-built_in">number</span>; <span class="hljs-attr">name</span>: <span class="hljs-built_in">string</span>; }

<span class="hljs-keyword">type</span> <span class="hljs-title class_">GetUser</span> = <span class="hljs-function">(<span class="hljs-params">userId: <span class="hljs-built_in">number</span></span>) =></span> <span class="hljs-title class_">User</span>; <span class="hljs-keyword">const</span> <span class="hljs-attr">getUser</span>: <span class="hljs-title class_">GetUser</span> = <span class="hljs-function">(<span class="hljs-params">userId</span>) =></span> { <span class="hljs-comment">// Fetch user data from a database or API</span> <span class="hljs-keyword">return</span> { <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>, }; };</pre></div><p id="434b">The best defenses against bugs are code review, TDD, and lint tools such as ESLint. TypeScript is not a substitute for these practices, because type correctness does not guarantee program correctness. TypeScript does occasionally catch bugs even after all your other quality measures have been applied. But its main benefit is the improved developer experience it provides via IDE support.</p><h1 id="b032">7. What is a Web Component?</h1><p id="0dfd">Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. They are built using open web technologies such as HTML, CSS, and JavaScript. They are part of the browser, and do not require external libraries or frameworks.</p><p id="979a">Web Components are particularly useful on large teams with many engineers who may be using different frameworks. They allow you to create reusable components that can be used in any framework, or no framework at all. For example, Adobe’s Spectrum design system is built using Web Components, and integrates smoothly with popular frameworks like React.</p><p id="a923">Web Components have existed for a long time, but have grown in popularity recently, especially in large organizations. They are supported by all major browsers, and are a W3C standard.</p><div id="9a5c"><pre><span class="hljs-comment"><!-- Defining a simple Web Component --></span> <span class="hljs-tag"><<span class="hljs-name">script</span>></span><span class="language-handlebars"><span class="language-xml"> // Define a class that extends HTMLElement class SimpleGreeting extends HTMLElement { // Define a constructor that attaches a shadow root constructor() { super(); const shadowRoot = this.attachShadow({ mode: "open" }); // Use a template literal for the shadow root's innerHTML shadowRoot.innerHTML = <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="language-css"> <span class="hljs-comment">/* Style the web component using a style tag */</span> <span class="hljs-selector-tag">p</span> { <span class="hljs-attribute">font-family</span>: Arial, sans-serif; <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--color, black); <span class="hljs-comment">/* Use a CSS variable for the color */</span> } </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span> <span class="hljs-comment">&lt;!-- The &lt;slot&gt; element is a placeholder for user-provided content. --&gt;</span> <span class="hljs-comment">&lt;!-- If no content is provided, it displays its own default content. --&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span>Hello, Web Components!<span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> ; } </span></span></pre></div><div id="66a9"><pre><span class="hljs-comment">// Define a static getter for the observed attributes</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">get</span> <span class="hljs-title function_">observedAttributes</span>() { <span class="hljs-keyword">return</span> [<span class="hljs-string">"color"</span>]; <span class="hljs-comment">// Observe the color attribute</span> } <span class="hljs-comment">// Define a callback for when an attribute changes</span> <span class="hljs-title function_">attributeChangedCallback</span>(<span class="hljs-params">name, oldValue, newValue</span>) { <span class="hljs-comment">// Update the CSS variable when the color attribute changes</span> <span class="hljs-keyword">if</span> (name === <span class="hljs-string">"color"</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">style</span>.<span class="hljs-title function_">setProperty</span>(<span class="hljs-string">"--color"</span>, newValue); } } } <span class="hljs-comment">// Register the custom element with a tag name</span> customElements.<span class="hljs-title function_">define</span>(<span class="hljs-string">"simple-greeting"</span>, <span class="hljs-title class_">SimpleGreeting</span>); </script> <!-- <span class="hljs-title class_">Using</span> the <span class="hljs-title class_">Web</span> <span class="hljs-title class_">Component</span> --> <!-- <span class="hljs-title class_">Pass</span> a custom greeting message using the slot --> <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">simple-greeting</span>></span>Hello, reader!<span class="hljs-tag"></<span class="hljs-name">simple-greeting</span>></span></span> <!-- <span class="hljs-title class_">Pass</span> a custom color using the attribute --> <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">simple-greeting</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"blue"</span>></span>Hello, World!<span class="hljs-tag"></<span class="hljs-name">simple-greeting</span>></span></span></pre></div><h1 id="34b1">8. What is a React Hook?</h1><p id="484c">Hooks are functions that let you use state and other React features without writing a class. Hooks allow you to use state, context, refs, and component lifecycle events by calling functions instead of writing class methods. The additional flexibility of functions allows you to organize your code better, grouping related functionality together in a single hook call, and separating unrelated functionality by implementing it in separate function calls. Hooks offer a powerful and expressive way to compose logic inside a component.</p><h2 id="4f67">Important React Hooks</h2><ul><li><code>useState</code> - allows you to add state to functional components. State variables are preserved between re-renders.</li><li><code>useEffect</code> - lets you perform side effects in functional components. It combines the cap

Options

abilities of <code>componentDidMount</code>, <code>componentDidUpdate</code>, and <code>componentWillUnmount</code> into a single function call, reducing the required code and creating better code organization than class components.</li><li><code>useContext</code> - allows you to consume context in function components.</li><li><code>useRef</code> - allows you to create a mutable reference that persists for the lifetime of the component.</li><li><b>Custom Hooks</b> — to encapsulate reusable logic. This makes it easy to share logic across different components.</li></ul><p id="cf73"><b>Rules of Hooks:</b> Hooks must be used at the top level of React functions (not inside loops, conditions, or nested functions) and only in React function components or custom Hooks.</p><p id="3e42">Hooks solved some common pain points with class components, such as the need to bind methods in the constructor, and the need to split functionality into multiple lifecycle methods. They also make it easier to share logic between components, and to reuse stateful logic without changing your component hierarchy.</p><h1 id="afad">9. How Do you Create a Click Counter in React?</h1><p id="6279">You can create a click counter in React by using the <code>useState</code> hook as follows:</p><div id="17e0"><pre><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span>, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> <span class="hljs-title function_">ClickCounter</span> = (<span class="hljs-params"></span>) => { <span class="hljs-keyword">const</span> [count, setCount] = <span class="hljs-title function_">useState</span>(<span class="hljs-number">0</span>); <span class="hljs-comment">// Initialize count to 0</span> <span class="hljs-keyword">return</span> ( <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span> <span class="hljs-tag"><<span class="hljs-name">p</span>></span>You clicked {count} times<span class="hljs-tag"></<span class="hljs-name">p</span>></span> <span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setCount((count) => count + 1)}>Click me<span class="hljs-tag"></<span class="hljs-name">button</span>></span> <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> ); }; <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">ClickCounter</span>;</pre></div><p id="daf4">Note that passing a function to <code>setCount</code> is best practice when you are deriving the new value from existing state, to ensure that you're always working with the latest state.</p><h1 id="f487">10. What is Test Driven Development (TDD)?</h1><p id="e4f1">Test Driven Development (TDD) is a software development approach where tests are written before the actual code. It revolves around a short, repetitive development cycle designed to ensure that the code meets specified requirements and is free of bugs. TDD can play a vital role in improving code quality, reducing bugs, and increasing developer productivity.</p><p id="b3c0">One of the most important measures of development team productivity is deployment frequency. One of the primary obstacles to continuous delivery is the fear of change. TDD helps to reduce this fear by ensuring that the code is always in a deployable state. This makes it easier to deploy new features and bug fixes, which in turn increases deployment frequency.</p><p id="1dc7">Testing first has many benefits over testing after:</p><ul><li><b>Better Code Coverage:</b> Tests are more likely to cover all edge cases when they are written first.</li><li><b>Improved API Design:</b> Tests force you to think about the API design before you write the code, which helps avoid leaking implementation details into the API.</li><li><b>Fewer Bugs:</b> Testing first helps you catch bugs earlier in the development process, when they are easier to fix.</li><li><b>Better Code Quality:</b> Testing first forces you to write modular, loosely coupled code, which is easier to maintain and reuse.</li></ul><p id="7bda">The final point is my favorite feature of TDD, and it taught me most of what I know about writing modular, cleanly architected code.</p><h2 id="a8a2">Key Steps in TDD:</h2><ol><li><b>Write a Test:</b> This test will fail initially, as the corresponding functionality does not yet exist.</li><li><b>Write the Implementation:</b> Just enough to make the test pass.</li><li><b>Refactor with Confidence:</b> Once the test passes, the code can be refactored with confidence. Refactoring is the process of restructuring existing code without changing its external behavior. Its purpose is to clean up the code, improve readability, and reduce complexity. With the test in place, if you make a mistake, you will be alerted to it immediately by the test failure.</li></ol><p id="8d28"><b>Repeat:</b> The cycle repeats for each functional requirement, gradually building up the software while ensuring that all tests continue to pass.</p><h2 id="19ec">Challenges</h2><ul><li><b>Learning Curve:</b> TDD is a skill and discipline that can take considerable time to develop. After 6 months of TDD, you may still feel like TDD is difficult and gets in the way of productivity. However, after 2 years with TDD, you will likely find that it has become second nature, and that you are more productive than ever before.</li><li><b>Time-Consuming:</b> Writing tests for every small functionality can feel time-consuming initially, though it usually pays off in the long term with reduced bugs and easier maintenance. I often tell people, “if you think you don’t have time for TDD, you <i>really</i> don’t have time to skip TDD.”</li></ul><p id="ddd1">Preparing yourself to answer these questions in an interview setting will certainly help you stand out from the crowd. It will help you become a better JavaScript developer, and that will help you thrive in your new role.</p><h1 id="6512">Next Steps</h1><p id="fef1">If you enjoyed this article and would like to learn more about software development or Eric Elliot’s content — please hold the clap button on this article and subscribe to my page. Topics include <i>JavaScript, TypeScript, React, TDD, <a href="https://readmedium.com/the-art-of-effortless-programming-3e1860abe1d3?source=email-65d7f64fedb-1703986658805-newsletter.subscribeToProfile-------------------------00fb12d2_e2eb_44bf_830c_d86e37a4a9f8--------406146e27552">AI Driven Development</a>, and Engineering Leadership.</i> Join today at <a href="http://redirect.medium.systems/r-78ZpXzCLIF?source=email-65d7f64fedb-1703986658805-newsletter.subscribeToProfile-------------------------00fb12d2_e2eb_44bf_830c_d86e37a4a9f8--------406146e27552">DevAnywhere.io</a>.</p><p id="f7cd">···</p><p id="7158"><b><i>Asim Zaidi </i></b><i>has been a Senior Software Engineer for A</i>pple<i>, Senior Software Engineer at Atlassian, renown Medium Author, Managing Partner @ Techmade, Co-Founder @ jail.app and more.</i></p><p id="2aaa">Would you like 1:1 career coaching from me? <a href="https://asimzaidi.medium.com/membership">Sign up here</a> and I will contact you. <a href="https://asimzaidi.medium.com/membership"><i>Subscribe</i></a><i> to get more of my posts. I can teach you how to optimize your LinkedIn to get interviews from top tech companies!</i></p><h1 id="7689">Don’t forget to clap and subscribe if you enjoyed!</h1><blockquote id="05cb"><p><i>~ 25 y/o Builder from Chicago, Asim Zaidi</i></p></blockquote><blockquote id="aafe"><p><i>Senior Software Engineer <a href="http://apple.com/">@Apple</a></i></p></blockquote><blockquote id="bfe4"><p><i>Prev: Senior Software Engineer @<a href="https://readmedium.com/5aa6b9976187">Atlassian</a></i></p></blockquote><blockquote id="c9cf"><p><i>Founder: Techmade ([email protected]) / Land a Job in Tech.</i></p></blockquote><blockquote id="9d4a"><p><i>Twitter for my Web3 shenanigans: <a href="http://twitter.com/_asimzaidi_">asimzaidi</a></i></p></blockquote><div id="fce8" class="link-block"> <a href="https://asimzaidi.medium.com/how-to-become-a-senior-react-engineer-5258911b8179"> <div> <div> <h2>How To Become a SENIOR React Engineer</h2> <div><h3>Congratulations on your journey as a React developer! Now it’s time to elevate your skills and reach the pinnacle of…</h3></div> <div><p>asimzaidi.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*wdz9_Gtkf6LfXRjn)"></div> </div> </div> </a> </div><div id="6742" class="link-block"> <a href="https://asimzaidi.medium.com/how-senior-engineers-build-react-apps-deep-dive-1d23bd579dc7"> <div> <div> <h2>How Senior Engineers Build React Apps: Deep Dive</h2> <div><h3>React, an essential tool in any senior engineer’s arsenal, has gained acclaim for its powerful capabilities in building…</h3></div> <div><p>asimzaidi.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*aMuer70Emy4hSp-Q)"></div> </div> </div> </a> </div><div id="5ad7" class="link-block"> <a href="https://asimzaidi.medium.com/react-concepts-for-senior-engineers-3966b6505388"> <div> <div> <h2>React Concepts for Senior Engineers</h2> <div><h3>As a software developer, becoming a senior engineer is a challenging yet rewarding goal. A senior engineer is a highly…</h3></div> <div><p>asimzaidi.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*kduAaK_qptvhFBfW)"></div> </div> </div> </a> </div><div id="651e" class="link-block"> <a href="https://asimzaidi.medium.com/senior-engineering-strategies-for-advanced-react-and-typescript-9d7aa8a07fd8"> <div> <div> <h2>Senior Engineering Strategies for Advanced React and TypeScript</h2> <div><h3>React and TypeScript are two of the most popular front-end technologies used in modern web development. React’s…</h3></div> <div><p>asimzaidi.medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*B7yM2tZWSS1smb69)"></div> </div> </div> </a> </div></article></body>

Senior Frontend Engineer Interview Questions in 2024 by Eric Elliot

In the dynamic landscape of JavaScript, the approach to technical interviews has evolved substantially. This guide presents 10 critical questions that are integral for every JavaScript developer to know as of 2024. These questions span various topics, including closures and Test-Driven Development (TDD), preparing you to effectively navigate the complexities of modern JavaScript.

As someone who frequently conducts technical interviews, I regularly incorporate these questions. My approach when candidates are unfamiliar with the answers isn’t to dismiss them outright. Rather, I use the opportunity to educate them on these concepts, gauging their ability to listen, learn, and cope with the stress of not knowing an answer during an interview.

1. What is a Closure?

A closure gives you access to an outer function’s scope from an inner function. When functions are nested, the inner functions have access to the variables declared in the outer function scope, even after the outer function has returned:

const createSecret = (secret) => {
  return {
    getSecret: () => secret,
    setSecret: (newSecret) => {
      secret = newSecret;
    },
  };
};

const mySecret = createSecret("My secret");
console.log(mySecret.getSecret()); // My secret
mySecret.setSecret("My new secret");
console.log(mySecret.getSecret()); // My new secret

Closure variables are live references to the outer-scoped variable, not a copy. This means that if you change the outer-scoped variable, the change will be reflected in the closure variable, and vice versa, which means that other functions declared in the same outer function will have access to the changes.

Common use cases for closures include:

  • Data privacy
  • Currying and partial applications (frequently used to improve function composition, e.g. to parameterize Express middleware or React higher order components)
  • Sharing data with event handlers and callbacks

Data Privacy

Encapsulation is a vital feature of object oriented programming. It allows you to hide the implementation details of a class from the outside world. Closures in JavaScript allow you to declare private variables for objects:

// Data privacy
const createCounter = () => {
  let count = 0;
  return {
    increment: () => ++count,
    decrement: () => --count,
    getCount: () => count,
  };
};

Curried functions and partial applications:

// A curried function takes multiple arguments one at a time.
const add = (a) => (b) => a + b;

// A partial application is a function that has been applied to some,
// but not yet all of its arguments.
const increment = add(1); // partial application
increment(2); // 3

2. What is a Pure Function?

Pure functions are important in functional programming. Pure functions are predictable, which makes them easier to understand, debug, and test than impure functions. Pure functions follow two rules:

  1. Deterministic — given the same input, a pure function will always return the same output.
  2. No side-effects — A side effect is any application state change that is observable outside the called function other than its return value.

Examples of Non-deterministic Functions

Non-deterministic functions include functions that rely on:

  • A random number generator.
  • A global variable that can change state.
  • A parameter that can change state.
  • The current system time.

Examples of Side Effects

  • Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain).
  • Logging to the console.
  • Writing to the screen, file, or network.
  • Throwing an error. Instead, the function should return a result indicating the error.
  • Triggering any external process.

In Redux, all reducers must be pure functions. If they are not, the state of the application will be unpredictable, and features like time-travel debugging will not work. Impurity in reducer functions may also cause bugs that are difficult to track down, including stale React component state.

3. What is Function Composition?

Function composition is the process of combining two or more functions to produce a new function or perform some computation: (f ∘ g)(x) = f(g(x)) (f composed with g of x equals f of g of x).

const compose = (f, g) => (x) => f(g(x));

const g = (num) => num + 1;
const f = (num) => num * 2;
const h = compose(f, g);
h(20); // 42

React developers can clean up large component trees with function composition. Instead of nesting components, you can compose them together to create a new higher-order component that can enhance any component you pass to it with additional functionality.

4. What is Functional Programming?

Functional programming is a programming paradigm that uses pure functions as the primary units of composition. Composition is so important in software development that virtually all programming paradigms are named after the units of composition they use:

  • Object-oriented programming uses objects as the unit of composition.
  • Procedural programming uses procedures as the unit of composition.
  • Functional programming uses functions as the unit of composition.

Functional programming is a declarative programming paradigm, which means that programs are written in terms of what they do, rather than how they do it. This makes functional programs easier to understand, debug, and test than imperative programs. They also tend to be a lot more concise, which reduces code complexity and makes it easier to maintain.

Other key aspects of functional programming include:

  • Immutability — immutable data structures are easier to reason about than mutable data structures.
  • Higher-order functions — functions that take other functions as arguments or return functions as their result.
  • Avoiding shared mutable state — shared mutable state makes programs difficult to understand, debug, and test. It also makes it difficult to reason about the correctness of a program.

Since pure functions are easy to test, functional programming also tends to lead to better test coverage and fewer bugs.

5. What is a Promise?

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. It acts as a placeholder for a value that is initially unknown, typically because the computation of its value is not yet complete.

Key Characteristics of Promises:

Stateful: A Promise is in one of three states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Immutable: Once a Promise is fulfilled or rejected, its state cannot change. It becomes immutable, permanently holding its result. This makes Promises reliable in asynchronous flow control.

Chaining: Promises can be chained, meaning the output of one Promise can be used as input for another. This is done using .then() for success or .catch() for handling failures, allowing for elegant and readable sequential asynchronous operations. Chaining is the async equivalent of function composition.

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
    // You could also reject with a new error on failure.
  }, 1000);
});

promise
  .then((value) => {
    console.log(value); // Success!
  })
  .catch((error) => {
    console.log(error);
  });

In JavaScript, you can treat promises and promise returning functions as if they are synchronous, using the async/await syntax. This makes asynchronous code much easier to read and reason about.

const processData = async () => {
  try {
    const data = await fetchData(); // Waits until the Promise is resolved
    console.log("Processed:", data); // Process and display the data
  } catch (error) {
    console.error("Error:", error); // Handle any errors
  }
};

6. What is TypeScript?

TypeScript is a superset of JavaScript, developed and maintained by Microsoft. It has grown significantly in popularity in recent years, and chances are good that if you are a JavaScript engineer, you will eventually need to use TypeScript. It adds static typing to JavaScript, which is a dynamically typed language. Static typing helps developers catch errors early in the development process, improving code quality and maintainability.

Key Features of TypeScript:

Static Typing: Define types for your variables and function parameters to ensure consistency throughout your code.

Enhanced IDE Support: Integrated Development Environments (IDEs) can provide better autocompletion, navigation, and refactoring, making the development process more efficient.

Compilation: TypeScript code is transpiled into JavaScript, making it compatible with any browser or JavaScript environment. During this process, type errors are caught, making the code more robust.

Interfaces: Interfaces allow you to specify abstract contracts that objects and functions must satisfy.

Compatibility with JavaScript: TypeScript is highly compatible with existing JavaScript code. JavaScript code can be gradually migrated to TypeScript, making the transition smooth for existing projects.

interface User {
  id: number;
  name: string;
}

type GetUser = (userId: number) => User;
const getUser: GetUser = (userId) => {
  // Fetch user data from a database or API
  return {
    id: userId,
    name: "John Doe",
  };
};

The best defenses against bugs are code review, TDD, and lint tools such as ESLint. TypeScript is not a substitute for these practices, because type correctness does not guarantee program correctness. TypeScript does occasionally catch bugs even after all your other quality measures have been applied. But its main benefit is the improved developer experience it provides via IDE support.

7. What is a Web Component?

Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. They are built using open web technologies such as HTML, CSS, and JavaScript. They are part of the browser, and do not require external libraries or frameworks.

Web Components are particularly useful on large teams with many engineers who may be using different frameworks. They allow you to create reusable components that can be used in any framework, or no framework at all. For example, Adobe’s Spectrum design system is built using Web Components, and integrates smoothly with popular frameworks like React.

Web Components have existed for a long time, but have grown in popularity recently, especially in large organizations. They are supported by all major browsers, and are a W3C standard.

<!-- Defining a simple Web Component -->
<script>
  // Define a class that extends HTMLElement
  class SimpleGreeting extends HTMLElement {
    // Define a constructor that attaches a shadow root
    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: "open" });
      // Use a template literal for the shadow root's innerHTML
      shadowRoot.innerHTML = `
        <style>
          /* Style the web component using a style tag */
          p {
            font-family: Arial, sans-serif;
            color: var(--color, black); /* Use a CSS variable for the color */
          }
        </style>
        <!-- The <slot> element is a placeholder for user-provided content. -->
        <!-- If no content is provided, it displays its own default content. -->
        <p><slot>Hello, Web Components!</slot></p>
      `;
    }
// Define a static getter for the observed attributes
    static get observedAttributes() {
      return ["color"]; // Observe the color attribute
    }
    // Define a callback for when an attribute changes
    attributeChangedCallback(name, oldValue, newValue) {
      // Update the CSS variable when the color attribute changes
      if (name === "color") {
        this.style.setProperty("--color", newValue);
      }
    }
  }
  // Register the custom element with a tag name
  customElements.define("simple-greeting", SimpleGreeting);
</script>
<!-- Using the Web Component -->
<!-- Pass a custom greeting message using the slot -->
<simple-greeting>Hello, reader!</simple-greeting>
<!-- Pass a custom color using the attribute -->
<simple-greeting color="blue">Hello, World!</simple-greeting>

8. What is a React Hook?

Hooks are functions that let you use state and other React features without writing a class. Hooks allow you to use state, context, refs, and component lifecycle events by calling functions instead of writing class methods. The additional flexibility of functions allows you to organize your code better, grouping related functionality together in a single hook call, and separating unrelated functionality by implementing it in separate function calls. Hooks offer a powerful and expressive way to compose logic inside a component.

Important React Hooks

  • useState - allows you to add state to functional components. State variables are preserved between re-renders.
  • useEffect - lets you perform side effects in functional components. It combines the capabilities of componentDidMount, componentDidUpdate, and componentWillUnmount into a single function call, reducing the required code and creating better code organization than class components.
  • useContext - allows you to consume context in function components.
  • useRef - allows you to create a mutable reference that persists for the lifetime of the component.
  • Custom Hooks — to encapsulate reusable logic. This makes it easy to share logic across different components.

Rules of Hooks: Hooks must be used at the top level of React functions (not inside loops, conditions, or nested functions) and only in React function components or custom Hooks.

Hooks solved some common pain points with class components, such as the need to bind methods in the constructor, and the need to split functionality into multiple lifecycle methods. They also make it easier to share logic between components, and to reuse stateful logic without changing your component hierarchy.

9. How Do you Create a Click Counter in React?

You can create a click counter in React by using the useState hook as follows:

import React, { useState } from "react";

const ClickCounter = () => {
  const [count, setCount] = useState(0); // Initialize count to 0
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount((count) => count + 1)}>Click me</button>
    </div>
  );
};
export default ClickCounter;

Note that passing a function to setCount is best practice when you are deriving the new value from existing state, to ensure that you're always working with the latest state.

10. What is Test Driven Development (TDD)?

Test Driven Development (TDD) is a software development approach where tests are written before the actual code. It revolves around a short, repetitive development cycle designed to ensure that the code meets specified requirements and is free of bugs. TDD can play a vital role in improving code quality, reducing bugs, and increasing developer productivity.

One of the most important measures of development team productivity is deployment frequency. One of the primary obstacles to continuous delivery is the fear of change. TDD helps to reduce this fear by ensuring that the code is always in a deployable state. This makes it easier to deploy new features and bug fixes, which in turn increases deployment frequency.

Testing first has many benefits over testing after:

  • Better Code Coverage: Tests are more likely to cover all edge cases when they are written first.
  • Improved API Design: Tests force you to think about the API design before you write the code, which helps avoid leaking implementation details into the API.
  • Fewer Bugs: Testing first helps you catch bugs earlier in the development process, when they are easier to fix.
  • Better Code Quality: Testing first forces you to write modular, loosely coupled code, which is easier to maintain and reuse.

The final point is my favorite feature of TDD, and it taught me most of what I know about writing modular, cleanly architected code.

Key Steps in TDD:

  1. Write a Test: This test will fail initially, as the corresponding functionality does not yet exist.
  2. Write the Implementation: Just enough to make the test pass.
  3. Refactor with Confidence: Once the test passes, the code can be refactored with confidence. Refactoring is the process of restructuring existing code without changing its external behavior. Its purpose is to clean up the code, improve readability, and reduce complexity. With the test in place, if you make a mistake, you will be alerted to it immediately by the test failure.

Repeat: The cycle repeats for each functional requirement, gradually building up the software while ensuring that all tests continue to pass.

Challenges

  • Learning Curve: TDD is a skill and discipline that can take considerable time to develop. After 6 months of TDD, you may still feel like TDD is difficult and gets in the way of productivity. However, after 2 years with TDD, you will likely find that it has become second nature, and that you are more productive than ever before.
  • Time-Consuming: Writing tests for every small functionality can feel time-consuming initially, though it usually pays off in the long term with reduced bugs and easier maintenance. I often tell people, “if you think you don’t have time for TDD, you really don’t have time to skip TDD.”

Preparing yourself to answer these questions in an interview setting will certainly help you stand out from the crowd. It will help you become a better JavaScript developer, and that will help you thrive in your new role.

Next Steps

If you enjoyed this article and would like to learn more about software development or Eric Elliot’s content — please hold the clap button on this article and subscribe to my page. Topics include JavaScript, TypeScript, React, TDD, AI Driven Development, and Engineering Leadership. Join today at DevAnywhere.io.

···

Asim Zaidi has been a Senior Software Engineer for Apple, Senior Software Engineer at Atlassian, renown Medium Author, Managing Partner @ Techmade, Co-Founder @ jail.app and more.

Would you like 1:1 career coaching from me? Sign up here and I will contact you. Subscribe to get more of my posts. I can teach you how to optimize your LinkedIn to get interviews from top tech companies!

Don’t forget to clap and subscribe if you enjoyed!

~ 25 y/o Builder from Chicago, Asim Zaidi

Senior Software Engineer @Apple

Prev: Senior Software Engineer @Atlassian

Founder: Techmade ([email protected]) / Land a Job in Tech.

Twitter for my Web3 shenanigans: _asimzaidi_

JavaScript
Software Development
Software Engineering
Front End Development
React
Recommended from ReadMedium