Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to quickly get the union of two arrays in JavaScript

To get the union of two arrays in JavaScript, merge the arrays, create a new Set object from the merged result to remove the duplicates, then convert it back to an array, i.e., Array.from(new Set([...arr1, ...arr2])).

For example:

JavaScript
function getUnion(arr1, arr2) { return Array.from(new Set([...arr1, ...arr2])); } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

Array.from() method

The Array from() method converts Sets and other iterable objects to arrays.

JavaScript
const set = new Set(['Paul', 'John', 'George', 'Ringo']); const arr = Array.from(exampleSet); console.log(arr); // ['Paul', 'John', 'George', 'Ringo'] const map = new Map(); map.set('Bob', 'Marley'); map.set('Mick', 'Jagger'); let arr2 = Array.from(map); console.log(exampleArray2); // [ ['Bob', 'Marley'], ['Mick', 'Jagger'] ]

Set() constructor

We create these sets with the Set constructor, which can only contain unique values, so it removes any possible duplicates that may be in the array it receives.

JavaScript
const set = new Set([1, 1, 2, 3, 3, 4]); console.log(Array.from(set)); // [1, 2, 3, 4]

Spread syntax (...)

To pass this array to the Set() constructor, we use the spread syntax (...) to merge the two arrays together. The spread syntax unpacks the value of each array into another array:

JavaScript
const array1 = [10, 20, 30]; const array2 = [40, 50, 60]; const mergedArray = [...array1, ...array2]; console.log(mergedArray);

Use Array concat() to merge arrays for Set()

We could use the Array concat() method in place of the spread syntax:

JavaScript
function getUnion(arr1, arr2) { return Array.from(new Set(arr1.concat(arr2))); } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

Use Array from() to convert Set back to array

And we could use this spread syntax to replace the Array from(), although this may make the code a bit less readable:

JavaScript
function getUnion(arr1, arr2) { return [...new Set([...arr1, ...arr2])]; } const array1 = [1, 2, 3, 4, 5]; const array2 = [4, 5, 6, 7, 8]; const union = getUnion(array1, array2); // [1, 2, 3, 4, 5, 6, 7, 8] console.log(union);

We can use the same principles to easily get the union of two sets in JavaScript.

Get union of two sets in JavaScript

To get the union of two sets in JavaScript, convert the sets to arrays and merge them, then create a Set from the results of the merge.

For example:

JavaScript
function getUnion(set1, set2) { return new Set([...set1, ...set2]); } const set1 = new Set(['a', 'b', 'c', 'd']); const set2 = new Set(['c', 'd', 'e', 'f']); const union = getUnion(set1, set2); console.log(union); // Set(6) { 'a', 'b', 'c', 'd', 'e', 'f' }

Key takeaways

  • To get the union of two arrays in JavaScript, create a new Set object from the merge of the two arrays, then convert this Set object to an array again, i.e., Array.from(new Set(arr1.concat(arr2))).
  • We can do a similar thing to get the union of two sets, i.e., new Set([...set1, ...set2]).

How to quickly fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js

The ERR_OSSL_EVP_UNSUPPORTED error happens in Node.js when a JavaScript module still uses a flawed OpenSSL version that is incompatible with the version Node.js uses.

The ERR_OSSL_EVP_UNSUPPORTED error occurring.
The ERR_OSSL_EVP_UNSUPPORTED error occurring.

To fix it, downgrade to Node.js v16.13.0, or use the npm audit fix --force command to upgrade your packages to versions that use the updated OpenSSL version.

Why does the ERR_OSSL_EVP_UNSUPPORTED error occur in Node.js?

In Node.js v17, the Node.js team patched an OpenSSL security vulnerability. This fix introduced a breaking change; if you try to use OpenSSL in Node.js v17 or later versions without simultaneously updating those modules that use previous OpenSSL versions, you’ll get this error.

And you’ll get it the next time Node.js updates to use a newer OpenSSL version with breaking changes and you haven’t updated the OpenSSL-dependent libraries.

Fix: upgrade NPM packages

To fix the ERR_OSSL_EVP_UNSUPPORTED error, update the Node.js packages causing the error to the latest version.

Run npm audit fix to fix vulnerabilities

You can run the npm audit fix command to identify those packages using the outdated OpenSSL version and fix them automatically.

Shell
npm audit fix

npm audit fix reviews the project’s dependency tree to identify packages that have known vulnerabilities, and attempts to upgrade and/or fix the vulnerable dependencies to a safe version.

npm audit fix --force

If you want to install semver major updates to vulnerable packages, you can use the --force option. 

Shell
npm audit fix --force

Be cautious with this option as it could potentially break your project.

yarn-audit-fix

If you’re a Yarn user, you can use the yarn-audit-fix package to do what npm audit fix does.

Upgrade Webpack to v5

If you’re using Webpack directly to bundle your files, you can upgrade it to version v5 – specifically, v5.61.0 – to fix the ERR_OSSL_EVP_UNSUPPORTED error.

Shell
npm i webpack@latest # Yarn yarn add webpack@latest

If instead, you’re using a tool like Create React App and the Vue CLI that use Webpack internally, you’ll upgrade the tool to a version that doesn’t have this error.

Fix for Create React App: Upgrade react-scripts to v5

If you’re using Create React App then you can fix the ERR_OSSL_EVP_UNSUPPORTED error by upgrading react-scripts to version 5, which comes with the newer Webpack version 5.

Install version 5 or later with this command:

Shell
npm i react-scripts@latest # Yarn yarn add react-scripts@latest

Fix for Vue CLI: Upgrade to v5

Similarly for the Vue CLI, you can fix the ERR_OSSL_EVP_UNSUPPORTED error by upgrading the Vue CLI to version 5 which also comes with the newer Webpack version 5.

Install Vue CLI version 5 or later with this command:

Shell
npm update -g @vue/cli # OR yarn global upgrade --latest @vue/cli

More info on how to upgrade the Vue CLI here.

Fix: Use --openssl-legacy-provider option

To fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js, you can also use the --openssl-legacy-provider option when running the script.

This solution is more of a hack though, as it leaves your app open to security threats.

The --openssl-legacy-provider option is only available in Node version 17 or later.

Run with script

So for the start script, you’ll use this command:

Shell
export NODE_OPTIONS=--openssl-legacy-provider && npm run start # Windows set NODE_OPTIONS=--openssl-legacy-provider && npm run start

Modify script

You can also set this directly in the script to avoid needless repetition.

On Linux/Mac:

JSON
{ ... "scripts": { "start": "export NODE_OPTIONS=--openssl-legacy-provider && webpack serve", "build": "webpack --mode production" } ... }

On Windows:

JSON
{ ... "scripts": { "start": "set NODE_OPTIONS=--openssl-legacy-provider && node .", "build": "set NODE_OPTIONS=--openssl-legacy-provider && node build.js" } ... }

Make sure the script is cross-platform

But now the scripts aren’t cross-platform.

They’ll obviously be problematic when collaborating and team members use other operating systems. What do we do? We install the cross-env NPM module and run the script with it.

Shell
npm i cross-env # Yarn yarn add cross-env
JSON
{ ... "scripts": { "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider webpack .", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider node build.js" }, "devDependencies": { "cross-env": "^7.0.3" } ... }

Now the script runs successfully on every platform.

Fix for Vue CLI

So to fix the ERR_OSSL_EVP_UNSUPPORTED error when using Vue with the Vue CLI, install the cross-env module and set the --openssl-legacy-provider option:

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider vue-cli-service serve", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix for Create React App

And to fix the ERR_OSSL_EVP_UNSUPPORTED error when using React with Create React App, install the cross-env module and set the --openssl-legacy-provider option.

JSON
{ ... "scripts": { "serve": "cross-env NODE_OPTIONS=--openssl-legacy-provider ", ... }, "devDependencies": { "cross-env": "^7.0.3" ... } ... }

Fix: Downgrade to Node.js v16.13.0

To fix the ERR_OSSL_EVP_UNSUPPORTED error in Node.js, downgrade your Node.js version to 16.13.0.

This solution is more of a hack though, as it leaves your app open to security threats.

Install from official website

Use this official link to download Node.js v16.13.0.

Install with Chocolatey

If you’re using Chocolatey, Node.js is available as the nodejs package, meaning you can easily install it in a terminal using the following command.

Shell
# Use current LTS version choco install nodejs --version=18.5.0

Install with nvm

If you’re using nvm or nvm-windows, use these commands to quickly install and switch to Node.js v16.13.0.

Shell
nvm install 16.13.0 nvm use 16.13.0

Key takeaways

  • The ERR_OSSL_EVP_UNSUPPORTED error in Node.js occurs when a JavaScript module uses an outdated OpenSSL version that is incompatible with the current Node version. This typically happens when Node.js v17 or later versions are used without updating the modules that use previous OpenSSL versions.
  • To fix this error, you can:
    • Downgrade to Node.js v16.13.0.
    • Use the npm audit fix --force or yarn-audit-fix command to upgrade your packages to versions that use the updated OpenSSL version.
  • If you’re using Webpack, you can upgrade it to version v5.61.0 to fix the error. For Create React App and Vue CLI, you can upgrade them to v5.
  • Another way to fix the error is to use the --openssl-legacy-provider option when running the script. However, this solution leaves your app open to security threats and is only available in Node version 17 or later.
  • Downgrading to Node.js v16.13.0 is another way to fix the error. However, this solution also leaves your app open to security threats. You can install this version from the official website, or use Chocolatey, nvm, or nvm-windows to install and switch to this version.

Fine-tuning for OpenAI’s GPT-3.5 Turbo model is finally here

Some great news lately for AI developers from OpenAI.

Finally, you can now fine-tune the GPT-3.5 Turbo model using your own data. This gives you the ability to create customized versions of the OpenAI model that perform incredibly well at specific tasks and give responses in a customized format and tone, perfect for your use case.

For example, we can use fine-tuning to ensure that our model always responds in a JSON format, containing Spanish, with a friendly, informal tone. Or we could make a model that only gives one out of a finite set of responses, e.g., rating customer reviews as critical, positive, or neutral, according to how *we* define these terms.

As stated by OpenAI, early testers have successfully used fine-tuning in various areas, such as being able to:

  • Make the model output results in a more consistent and reliable format.
  • Match a specific brand’s style and messaging.
  • Improve how well the model follows instructions.

The company also claims that fine-tuned GPT-3.5 Turbo models can match and even exceed the capabilities of base GPT-4 for certain tasks.

Before now, fine-tuning was only possible with weaker, costlier GPT-3 models, like davinci-002 and babbage-002. Providing custom data for a GPT-3.5 Turbo model was only possible with techniques like few-shot prompting and vector embedding.

OpenAI also assures that any data used for fine-tuning any of their models belongs to the customer, and then don’t use it to train their models.

What is GPT-3.5 Turbo, anyway?

Launched earlier this year, GPT-3.5 Turbo is a model range that OpenAI introduced, stating that it is perfect for applications that do not solely focus on chat. It boasts the capability to manage 4,000 tokens at once, a figure that is twice the capacity of the preceding model. The company highlighted that preliminary users successfully shortened their prompts by 90% after applying fine-tuning on the GPT-3.5 Turbo model.

What can I use GPT-3.5 Turbo fine-tuning for?

  • Customer service automation: We can use a fine-tuned GPT model to make virtual customer service agents or chatbots that deliver responses in line with the brand’s tone and messaging.
  • Content generation: The model can be used for generating marketing content, blog posts, or social media posts. The fine-tuning would allow the model to generate content in a brand-specific style according to prompts given.
  • Code generation & auto-completion: In software development, such a model can provide developers with code suggestions and autocompletion to boost their productivity and get coding done faster.
  • Translation: We can use a fine-tuned GPT model for translation tasks, converting text from one language to another with greater precision. For example, the model can be tuned to follow specific grammatical and syntactical rules of different languages, which can lead to higher accuracy translations.
  • Text summarization: We can apply the model in summarizing lengthy texts such as articles, reports, or books. After fine-tuning, it can consistently output summaries that capture the key points and ideas without distorting the original meaning. This could be particularly useful for educational platforms, news services, or any scenario where digesting large amounts of information quickly is crucial.

How much will GPT-3.5 Turbo fine-tuning cost?

There’s the cost of fine-tuning and then the actual usage cost.

  • Training: $0.008 / 1K tokens
  • Usage input: $0.012 / 1K tokens
  • Usage output: $0.016 / 1K tokens

For example, a gpt-3.5-turbo fine-tuning job with a training file of 100,000 tokens that is trained for 3 epochs would have an expected cost of $2.40.

OpenAI, GPT 3.5 Turbo fine-tuning and API updates

When will fine-tuning for GPT-4 be available?

This fall.

OpenAI has announced that support for fine-tuning GPT-4, its most recent version of the large language model, is expected to be available later this year, probably during the fall season. This upgraded model has been proven to perform at par with humans across diverse professional and academic benchmarks. It surpasses GPT-3.5 in terms of reliability, creativity, and its capacity to deal with instructions that are more nuanced.

10 powerful JavaScript animation libraries for engaging user experiences

Animations. A fantastic way to stand out from the crowd and grab the attention of your visitors.

With creative object motion and fluid page transitions, you not only add a unique aesthetic appeal to your website but also enhance user engagement and create a memorable first impression.

And creating animations can’t get any easier with these 10 powerful JavaScript libraries. Scroll animations, handwriting animations, SPA page transitions, typing animations, color animations, SVG animations… they are endlessly capable. They are the best.

1. Anime.js

An animation creating with Anime.js
An animation created with Anime.js.

With over 43k stars on GitHub, Anime.js is easily one of the most popular animation libraries out there.

It’s a lightweight JavaScript animation library with a simple API that can be used to animate CSS properties, SVG, DOM attributes, and JavaScript objects. With Anime.js, you can play, pause, restart or reverse an animation. The library also provides staggering features for animating multiple elements with follow-through and overlapping actions. There are various animation-related events also included, which we can listen to using callbacks and Promises.

Visit the Anime.js website

2. Lottie

An animation created with Lottie.js
An animation created with Lottie.

Lottie is a library that parses Adobe After Effects animations exported as JSON with the Bodymovin plugin and renders them natively on mobile and web applications. This eliminates the need to manually recreate the advanced animations created in After Effects by expert designers. The Web version alone has over 27k stars on GitHub.

Visit the Lottie website

3. Velocity

An animation created with Velocity.
An animation created with Velocity.

With Velocity you create color animations, transforms, loops, easings, SVG animations, and more. It uses the same API as the $.animate() method from the jQuery library, and it can integrate with jQuery if it is available. The library provides fade, scroll, and slide effects. Besides being able to control the duration and delay of an animation, you can reverse it sometime after it has been completed, or stop it altogether when it is in progress. It has over 17k stars on GitHub and is a good alternative to Anime.js.

Visit the Velocity website

4. Rough Notation

Som Rough Notation annotation styles.
Some Rough Notation annotation styles.

Rough Notation is a JavaScript library for creating and animating colorful annotations on a web page. It uses RoughJS to create a hand-drawn look and feel. You can create several annotation styles, including underline, box, circle, highlight, strike-through, etc., and control the duration and color of each annotation style.

Visit the Rough Notation website

5. Popmotion

An animation created with Popmotion.
An animation created with Popmotion.

Popmotion is a functional library for creating prominent and attention-grabbing animations. What makes it stand out? – there are zero assumptions about the object properties you intend to animate, but instead provides simple, composable functions that can be used in any JavaScript environment.

The library supports keyframes, spring and inertia animations on numbers, colors, and complex strings. It is well-tested, actively maintained, and has over 19k stars on GitHub.

Visit the Popmotion website

6. Vivus

An animation created with Vivus.
An animation created with Vivus.

Vivus is a JavaScript library that allows you to animate SVGs, giving them the appearance of being drawn. It is fast and lightweight with exactly zero dependencies, and provides three different ways to animate SVGs: Delayed, Sync, and OneByOne. You can also use a custom script to draw an SVG in your preferred way.

Vivus also allows you to customize the duration, delay, timing function, and other animation settings. Check out Vivus Instant for live, hands-on examples.

Visit the Vivus website

7. GreenSock Animation Platform (GSAP)

An animation created with GSAP

The GreenSock Animation Platform (GSAP) is a library that lets you create wonderful animations that work across all major browsers. You can use it in React, Vue, WebGL, and the HTML canvas to animate colors, strings, motion paths, and more. It also comes with a ScrollTrigger plugin that lets you create impressive scroll-based animations with little code.

Used in over 11 million sites, with over 15k stars on GitHub, it is a versatile and popular indeed. You can use the GSDevTools from GreenSock to easily debug animations created with GSAP.

Visit the GSAP website

8. Three.js

An animation created with Three.js
An animation created with Three.js

Three.js is a lightweight library for displaying complex 3D objects and animations. It makes use of WebGL, SVG, and CSS3D renderers to create engaging three-dimensional experiences that work across a wide range of browsers and devices. It is a well-known library in the JavaScript community, with over 85k stars on GitHub.

Visit Three.js website

9. ScrollReveal

ScrollReveal animations.
ScrollReveal animations.

The ScrollReveal library lets you easily animate a DOM element as it enters or leaves the browser viewport. It provides various types of elegant effects to reveal or hide an element on-scroll in multiple browsers. And quite easy to use too, with with zero dependencies and over 21k stars on GitHub.

Visit the ScrollReveal website

10. Barba.js

Page transitions created with Barba.js.
Page transitions created with Barba.js.

One creative way to make your website outstanding is to add lively transitions between the pages as your users navigate between them. This produces a better user experience than simply displaying the new webpage or reloading the browser.

And that’s why Barba.js is so useful; this library lets you create enjoyable page transitions by making the site run like a Single Page Application (SPA). It reduces the delay between pages and minimizes the number of HTTP requests that the browser makes. It’s gotten almost 11k stars on GitHub.

Visit Barba.js website

Bonus

11. Mo.js

An animation created with Mo.js
An animation created with Mo.js.

Great library for creating compelling motion graphics.

It provides simple, declarative APIs for effortlessly creating smooth animations and effects that look great on devices of various screen sizes. You can move HTML or SVG DOM elements, or you can create a special Mo.js object, which comes with a set of unique capabilities. It is a reliable and well-tested library, with over 1500 tests written and over 17k stars on GitHub.

Visit the Mo.js website

12. Typed.js

An animation created with Typed.js

The name says it all; an animated typing library.

It types out a specific string character by character as if someone was typing in real-time, allowing you pause the typing speed, and even pause the typing for a specific amount of time. With smart backspacing, it types out successive strings starting with the same set of characters as the current one without backspacing the entire preceding string – as we saw in the demo above.

Also included is support for bulk typing, which types out a group of characters on the screen at the same time, instead of one after the other. Typed.js has over 12k stars on GitHub and is trusted by Slack and Envato.

Visit the Typed.js website

Final thoughts

The world of web animation is vast and dynamic, constantly evolving with the advent of new technologies and libraries. The animation libraries highlighted in this article offer an array of features to create engaging, interactive, and visually appealing experiences for users. They are a testament to the power and flexibility of JavaScript, and demonstrate how animations greatly enhance the user experience.

As a developer, harnessing these tools will no doubt elevate your projects, making them stand out in an increasingly competitive digital landscape.

How to move a line or selection up or down in VS Code

To move a line up or down in Visual Studio Code, use this keyboard shortcut:

  • Windows and Linux: Alt + ↑ (Up arrow) to move line up; Alt + ↓ (Down arrow) to move line down.
  • Mac: Option + ↑ to move line up; Option + ↓ to move line down.
Moving a line up or down in Visual Studio Code.

Move selection up or down in VS Code

Similarly, to move a selection up or down in Visual Studio Code, use this keyboard shortcut:

  • Windows and Linux: Alt + ↑ (Up arrow) to move selection up, Alt + ↓ (Down arrow) to move selection down.
  • Mac: Option + ↑ to move selection up, Option + ↓ to move selection down.
Moving a selection up or down in Visual Studio Code.

Why would you need to move a line/selection up or down in code?

  1. Refactoring: When cleaning up your code, you may need to move lines of code around in and out of functions and classes, to make it more readable and maintainable.
  2. Debugging: Like when fixing that error caused by using a variable before declaration/initializing it; with the keyboard shortcuts you easily move the declaration line up before the usage.
  3. Changing control flow: For those instances where the order of function calls or assignments need to change to reflect a new code logic update.

Commands in Visual Studio Code

In VS Code, we have commands, defined actions that carry our various operations in the editor.

We can easily run a command with the Command Palette, which we can access with these keyboard shortcuts:

  • Windows / Linux: Ctrl + Shit + P
  • Mac: Command + Shift + P

The Move Line Up command in VS Code

To move a line/selection up in Visual Studio Code, we use the Move Line Up command.

Moving a line up with the Move Line Up command.

Or with the keyboard shortcuts:

  • Windows/Linux: Alt + ↑ (Up arrow)
  • Mac: Option + ↑
Moving a line up in Visual Studio Code with the keyboard shortcut.

The Move Line Down command in VS Code

In the same manner, to move a line/selection down in Visual Studio Code, we use the Move Line Down command.

Moving a line down in Visual Studio Code with the Move Line Down command

Or with the keyboard shortcuts:

  • Windows/Linux: Alt + ↓ (Down arrow)
  • Mac: Option +
Moving a line down with keyboard shortcuts

Change keyboard shortcut to move line up or down

Personally, I think they’re fine, but if you don’t like the keyboard shortcut to move the line up or down, then navigate to the Keyboard Shortcuts page and change the keybinding for the Move Line Up and Move Line Down commands.

There are multiple ways to get this page; you can click the Keyboard Shortcuts item on the Manage popup shown below or use the shortcut next to the text (Ctrl + K Ctrl + S) here.

Opening the Keyboard Shortcuts page from the Settings popup

To change the keybinding, search for “move line up” or “move line down” in the search bar.

Searching for the Move Line Up command in the Keyboard Shortcuts page
Searching for the Move Line Down command in the Keyboard Shortcuts page of VS Code

Then double-click on the Move Line Up or Move Line Down command, type a new keyboard shortcut, and press the Enter key to carry out the change.

Changing the default keybinding for the Move Line Down command

The change here was Ctrl + E, Ctrl + E – certainly not the smartest choice, but now you’ve seen how it works.

Key takeaways

  • To move a line or selection up or down in Visual Studio Code, use the Alt + ↑ (Up arrow) for up and Alt + ↓ (Down arrow).
  • Moving lines or selections up or down in code can be useful for refactoring, debugging, and changing control flow.
  • You can change the keyboard shortcut to move a line up or down by changing the Move Line Up and Move Line Down command.

How to prevent form submission in Vue.js

To prevent a page refresh on form submit in Vue.js, use the .prevent event modifier in the submit event listener.

App.vue
<template> <div id="app"> <form @submit.prevent="handleSubmit"> <label> Email <br /> <input type="email" v-model="email" required /> </label> <br /> <label> Password <br /> <input type="password" v-model="password" required /> </label> <br /> <button type="submit" style="margin-top: 16px" > Submit </button> </form> </div> </template> <script> export default { name: 'App', data() { return { email: '', password: '', }; }, methods: { handleSubmit() { this.email = ''; this.password = ''; alert('Form submitted'); }, }, }; </script>
The page refresh is prevented in Vue.js when the button submits the form.

We use the .prevent modifier to stop the default action of the event from happening. In this case, that action was a page refresh, so .prevent stopped the page refresh on the form submission.

App.vue
<form @submit.prevent="handleSubmit">

.prevent is a Vue.js event modifier, which lets us access and modify event-related data.

We use the @submit directive to add a submit event listener to the form; this listener runs when the user clicks the button to submit the form.

In this case we only reset the form; in practical scenarios you’ll likely make an AJAX request to a server with the form data.

App.vue
<template> ... </template> <script> export default { ... methods: { async handleSubmit() { const user = { email: this.email, password: this.password, }; try { const response = await axios.post('http://your-api-url.com', user); console.log(response.data); } catch (error) { console.error(error); } this.email = ''; this.password = ''; } } }; </script>

For the button to submit the form, we must set its type attribute to "submit"

App.vue
<button type="submit" style="margin-top: 16px;"> Submit </button>

With type="submit", the browser also submits the form when the user presses the Enter key in an input field.

Remove type="submit" from the button to prevent page refresh

To prevent page refresh on form submit in Vue.js, you can also remove the type="submit" from the button.

When is this useful? You may want to show an alert message or something before submission. In this case, we wouldn’t want type="submit" since it submits the form on button click.

App.vue
<template> <div id="app"> <form> <label> Email <br /> <input type="email" v-model="email" required /> </label> <br /> <label> Password <br /> <input type="password" v-model="password" required /> </label> <br /> <button type="button" @click="handleSubmit" style="margin-top: 16px" > Submit </button> </form> </div> </template> <script> export default { data() { return { email: '', password: '', }; }, methods: { handleSubmit() { // Perform custom actions before form submission alert('Are you sure you want to submit the form?'); // Simulate form submission by clearing input fields this.email = ''; this.password = ''; alert('Form submitted'); }, }, }; </script>
Preventing a page refresh on form submit in Vue.js to show an alert dialog before submission.

We used type="button" on the button, but that’s as good as not having a type attribute. It doesn’t do anything on click.

Key takeaways

  • To prevent page refresh on form submit in Vue.js, use the .prevent modifier in the submit event listener.
  • Set type="submit" to ensure the form submits on button click or Enter press. Remove it when you don’t want this.
  • Remove type="submit" when something needs to happen after the button click before submitting the form, e.g., show a dialog, make an initial request, etc.

How to check if a variable is null or undefined in React

To check if a variable in null or undefined in React, use the || operator to check if the variable is equal to null or equal to undefined.

JavaScript
import { useState } from 'react'; export default function App() { const [variable] = useState(undefined); const [message, setMessage] = useState(undefined); const nullOrUndefinedCheck = () => { // Check if undefined or null if (variable === undefined || variable === null) { setMessage('Variable is undefined or null'); } else { setMessage('Variable is NOT undefined or null'); } // Check if NOT undefined or null if (variable !== undefined && variable !== null) { setMessage('Variable is NOT undefined or null'); } }; return ( <div> <button onClick={() => nullOrUndefinedCheck()}>Check variable</button> <h2>{message}</h2> </div> ); }
Checking if a variable is null or undefined in React.

The logical OR (||) operator

The logical OR operator (||) results in true if either the value at the left or right is true.

JavaScript
const isTrue = true; const isFalse = false; const result1 = isTrue || isFalse; console.log(result1); // Output: true const result2 = isFalse || isFalse; console.log(result2); // Output: false

When you use || on non-boolean values, it returns the first truthy value:

JavaScript
const str = ''; const num = 0; const result1 = str || 'Default String'; console.log(result1); // Output: 'Default String' const result2 = num || 42; console.log(result2); // Output: 42

The falsy values in JavaScript are undefined, null, 0, NaN, '' (empty string), and false. Every other value is truthy.

Checking if NOT null or undefined with De Morgan’s laws

From De Morgan’s law, not (A or B) = not A and not B, where A and B are boolean conditions.

That’s why we used this condition to check if the variable is not null or undefined:

JavaScript
// not A and not B if (variable !== undefined && variable !== null) { setMessage('✅ Variable is NOT undefined or null'); }

And why we could just as easily do this:

JavaScript
// not (A or B) if (!(variable === undefined || variable === null)) { setMessage('✅ Variable is NOT undefined or null'); }

null and undefined are the same with ==

It’s important you use === over == for the check, if you want null and undefined to be treated separately. == is known as the loose equality operator, can you guess why it has that name?

JavaScript
console.log(null == undefined); // true console.log(null === undefined); // false

Loose equality fails in cases where undefined and null don’t mean the same thing.

Imagine a shopping cart application where a user adds items the cart, represented by a cartItems variable.

  • If cartItems is undefined, it’ll mean that the shopping cart hasn’t been initialized yet, or an error occurred while fetching it, and we should load this data before proceeding.
  • If cartItems is null, it’ll mean that the shopping cart is empty – the user hasn’t added any items yet.

Here’s a simplified example of how you might handle this in a React component:

JavaScript
import React, { useEffect, useState } from 'react'; const ShoppingCart = () => { const [cartItems, setCartItems] = useState(); // ... useEffect(() => { // Assume fetchCartItems() returns a promise that resolves to the cart items fetchCartItems() .then((items) => setCartItems(items)) .catch(() => setCartItems(null)); }, []); if (cartItems === undefined) { return <div>Loading cart items...</div>; } else if (cartItems === null) { return <div>Your shopping cart is empty! Please add some items.</div>; } else { return ( <div> <h2>Your Shopping Cart</h2> {cartItems.map((item) => ( <p key={item.id}>{item.name}</p> ))} </div> ); } }; export default ShoppingCart;

If we had used the == operator, only the first comparison to undefined or null would have run.

Check for null, undefined, or anything falsy in React

Instead of checking explicitly for null or undefined, you might be better off checking if the variable is falsy.

JavaScript
import { useState } from 'react'; export default function App() { const [variable] = useState(undefined); const [message, setMessage] = useState(undefined); const falsyCheck = () => { // Check if falsy if (!variable) { setMessage('✅ Variable is falsy'); } else { setMessage('❌ Variable is NOT falsy'); } }; return ( <div> <button onClick={() => falsyCheck()}>Check variable</button> <h2>{message}</h2> </div> ); }

By passing the variable to the if statement directly, it is coalesced to a true or false boolean depending on whether the value is truthy or falsy.

The falsy values in JavaScript are undefined, null, 0, NaN, '' (empty string), and false. Every other value is truthy.

How to prevent page refresh on form submit in React

To prevent a page refresh on form submit in React, call event.preventDefault() in the submit event listener.

App.jsx
import React, { useState } from 'react'; function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleEmailChange = (event) => { setEmail(event.target.value); }; const handlePasswordChange = (event) => { setPassword(event.target.value); }; const handleSubmit = (event) => { event.preventDefault(); // Simulate form submission by clearing input fields setEmail(''); setPassword(''); }; return ( <form onSubmit={handleSubmit}> <label> Email <br /> <input type="email" value={email} onChange={handleEmailChange} required /> </label> <br /> <label> Password <br /> <input type="password" value={password} onChange={handlePasswordChange} required /> </label> <br /> <button type="submit" style={{ marginTop: 16 }}> Submit </button> </form> ); } export default function App() { return <LoginForm />; }
The page refresh is prevented in React when the button submits the form.

We use the Event preventDefault() method to stop the default action of the event from happening. In this case, that action was a page refresh, so preventDefault() prevented the page refresh on the form submission.

App.jsx
const handleSubmit = (event) => { event.preventDefault(); // Simulate form submission by clearing input fields setEmail(''); setPassword(''); };

preventDefault() is a property of an Event object, which lets us access and modify event-related data.

We use the onSubmit prop to add a submit event listener to the form; this listener runs when the user clicks the button to submit the form.

All we did here was reset the form, but of course in the real world, you probably want to make an AJAX request to a server with the form data.

App.jsx
const handleSubmit = async (event) => { event.preventDefault(); const user = { email: email, password: password, }; try { const response = await axios.post('http://your-api-url.com', user); console.log(response.data); } catch (error) { console.error(error); } setEmail(''); setPassword(''); };

For the button to submit the form, we must set its type prop to submit

App.jsx
<button type="submit" style={{ marginTop: 16 }}> Submit </button>

With type="submit", the browser also submits the form when the user presses the Enter key in an input field.

Remove type="submit" from the button to prevent page refresh

To prevent page refresh on form submit in React, you can also remove the type="submit" from the button.

When is this useful? You may want to show an alert message or something before submission. In this case, we wouldn’t want type="submit" since it submits the form on button click.

App.jsx
import React, { useState } from 'react'; function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleEmailChange = (event) => { setEmail(event.target.value); }; const handlePasswordChange = (event) => { setPassword(event.target.value); }; const handleSubmit = () => { // Perform custom actions before form submission alert('Are you sure you want to submit the form?'); // Simulate form submission by clearing input fields setEmail(''); setPassword(''); }; return ( <form> <label> Email <br /> <input type="email" value={email} onChange={handleEmailChange} required /> </label> <br /> <label> Password <br /> <input type="password" value={password} onChange={handlePasswordChange} required /> </label> <br /> <button type="button" onClick={handleSubmit} style={{ marginTop: 16 }}> Submit </button> </form> ); } export default function App() { return <LoginForm />; }
Prevent a page refresh on form submit in React to show an alert dialog before submission.

We used type="button" on the button, but that’s as good as not having a type attribute. It doesn’t do anything on click.

Key takeaways

  • To prevent page refresh on form submit in React, call event.preventDefault() in the submit event listener.
  • Set type="submit" to ensure the form submits on button click or Enter press. Remove it when you don’t want this.
  • Remove type="submit" when you need to do something after the button click before submitting the form, e.g., show a dialog, make an initial request, etc.

How to Fix the “Unexpected reserved word ‘enum'” Error in JavaScript

The “Unexpected reserved word ‘enum'” syntax error happens in JavaScript happens because enum is not a valid keyword in JavaScript, but it is reserved.

The "Unexpected reserved word 'enum'" syntax error happening in JavaScript.

It was reserved in the ECMAScript specification in case it may become valid in the future.

If it wasn’t reserved, devs could start using it as variable names in their code – making future keyword use impossible!

JavaScript
// ❌ SyntaxError: Unexpected reserved word 'enum' enum Color { Red, Blue, Green } const color = Color.Red;

To fix it, represent the enumeration in another way, or change the file to TypeScript.

Fix: Create a JavaScript enum the right way

Enums are useful stuff, but since there’s no enum keyword in JS, we’ll have to find others way to create and use them.

One powerful way to create an enumeration is with an object with JavaScript symbol properties:

JavaScript
const daysOfWeek = { Mon: Symbol('Mon'), Tue: Symbol('Tue'), Wed: Symbol('Wed'), Thu: Symbol('Thu'), Fri: Symbol('Fri'), Sat: Symbol('Sat'), Sun: Symbol('Sun'), }; const dayOfWeek = daysOfWeek.Tue;

With JavaScript symbols, we make sure that the constants are always different values, as every symbol is unique.

No need to worry duplicates – pretty convenient, right?

If we used this:

JavaScript
const daysOfWeek = { Mon: 'Mon', Tue: 'Tue', Wed: 'Wed', Thu: 'Thu', Fri: 'Fri', Sat: 'Sat', Sun: 'Sun', }; const dayOfWeek = daysOfWeek.Tue;

Someone could easily reassign the object’s properties to something else, giving us something more to worry about.

Fix: Just use TypeScript

Ah, TypeScript.

Alway there for us. Filled to the top with juicy modern stuff.

I mean enums aren’t so modern, but it’s one thing TS has that JS doesn’t.

Our first JS code runs flawlessly in TypeScript.

TypeScript
// ✅ No error - enums all the way! enum Color { Red, Blue, Green } const color = Color.Red;

So, if you really need that enum keyword – even though much of the TypeScript community seems to frown on it – change that file extension.

Oh, it could even be that it’s TypeScript you wanted all along. As it happened here.

Here, this person was new to TypeScript on Node (we’ll all been there) and ran his TS file with the node command directly.

Well, Node didn’t care about the extension and just treated the entire thing like a JavaScript file.

The easy solution was to compile it first with tsc before running node on the JS output. Or to use ts-node on the TypeScript file directly.

Key takeaways

So, the few things to keep in mind on fixing the “Unexpected reserved keyword ‘enum'” error in JavaScript:

  1. enum is a no-go in JavaScript (for now): JavaScript doesn’t have enum. It’s reserved for future use.
  2. Use objects with symbol properties: Want to create enumerations in JavaScript? Use objects with symbol properties.
  3. Symbols keep your code safe: Symbols are unique. They stop others from messing with your object’s properties.
  4. TypeScript has enum: Need enum? Switch to TypeScript. It’s got your back.
  5. Remember to compile TypeScript: Using TypeScript for Node.js? Compile your TypeScript files first. Or quickly use ts-node.

This new ES7 feature made my math 3 times easier

But 5 lines of Java is one line of Python.

How many times have you heard something like that from lovers of the later?

Seems like they love to trash languages they stubbornly believe are verbose. I came to see that “Pythonic” is something truly cherished by our friends in the Python community.

Your Python code works, and so what? Where is elegance? Where is readability?

Think you can write a simple for loop and get away with it?

Python
total = 0 for i in range(1, 11): total += i print("The sum of the first 10 numbers is:", total)

Just wait till one of them find out — to say you’ll face severe criticism is an understatement.

Because apparently — and I kind of agree — it’s just not “beautiful” or concise enough.

To be “Pythonic” is best.

JavaScript
total = sum(i for i in range(1, 11)) print("The sum of the first 10 numbers is:", total)

An ES7 feature that brings syntactic sugar and conciseness

The ** operator.

This one almost always comes up in Python’s favor when talking about language conciseness, up there with generators and the // operator.

It’s good to know JavaScript now has this feature, over 6 years ago in fact.

But it was surprising to know that a sizeable number of our fellow JavaScripters never knew it’s in the language.

It’s now effortless to get the power of a number, with the ** operator. Instead of Math.pow(a, b), you do a ** b.

JavaScript
const result = Math.pow(10, 2); console.log(result); // 100 const result2 = Math.pow(2, Math.pow(3, 2)); console.log(result2); const result3 = 10 ** 2; console.log(result3); // 100 const result4 = 2 ** 3 ** 2; console.log(result4) // 512

We don’t need a function for such a common math operation anymore.

You can even pass a decimal number as a power with **Math.pow() can do this too:

JavaScript
const result = Math.pow(49, 1.5); console.log(result); // 343 const result2 = 49 ** 1.5; console.log(result2); // 343

And it’s not only a drop-in replacement for Math.pow(); ** can take BigInts too:

JavaScript
// ❌ Error: Cannot convert a BigInt value to a number const result1 = Math.pow(32n, 2); console.log(result1);
JavaScript
const result2 = 32n ** 2n; console.log(result2); // 1024n

BigInts let us represent numbers of any size without losing precision or experiencing overflow errors.

JavaScript
const veryLargeNumber = 1234567890123456789012345678901234567890n; console.log(typeof veryLargeNumber); // "bigint" console.log(veryLargeNumber * 2n); // 2469135780246913578024691357802469135780n

You can see that we simply add an n at the end of the digits to make it a BigInt.

Final thoughts

Language wars are a fun programmer pastime.

It’s always fun to debate about which programming language is more elegant and concise.

But at the end of the day, we’ve got to keep in mind that writing readable and maintainable code is what matters most.

In this article, we saw that the ** operator introduced in ES7 for JavaScript is a neat trick that can make your code more concise, and it even works with BigInts!

More features keep getting added every year — ES13 was released in 2022 — to increase and add more syntactic sugar.

So, keep exploring the possibilities of your favorite programming language, and have fun coding!