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.
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])).
The Array from() method converts Sets and other iterable objects to arrays.
JavaScriptCopied!
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.
JavaScriptCopied!
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:
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:
JavaScriptCopied!
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]).
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.
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.
ShellCopied!
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.
ShellCopied!
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.
ShellCopied!
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:
ShellCopied!
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:
ShellCopied!
npm update -g @vue/cli
# OR
yarn global upgrade --latest @vue/cli
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.
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:
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.
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.
ShellCopied!
# 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.
ShellCopied!
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 bySlack and Envato.
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.
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.
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.
Why would you need to move a line/selection up or down in code?
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.
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.
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.
Or with the keyboard shortcuts:
Windows/Linux: Alt + ↑ (Up arrow)
Mac: Option + ↑
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.
Or with the keyboard shortcuts:
Windows/Linux: Alt + ↓ (Down arrow)
Mac:Option + ↓
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.
To change the keybinding, search for “move line up” or “move line down” in the search bar.
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.
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.
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.vueCopied!
<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.
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.
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.
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:
JavaScriptCopied!
// 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:
JavaScriptCopied!
// 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?
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:
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.jsxCopied!
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.
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.
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.
The “Unexpected reserved word ‘enum'” syntax error happens in JavaScript happens because enum is not a valid keyword in JavaScript, but it is reserved.
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!
JavaScriptCopied!
// ❌ 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:
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?
PythonCopied!
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.
JavaScriptCopied!
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.
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!