Category: Javascript

Landing your first job! Notes to my younger self.

Landing your first job! Notes to my younger self.

First ever conference talk complete! Something that was well worth the effort to create. Anyway I thought it would be great to put down my talk into words. I’ll put a post up per topic that was covered during my talk. I’ve yet to listen to my own talk, although I know I rattled through it faster than I wanted 🙂 So here I’ll expand what was in my head as well as some of the areas that I didn’t have enough time to delve into.

For those that didn’t attend or watch the React JS Finland conference (https://youtu.be/zE8PDM_7xoQ?t=11399) – it was great. Such a warm and welcoming bunch of people. And some of the people there are just amazing and super friendly. Helsinki may not seem like place to go – but I highly recommend it. The developer community feels like it’s really big and cooperative.

Getting started

This was my first point and the main jist of it is – without work experience how to do you get that experience so that someone hires you? This is something I didn’t do before I got a job, although over my early years in various jobs, I did things like this – which seriously helped me get more advanced roles.

Perhaps out of this section, the one thing I didn’t have time to mention was that I’ve seen over the years, that those who while at university (or similar) are able to get some kind of internship or summer time work experience (even if unpaid/helping charities etc) developing software. They are much more likely to be hired first.

While this perhaps seems a little unfair, as many can’t afford to work for free or next to nothing, life isn’t fair. Which is why you need to put the effort into the next part if you didn’t or couldn’t get work experience while learning at the same time.

View from the tower in the conference centre.

Motivation & Ideas

Two key things will hold you back, motivation and a good idea. You can look online and I’ve seen so many to-do lists, for example. While these are just fine for a tutorial, they aren’t the kind of thing that will excite you to keep programming for hours and days on end.

Too that end you’ll need to find yourself a good idea. So where to get that from? Well, in the past picking an item from one of your hobbies or interests. You will no doubt find that someone else has created something else that’s very similar, but don’t let that put you off. As you develop YOUR idea, you will end up adding your own twist to it.

Mental rewards

Whiteboard, sticky notes and pens. Why? Some people in the software world don’t do this (not even electronically). These people have been developing for a good while and when you interview them you can tell that what they do isn’t structured/well planned as it could be. Yes it’s not as simple as get a whiteboard, but it’s a mindset and the Jira/whiteboard board needs to be part of it. So what should you do?

Well, you have your idea/subject. It needs broken down into a few big tasks ‘epics’, then each of those needs to be broken down into individual units/stories. Those need prioritised. This is your first business take away. You will learn to prioritise them and now you have a concrete example to talk about in an interview (that bit is super important). When you do work on your tasks, work on them one by one. Only ever do one at a time! If you complete a story and something comes out of it, maybe just a ‘tiny’ task, you think I’ll just stick it onto this task. DON’T! Create a new task and do it right after, but don’t join the two together.

Buy yourself a physical whiteboard

The whiteboard

This is where the whiteboard/sticky notes come in. Put up enough to complete an actionable item/epic. Some of these many be learning tasks (spikes) as well as actual coding tasks. As an example you may need to investigate bundling/build tools. Task 1 could be to find out the top 3-5 tools available. You can have new tasks per tool. You’d create a ticket per tool and that will involve doing a small demo per tool. Finally you’d have a ticket to evaluate each one against the others. So a simple find a suitable build/bundler for your idea may well have 7 unique tasks/stories.

The act of progressing a ticket from ready for work, all the way along to done/released is a concept that although simple will trigger those mental rewards. You’ve done something! Great! The smaller the task the more tasks you can get done. There is nothing more demoralising that being stuck on the same task for days. If this is being done during a few spare hours, the smaller you can make the tasks the more likely you are to complete them. A large task requires much more time to get the task into your head. Sometimes by the time it’s in your head, and you’re flowing, the time is up. Keep them small.

There is a whole heap of knowledge out there on Agile (for example https://www.atatus.com/glossary/agile-methodology/), this post isn’t to teach you that, but to highlight doing it is very rewarding.

Takeaways

  • Get an idea for a project from your hobbies/interests.
  • Create tasks that are as small as you can make them.
  • Only ever do one task at a time.
  • Prioritise tasks to get something out/completed.
  • Think about why you are doing something. As in why is task A more important than task B.
  • You will be learning new techniques, think about how you implement such learnings, how to enhance your learnings.
  • Think about your flow, how to you improve it. Did you do anything that suited your style of code/learning.

Coding is as much about the process of writing code, as it about writing the actual code. Can you describe that?

Spread and Exclude

Spread and Exclude

The other day I wanted to log out some values of a large object. But one particular property was massive and not needed. So how could I pass all of the original object minus that one property that was going to get in the way?
As in how to exclude a single property from a object.

Solution:

It’s a very simple and I think elegant solution. so here it is.

Using the spread operator you can list the specific items to copy first (these will then be excluded) then use the … rest operator to copy the remaining items.

That’s it! It telling your code what to specifically copy first, those will then not be included when you use the rest operator. Brilliant!

const bigObject = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6};
const { a, ...copiedAndExcluded } = bigObject;
// copiedAndExcluded is now the same as bigObject, expect it doesn't have the property 'a'.

Also in my case the bigObject was a property of something else, which at times may have been undefined. This will cause an error, as you can’t spread undefined.

const parentObject = { a: 1, bigObject = undefined, c: 3, d: 4};
const { a, ...copiedAndExcluded } = parentObject.bigObject || {};
// 'a' and 'copiedAndExcluded' will be undefined

The `|| {}` will make sure that the code doesn’t try to spread the value of undefined (as that will throw an error). You can however spread an empty object. The values that come out will be undefined, which in my case was just fine.

Array’s – Reducing all duplicates

Array’s – Reducing all duplicates

Years ago when I blogged regularly about Actionscript/Flex some of the most simple and yet popular posts were on array’s.
Today I find myself doing something similar in Javascript – and there is no out of the box solution that I’m aware off.

Take a large array (where duplicates probably exist) and condense it into a collection of unique items.

Let’s say your hitting some API and it returns 1000’s of results, and in that result you want to find out how many unique types of XXXX there are. How would you do that?
One simple way is to use an object and store the items using the key part of an object.

const duplicatedArray = [
  { name: "Bob", hairColour: "Black" },
  { name: "Jane", hairColour: "Grey" },
  { name: "Mark", hairColour: "Red" },
  { name: "Marsalli", hairColour: "Black" },
  { name: "Rachel", hairColour: "Brown" },
  { name: "Craig", hairColour: "Red" },
];

const getUniqueCollection = (keyFilter) => {
  const reduced = {};
  duplicatedArray.forEach((person) => {
    reduced[person[keyFilter]] = person[keyFilter];
  });
  return reduced;
};

What’s going on is that it will pass only once through the array with duplication’s, and each time it will write that to the reduced object. If, as there is in this example it comes across two Black hair types then the 2nd one will overwrite the first, therefor removing any duplication.

End result, you now have an Object (some may well call this a dictionary) that on inspection contains unique list of hair colours. This for example could be used to populate a dropdown box or similar. Or you could use the below to iterate over the new object.

for (var key in uniqueCollection) {
    var value = uniqueCollection[key];
    // do something...
  }

Lets say you’ve a more complex object!

const complexDuplicatedArray = [
  { brand: "Ford", colour: "Black", ignoredProperty: "XXX" },
  { brand: "Tesla", colour: "Grey", ignoredProperty: "AAA" },
  { brand: "VW", colour: "Red", ignoredProperty: "222" },
  { brand: "Ford", colour: "Black", ignoredProperty: "111" },
  { brand: "Tesla", colour: "Brown", ignoredProperty: "ZZZ" },
  { brand: "VW", colour: "Red", ignoredProperty: "YYY" },
];

// pass in ["brand", "colour"] as the parameter keyFilter
const getComplexUniqueCollection = (keyFilter) => {
  const reduced = {};
  complexDuplicatedArray.forEach((car) => {
    const keyValue = JSON.stringify(car, keyFilter);
    reduced[keyValue] = keyValue;
  });
  return reduced;
};

So here we are filtering on 2 keys, the brand and the colour. Convert the object to a string and drop the properties that we do not care about.

JSON.stringify

The stringify part in the above is key. What’s it’s doing is taking an array of strings to include in the stringify process.
So using
myObj = { brand: "Ford", colour: "Black", ignoredProperty: "XXX" }
JSON.stringify( myObj, [‘brand’, ‘colour’]); will output
"{"brand":"Ford","colour":"Black"}"
This is ideal for using as the key to store, so if there is another Ford car that is Black with a different property that you wish to ignore, then it’s not included.

Overriding template literal strings

Overriding template literal strings

Have you been using template literals for a while? Most likely, but did you know that you can override how it constructs the overall string? I didn’t until recently.

If you haven’t seen it, then I think you’ll be sure to think that this code is really cool and so much potential use in other areas.

It’s called tagged templates. It means that rather than calling your literal with the standard joining method, you pass your arguments to your own method.
See the below – as ever code is the best way to explain.

const person1 = "Mike";
const person2 = "Bob";

const taggedTemplateStringLiteral = myMethod`you can say hello to ${person1} and ${person2} :)`;

function myMethod(baseMessages, ...params) {
  // The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
  // array.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
  return baseMessages.reduce((acc, cur, i) => {
    acc += `${params[i - 1]?.toUpperCase() ?? ""} ${cur}`;
    return acc;
  });

  /*   Adding in the below as this is perhaps a more common approach,
       but as show in previous post you can improve undefined checks
       with nullish coalescing as shown in the above snippet.

    return baseMessages.reduce((acc, cur, i) => {
      acc += `${params[i - 1] ? params[i - 1].toUpperCase() : ""} ${cur}`;
      return acc;
    }); 
  */
}

What’s going on?

Firstly you have you grave character `. This make it into a template literal. When a string is enclosed with those then each portion (split up by using ${ } for code/var segments) is then included into an array.
Next each parameter, whatever is evaluated for each ${ } block is passed as a separate parameter. You could call them individually or in my case I used the rest (…) operator to grab them all.

myMethod`you can say hello to ${person1} and ${person2} :)`

The means to invoke the method is what caught my eye, in that you do not call it like an actual method! The above ends up being the same as –

myMethod(["you can say hello to ", " and ", " :)"], "Mike", "Bob" );

Which is rather smart and a great little snippet to remember.

?? Nullish coalescing & Optional chaining ?.

?? Nullish coalescing & Optional chaining ?.

Javascript Sucks! It really really does at times. Take a look at the difference between the books ‘The Definitive Guide’ and the ‘the best bits’ 😁 I joke, of course, but some portions of it are just annoying.

It’s loose and simple way, is it’s strength and it’s weakness, but with each new feature from the latest ES++ range comes new means to clean up your code and hopefully stop shooting your feet!
The below new operators come from ES2020, the 11th edition.

Operators with ? in them can be a bit confusing if you’ve never seen them and also they are hard to search for. How do you search for ? if you don’t know the operator name? So this is here for my own bookmarking as well as a reference for others. First up we have the ??

?? is the Nullish Coalescing operator

What’s its purpose, to make getting expected true/false values back where it would seem normal to do so! What do I mean, well normally if you want something to be false you’d make it false. Or you’d expect null/undefined to be false.

But under normal circumstances, JS isn’t like that. I’m not going to go into the falsy/truthiness of JS, but to suffice to say that the ?? allows for default values such as 0 or an empty string to be valid values, rather than being false.

const textSetToAnEmptyString = "";
const DEAFAULT_TEXT = "This is the default";

const myText = textSetToAnEmptyString ?? DEAFAULT_TEXT;
console.log(myText); // ""

const myTextOldWay = textSetToAnEmptyString || DEAFAULT_TEXT;
console.log(myTextOldWay); // "This is the default" - probably not what you wanted

As can be seen if the text is set to an empty string which is a valid value, with the ?? operator it remains as an empty string, which is exactly what you’d wish.

But if you wished to use the || operator then the empty string will be changed as “” is considered false in JS land.

?. is the Optional chaining operator

Looking into this new feature, it is REALLY great.
Checking if a value exists in some nested object for JS is yet another of those painful items. Not that’s it hard to do, but it’s such bloated code.
So this is simplest to show via code

// set up an empty object
const obj = {};
const foo = obj.child;  // foo will be undefined - No error
const fooError = obj.child.secondChild;  // Error - can't access secondChild from an undefined value
const fooTwo = obj.child?.secondChild; // fooTwo will be undefined - no error
const fooThree = obj.child?.secondChild.thirdChild; // fooThree will be undefined - no error
const fooFour = obj.child?.secondChild.thirdChild.fourthChild; // undefined - no error

What’s going on with fooThree and fooFour???

Well the ?. operator is short circuiting when it goes to assign a value to to fooThree and fooFour.

  • Looks at obj – which is a valid object
  • looks for child, and JS being the way it is doesn’t complain, and returns undefined (as it does not exist)
  • ?. check now means that it will go no further as child was undefined
  • secondChild, thirdChild and fourthChild do not get looked at/processed due to the short circuiting of process

Also works on methods 👍

const myFunc = () => { return "WOOO" };

const foo = {
  methodX : myFunc
}

const message = foo.methodX(); // "WOOO"
const message2 = foo.methodY(); // Error - methodY does not exist
const message3 = foo.methodY?.(); // undefined and carries on

// The ?. syntax will also work in the same way with arrays
// such as myArray?.[12] 👍

Multiple ?.

In the above child isn’t defined, but what would happen if it was defined?

const obj = {};
obj.child = {}; // Set child to an empty object
const foo = obj.child?.secondChild; // undefined - no error
const fooTwo = obj.child?.secondChild.thirdChild; // Error - can't access thirdChild from an undefined value
const fooThree = obj.child?.secondChild?.thirdChild; // undefined - no error

Here we needed to insert a second ?., this will check that secondChild is set before moving on. So for fooTwo there is an error as thirdChild can’t be accessed from undefined, but fooThree is ok as it doesn’t get to thirdChild due to the short circuiting.

Combos!

Both the above are powerful tools and even better is that they can be combined!
Let’s say you

let myMap = new Map();
myMap.set("foo", {name: "baz", description: "" });
myMap.set("bar", {name: "baz" });

let descriptionFoo = myMap.get("foo")?.description ?? "description not set"; // output is ""
let descriptionFooOld = myMap.get("foo")?.description || "description not set"; // Output is "description not set" - not what you'd wish for as it has been set
let descriptionBar = myMap.get("bar")?.description ?? "description not set"; // output is "description not set" as it wasn't set

Hopefully the above will give you some ideas of where to use these new operators. I’m sure as I go through some old code I’ll see better examples on where to use them.

Moving from IntelliJ to VS Code

Moving from IntelliJ to VS Code

Change is hard, and it’s always harder if you’ve been using ‘X’ for years.

I’ve been using IntelliJ for a number of years now, and it is great! It really is, and there is no reason other than cost not to use it. If cost is not a concern then use IntelliJ.

Keyboard shortcuts

You’ve spent years in one IDE, your fingers just know where to go, what to do. That instinctive physical memory would be very hard to get over. Any change will immediately make you less productive. You’re just not going to do it!

Thankfully the benefit of the community around VS code comes to hand.

Install this and your fingers need not learn anything new!

Unit tests

Next up is testing. I really like right clicking on a test to run/debug it. The below is a partial solution (right click to debug fails)
This requires two extensions to get it to work.

1 – Test Explorer UI

This gives you the side panel where you can see your tests – but you will see ZERO tests in here to start of with. You need to install one more extension.

2 – Jest Test Explorer

Install the below and you will now see your tests in a panel inside VS Code

You can see the list of test now inside the Test explorer.

As yet, I’m unable to get ‘debug’ to work. I can debug the entire suite of tests via a config command, but not a single test via the context menu.
This is really annoying… I’ll come back to this if/when I figure it out.

Coverage

Next up is coverage mappings. You’ve run your tests, added the coverage flag and you want to see where in the code you are missing coverage.

WARNING/TIP

I found that after I had installed the above, ran my coverage that nothing was being highlighted. After messing around with configuration for ages, restarting IDE etc and getting nowhere I disabled (not uninstalled) the previous extensions ( Jest Test Explorer and Test Explorer UI). After another restart of VS code, hey presto it worked!!!
Re-enabled the Test extensions and now all the extensions where working.

Not as pretty as IntelliJ, but it’s better than nothing. The colours can be customised, so this could be made less jarring on the eyes.

Code formatting – Prettier

Looking for auto format to a standard format that is widely accepted? Prettier is the way forward for many reasons. Install the above followed by a couple of config changes and your code will be beautiful.

Go to your settings, filter by ‘save’ then update to settings shown here.
“Format on Save” – True
“Auto Save” – onFocusChange

Intellisense

Lastly, this is a bundle of other extensions that enable things like autocomplete of filenames, autocomplete of imports. This type of hints and flow should be automatic and is there from the outset in IntelliJ. So getting the same here is a must.

Close enough…

So now that I’ve installed all of these extensions I’m really happy with VS Code. Sure it’s not as good as IntelliJ – but VS Code is FREE.
So if you want to mess around at home for some personal projects, this is brilliant.

Why all the changes in my Package-lock file?

Why all the changes in my Package-lock file?

So I’ve checked out a JS project. I’ve run npm install, this should create no changes. Yet I’m now seeing my package-lock.json file appear in the version control changed files list.

So what’s changed? It’s mainly added loads of caret’s (^) to the versions of required software packages!

So what?

Well, you may have removed all the ^ from the package file so that your node modules remained the same, and you wish to guarantee each build will be the same. Adding a new package to your dependencies should not change large sections of the lock file. Having some semblance of oversight into the changes going on in the lock file may be useful when committing. But if 90% of it changes, and those changes are pretty much the addition of ^ caret’s or changes to the patch versions then it’s really hard to see what’s actually changed.

Bottom Line

Straight to the point, what’s going on? It’s your node/npm version! Specifically difference between version 5 and 6 (npm). This can happen if you are running with node 10 (most contain npm 6+), and others are running with node 8 (contains various npm 5 versions).
So if your project started with npm 5, then someone else does an install with npm 6, then you will see the large volume of changes.

Check out what version of npm is contained in each node version here

More depth

I had trouble finding this information online, hence this blog post to hopefully aid someone else. Here are some of the source links where I found information.

https://github.com/npm/npm/issues/20891 – Essentially the question I was looking for.
https://github.com/npm/npm/issues/20434#issuecomment-402988364 – Answer on why.

Should this information disappear I’ve grabbed a screenshot as well.

React Finland – post conference breakdown

React Finland – post conference breakdown

Time flies on, can’t believe its a month already since I attended the React Finland conference for the second time. Yes a second time, I took a fair amount away from the first one, so when I had the chance to go back again I definitely took that chance.

So why?

Friendly

Programmers and techy folk aren’t exactly the most chatty people, so when you are traveling on your own you’re always wondering how it will go. Will it be a case of turn up, enjoy the various talks then head back to your hotel after speaking with no one?

Nope, not here, at least not from my experience. Of course you need to be willing to speak to people, but the set up was great. Breaks long enough for people to grab a wee snack/drink and also visit the sponsors lounge area to chill.

I’ve been to enough conferences to know this isn’t easy to pull off. For example the ones in say London – complete opposite!

Sponsors chill out area
Sponsors chill out area – look at everyone talking! 😛 (They did actually)

Evening events

So you’ve a super friendly crowd and now they organise evening events.  For example after the workshop day a sizeable number of people headed over to one of the sponsors offices – Reaktor. I met with some great people and discussed lots of ideas, work and non-work topics. Had some friendly banter, food, drink and of course the obligatory Finnish sauna. Top hosting by Reaktor, again this was the same experience I had the previous year as well when I visited the Fraktio offices.

Reakor office chill out area

After day one of the conference, there was a comedy night. Yip comedy, in the same hall as the talks – and you know what it was actually rather good 😊 

Then you have the main after party event on the evening that the conference finished. Nothing too fancy, hall, food, music, drink.  Time to wind down, relax and cement some of the friendships that were made over the previous days.  Of course all these events just make the whole experience very enjoyable. Learning, sharing, and enjoying yourself at the same time.

BONUS

Due to the time it takes to get from Scotland to Finland I turned up a day early, no way I could have turned up on the Wed morning. Couple of weeks before (yes could have been arranged earlier but this wasn’t really part of the official conf) got the announcement that there was going to a pre-conference meet up! Great. It was held in one of the local companies offices, and maybe because it was unexpected, I thoroughly enjoyed it and it contained the talk that matched my company/team/project layout the most which made it the most appropriate. Getting into the mood of learning from others experiences. Only two talks, but both very good, especially the one from Smartly. Think it shows what the overall scene in Helsinki (Finland) is like. Very professional and well set up.

Bonus 2!

The organiser (Juho) had set up a slack channel for those wanting to meet up outside of the conference, to see a bit more of Helsinki if they wished. So on Sat after most people had left and flown home myself and Juho took a stroll around one of Helsinki’s nature reserves. Beautiful, weather really played its part and if anything was a tad hot for my liking – yes really. To hot in Helsinki! Never thought to bring shorts with me.  If you wish to see what it’s like I’ve got an album of just the walk – https://flic.kr/s/aHskQQsHuk. We must have walked 26-28km during the course of the day.

Squirrel

But what about the conference???

Sure, so I enjoyed myself, but that’s not the point of going to the React conference.  Well the conference didn’t disappoint either. The schedule for the two days were split into themes, so that you got back to back talks on say architecture, accessibility, styling, testing etc. Of course not everything will please everyone, so should you have had zero interest in styling/css then you headed out, had a shoulder massage, played some games in the sponsors lounge and had a chat with the sponsors or other attendees. Then you could find out about things like the micro satellite that they (think it was Reaktor) fired into orbit to photograph the forests! 
Think other than one talk, I stayed in and listened to every one of them and I’m glad I did.

Top talks for me –

Now for the ones I’ve not listed, doesn’t mean I didn’t like or didn’t take anything from them. Most were very good, only a couple I wasn’t keen on.  The above were the ones where I took something from and then able to use in my day to day role.

Was anything not so good?

Yes, unfortunately there was.  The workshop I attended wasn’t what I thought it was going to be and it was a super rushed course that finished approx. 1 ½ hours earlier than it was meant to. There was perhaps a reason for this in that the original trainer had to pull out, but the description of the course didn’t quite fit in with my expectation. https://react-finland.fi/workshops/#advanced-performance-tuning-for-react-applications  I was hoping for some performance tuning around the running of the application. Spotting common issues, what’s making items re-render needlessly, what takes up the most processing time, bad and good practice when dispatching events, that sort of thing.  The actual course was around start up time and getting the existing starter app down from say 4MB to a handful of KB’s.  For me, that’s not so much of an issue. Working only with internal customers I’ve never yet heard anyone ask for something to be smaller or faster at loading.  Sure we shouldn’t bloat our apps, but I’m not creating web pages so no one really cares. It did cover lazy loading and Service Workers which was great as well as other topics that I could take away.

So not a bad course and I did learn from it, just not what I expected and definitely too rushed. Unless you were very quick at touch typing, so you could watch the trainers screen and type at the same I don’t think you’d have been able to keep up.

Will I be back?

Sure hope so! I hear that the plan is to have two days of workshops! Sounds good 🙂

React Finland :D

React Finland :D

2nd year at React Finland, almost underway but what a bonus I’ve had so far!
I will be tweeting (@_delp_) live from the event and all going well covering all the best bits – which hopefully will be quite a lot.

It’s almost underway, but even before the conference has started I’ve been to a meet up at Smartly.io where there was a great talk about on Micro front ends. Same thinking as mirco services, but for the front end – makes sense, yes!

Had a workshop day yesterday which quite literally flow past with NikkitaFTW Some great insights into cutting down payloads and start up times. Perhaps best piece of information came in chunk on Service workers.

Service workers are dangerous – yet powerful!


https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#injectmanifest_plugin_1

Reaktor

Yeahhhh, they host a great meet up.
Check out the food on offer. Chatting for many hours to dev’s from all over Finland, Canada, France and even Vietnam!

React Finland ReactJS

And of course it wouldn’t be Finland without have a drink or two in the sauna. They love sauna here – and why not!!! The world needs more of them.

Clever Code

Clever Code

Getting into JS and come across code that many will consider ‘clever’ code. Is this code that is unreadable or is it the features that the language provides? I’m not really going to get into that discussion here – this post will hopefully instead help show and explain what is going on with such code. So should you see it then you’ll be able to understand what is going on and maybe even use it yourself.

const selective = [
    { id: "firstObjectId", ...obj1 },
    { id: "secondObjectId", ...obj2 },
    ...(obj3 ? [{ id: "thirdObjectId", ...obj3 }] : [])
  ];

What’s the aim of this code?

The aim of the above is to inject an ID into every object and at the same time it will only return two items if obj3 does not exist, and 3 if it does.

Why?

You may wish to combine a series of requests and sometimes you expect one of the requests to come back with nothing. If it does then there will be no need to return the 3rd element as an empty object – just drop it.

Explanation

Part 1 – What is { id: “firstObjectId”, …obj1 } doing? It’s taking the values from obj1, spreading them into another object while at the same time including an ID value. So it’s a new object with an ID as well as everything that was inside obj1 to start with.

What about …(obj3 ? [{ id: “thirdObjectId”, …obj3 }] : [])
Well if obj3 exists then it’s the same as the previous lines.
If it doesn’t exist then the line of code is

const selective = […([])]
which is

[…[]]

As the array is empty the spread operator will take nothing out of an empty array which leaves an empty array!
So we combine that with with the other spread objects and we now have a neat means of checking if an object exists and only if it does then include it in a returned item.

Old School

If this were in old school code it would look something like this

const returned = [
{ id: "firstObjectId", ...obj1 },
{ id: "secondObjectId", ...obj2 },
];
if (obj3) {
returned.push({ id: "thirdObjectId", ...obj3 });
}

So you are including an ‘if’ and then pushing the item into the array. Not quite as elegant!