Tag: Developer

Why you should hire a front-end developer

Matt Hobbs says you should hire a front-end developer because…

  • “A front-end developer is the best person to champion accessibility best practices in product teams.”
  • “80-90% of the end-user response time is spent on the front end.”
  • “A front-end developer takes pressure off interaction designers.”
  • “If you do not have a front-end developer there is a high risk that the good work the rest of the team does will not be presented to users in the best way.”

Direct Link to ArticlePermalink


The post Why you should hire a front-end developer appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,

WordPress Contributors Seek Sponsorship for Improving Gutenberg Developer Docs

A couple of WordPress contributors are currently looking for folks to sponsor them to work on the documentation for the WordPress block editor (often referred to as “Gutenberg”) and this is your chance to support them.

If you’ve developed blocks for the WordPress block editor — or at least have tried to — then you have likely struggled to find any meaningful documentation. Heck, just look at two recent posts here at CSS-Tricks where Dmitry Mayorov explains block variations and Leonardo Losoviz adds a welcome guide to the block editor. They both lament the lack of documentation and describe how they had to work around it. Chris has even experimented with different build approaches, from create-gluten-block to wp-cli to ACF Blocks. It’s sortuva Wild West out there and documented standards with examples would be a huge win, both for WordPress and for developers.

Now, I don’t think it’s worth getting into a debate into why the documentation doesn’t already exist a year since the block editor was released. There are lots of reasons for that and none of them help move things forward.

We flipped the switch to enable the WordPress block editor here at CSS-Tricks earlier this year and haven’t looked back. Where several of us on the team would write drafts in Dropbox Paper, Google Docs, or even a code editor, I think we’ve all started writing directly in WordPress because, well, it’s just so gosh-darned nice. I know I’m looking forward to contributing whatever I can to help this make this tool more accessible to developers — that’s the best way to spark new ideas and innovations for the future of blocks.

Direct Link to ArticlePermalink

The post WordPress Contributors Seek Sponsorship for Improving Gutenberg Developer Docs appeared first on CSS-Tricks.

CSS-Tricks

, , , , , , ,
[Top]

What is Developer Experience (DX)?

Developer Experience¹ is a term² that has one somewhat obvious meaning — the experience of developers — but it eludes definition in the sense that people invoke it at different times for different reasons referring to different things. For instance, our own Sarah Drasner’s current job title is “VP of Developer Experience” at Netlify. But a job title just one way the term is used. Let’s dig in a bit and apply it to the different ways people think about and use the term.

People think of specific companies.

I hear DX and Stripe together a lot. That makes sense. Stripe is a company almost exclusively for developers. They are serious about providing a good experience for their customers (developers), hence “developer experience.” Just listen to Suz Hinton talk about “friction journals”, which is this idea of using a product (like Stripe) and noting down every single little WTF moment, confusion, and frustration so that improvements can be made:

Netlify is like Stripe in this way, as is Heroku, CodePen, and any number of companies where the entire customer base is developers. For companies like this, it’s almost like DX is what user experience (UX) is for any other company.

People think of specific technologies.

It’s common to hear developer experience invoked when comparing technologies. For instance, some people will say that Vue offers a better developer experience than React. (I’m not trying to start anything, I don’t even have much of an opinion on this.) They are talking about things like APIs. Perhaps the state is more intuitive to manage in one vs. the other. Or they are talking about features. I know Vue and Svelte have animation helpers built-in while React does not. But React has hooks and people generally like those. These are aspects of the DX of these technologies.

Or they might be speaking about the feeling around the tools surrounding the core technology. I know create-react-app is widely beloved, but so is the Vue CLI. React Router is hugely popular, but Vue has a router that is blessed (and maintained) by the core team which offers a certain feeling of trust.

> vue create hello-world

> npx create-react-app my-app

I’m not using JavaScript frameworks/libraries as just any random example. I hear people talk about developer experience as it relates to JavaScript more than anything else — which could just be due to the people who are in my circles, but it feels notable.

People think of the world around the technology.

Everybody thinks good docs are important. There is no such thing as a technology that is better than another but has much worse docs. The one with the better docs is better overall because it has better docs. That’s not the technology itself; that’s the world around it.

Have you ever seen a developer product with an API, and when you view the docs for the API while logged in, it uses API keys and data and settings from your own account to demonstrate? That’s extraordinary to me. That feels like DX to me.

Airtable docs showing me API usage with my own data.

“Make the right thing easy,” notes Jake Dohm.

That word, easy, feels highly related to DX. Technologies that make things easy are technologies with good DX. In usage as well as in understanding. How easily (and quickly) can I understand what your technology does and what I can do with it?

What the technology does is often only half of the story. The happy path might be great, but what happens when it breaks or errors? How is the error reporting and logging? I think of Apollo and GraphQL here in my own experience. It’s such a great technology, but the error reporting feels horrendous in that it’s very difficult to track down even stuff like typos triggering errors in development.

What is the debugging story like? Are there special tools for it? The same goes for testing. These things are fundamental DX issues.

People think of technology offerings.

For instance, a technology might be “good” already. Say it has an API that developers like. Then it starts offering a CLI. That’s (generally) a DX improvement, because it opens up doors for developers who prefer working in that world and who build processes around it.

I think of things like Netlify Dev here. They already have this great platform and then say, here, you can run it all on your own machine too. That’s taking DX seriously.

One aspect of Netlify Dev that is nice: The terminal command to start my local dev environment across all my sites on Netlify, regardless of what technology powers them, is the same: netlify dev

Having a dedicated CLI is almost always a good DX step, assuming it is well done and maintained. I remember WordPress before WP-CLI, and now lots of documentation just assumes you’re using it. I wasn’t even aware Cloudinary had a CLI until the other day when I needed it and was pleasantly surprised that it was there. I remember when npm scripts started taking over the world. (What would npm be without a CLI?) We used to have a variety of different task runners, but now it’s largely assumed a project has run commands built into the package.json that you use to do anything the project needs to do.

Melanie Sumner thinks of CLIs immediately as core DX.

People think of the literal experience of coding.

There is nothing more directly DX than the experience of typing code into code editing software and running it. That’s what “coding” is and that’s what developers do. It’s no wonder that developers take that experience seriously and are constantly trying to improve it for themselves and their teams. I think of things like VS Code in how it’s essentially the DX of it that has made it so dominant in the code editing space in such a short time. VS Code does all kinds of things that developers like, does them well, does them fast, and allows for a very wide degree of customization.

TypeScript keeps growing in popularity no doubt in part due to the experience it offers within VS Code. TypeScript literally helps you code better by showing you, for example, what functions need as parameters, and making it hard to do the wrong thing.

Then there is the experience outside the editor, which in the browser itself. Years ago, I wrote Style Injection is for Winners where my point was, as a CSS developer, the experience of saving CSS code and seeing the changes instantly in the browser is a DX you definitely want to have. That concept continues to live on, growing up to JavaScript as well, where “hot reloading” is goosebump-worthy.

The difference between a poor developer environment (no IDE help, slow saves, manual refreshes, slow pipelines) and a great developer environment (fancy editor assistance, hot reloading, fast everything) is startling. It essentially makes you a better and more productive programmer.

People compare it to user experience (UX).

There is a strong negative connotation to DX sometimes. It happens when people blame it for it existing at the cost of user experience.

I think of things like client-side developer-only libraries. Think of the classic library that everyone loves to dunk: Moment.js. Moment allows you to manipulate dates in JavaScript, and is often used client-side to do that. Users don’t care if you have a fancy API available to manipulate dates because that is entirely a developer convenience. So, you ship this library for yourself (good DX) at the cost of slowing down the website (bad UX). Most client-side JavaScript is in this category.

Equally as often, people connect developer experience and user experience. If developers are empowered and effective, that will “trickle down” to produce good software, the theory goes.

Worst case, we’re in a situation where UX and DX are on a teeter totter. Pile on some DX and UX suffers on the other side. Best case, we find ways to disentangle DX and UX entirely, finding value in both and taking both seriously. Although if one has to win, certainly it should be the users. Like the HTML spec says:

In case of conflict, consider users over authors over implementors over specifiers over theoretical purity.

People think about time.

How long does a technology take to adopt? Good DX considers this. Can I take advantage of it without rewriting everything? How quickly can I spin it up? How well does it play with other technologies I use? What is my time investment?

This kind of thing makes me think of some recent experience with Cloudflare Workers. It’s really cool technology that we don’t have time to get all into right here, but suffice to say it gives you control over a website at a high level that we often don’t think about. Like what if you could manipulate a network request before it even gets to your web server? You don’t have to use it, but because of the level it operates on, new doors open up without caring about or interfering with whatever technologies you are using.

Not only does the technology itself position itself well, the DX of using it, while there are some rough edges, is at least well-considered, providing a browser-based testing environment.

A powerful tool with a high investment cost, eh, that’s cool. But a powerful tool with low investment cost is good DX.

People don’t want to think about it.

They say the best typography goes unnoticed because all you see is the actual thing it’s telling you. That can be true of developer experience. The best DX is that you never notice the tools because they just work.

Good DX is just being able to do your job rather than fight with tools. The tools could be your developer environment, it could be build tooling, it could be hosting stuff, or it could even be whatever APIs you are interfacing with. Is the API intuitive and helpful, or obtuse and tricky?


Feel free to keep going on this in the comments. What is DX to you?

  1. Are we capitalizing Developer Experience? I’m just gonna go for it.
  2. Looks like Michael Mahemoff has a decent claim on coining the term.

The post What is Developer Experience (DX)? appeared first on CSS-Tricks.

CSS-Tricks

,
[Top]

Comparing Social Media Outlets for Developer Tips

As a little experiment, I shared a development tip on three different social networks. I also tried to post it in a format that was most suitable for that particular social network:

How did each of them “do”? Let’s take a look. But bear in mind… this ain’t scientific. This is just me having a glance at one isolated example to get a feel for things across different social media sites.

The Twitter Thread

The Tweet

Twitter is probably our largest social media outlet. Despite the fact that I’ve done absolutely nothing with it this year other than auto-tweeting posts from this site (via our Jetpack Integration), those tweets do just about as well as it ever did when I was writing each tweet. These numbers are bound to change, but at the time of writing:

Views

102,501

Followers

~446,000

Retweets

108

Engagements

3,753

Likes

428 (first tweet)

Tweet Analytics showing 102,501 Impressions, 3,753 engagements and a few other more fine-grained stats.
Twitter provides analytics on tweets

Going off that engagements number, a little bit less than 1% of the followers had anything to do with it. I’d say this was a very average tweet for us, if not on the low side.

The Instagram Post

The Post

Instagram is by far the smallest of our social media outlets, being newer and not something I stay particularly active or consistent on. No auto-posting there just yet.

Followers

~2,800

Likes

308

Reached

2,685

Instagram provides analytics (“insights”) on posts.

Using Reach, that’s 96% of the followers. That’s pretty incredible compared t 1% of followers on Twitter. Although, on Twitter. I can easily put URLs to tweets and send people places, where my only options on Instagram are “check out the link in my profile” or use a swipe-up thing in an Instagram Story. So, despite the high engagement of Instagram, I’m mostly just getting the satisfaction of teaching something as well as a little brand awareness. It’s much harder for me to get you to directly do something from Instagram.

The YouTube Video

The Video

YouTube is in the middle for us, much bigger than Instagram but not as big as Twitter. YouTube is a little unique in that there can be (and are) advertising directly on the videos and that get’s a “revenue share” from YouTube. That’s very much not driving motivation for using YouTube (I make 50 cents a day, but it is unique compared to the others.

Subscribers

51,300

Likes

116

Views

2,455

YouTube analytics page showing 2.4K views, 192.8 hours of watch time, and a chart showing a graph that this video has more views than typical over time.
YouTube provides video analytics

Facebook?

We do have a Facebook page but it’s the most neglected of all of them. We auto-post new articles to it, but this experiment didn’t really have a blog post. I published the video to our site, but that doesn’t get auto-posted to Facebook, so the tip never made it there.

I used to feel a little guilty about not taking as much advantage of Facebook as I could, but whenever I look at overall analytics, I’m reminded that all of social media accounts combine for ~2% of traffic to this site. Spending any more time on this stuff is foolish for me, when that time could be spent on content for this site and information architecture for what we already have. And for Facebook specifically, whatever time we have spent there has never seemed to pan out. Just not a hive for developers.

CodePen?

I probably should have factored CodePen into this more, since it’s something of a social network itself with similar metrics. I worked on the examples in CodePen and the whole video was done in CodePen. But in this case, it was more about the journey than the destination. I did ultimately link to a demo at the end of the Twitter thread, but Instagram can’t link to it and I wasn’t as compelled to link to it on YouTube as the video itself to me was the important information.

If I was trying to compare CodePen stats here, I would have created the Pen in a step-by-step educational format so I could deliver the same idea. That actually sounds fun and I should probably still do that!

Winner?

Eh.

The problem is that there isn’t anything particularly useful to measure. What would have been way more interesting is if I had some really important call to action in each one where I’m like trying to sell you something or get you to sign up for something or whatever. I feel like that’s the real world of developer marketing. You gotta do 100 things for someone for free if you want them to do something for you on that 101st time. And on the 101st time, you should probably measure it somehow to see if the effort is worth it.

Here’s the very basic data together though…

Followers Engagements %
Twitter ~446,000 3,753 0.08%
Instagram ~2,800 2,685 96%
YouTube ~51,300 2,455 5%

One interesting thing is that I find the effort was about equal for all of them. You’d think a video would be hardest, but at least that’s just hit-record-hit-stop and minor editing. The other formats take longer to craft with custom text and graphics.

These would be my takeaways from this limited experiment:

  • You need big numbers on Twitter to do much. That’s because the engagement is pretty low. Still, it’s probably our best outlet for getting people to click a link and do something.
  • Instagram has amazing engagement, but it’s hard to send anyone anywhere. It’s still no wonder why people use it. You really do reach your audience there. If you had a strong call to action, I bet you could still get people do to it even with the absence of links (since people know how to search for stuff on the web).
  • While I mentioned that for this example the effort level was fairly even, in general, YouTube is going to require much higher effort. Video production just isn’t the same as farting out a couple of words or a screenshot. With that, and knowing that you’d need absolutely massive numbers to earn anything directly from YouTube, it’s pretty similar to other social networks in that you need to derive value from it abstractly.
  • This was not an idea that “went viral” in any sense. This is just standard-grade engagement, which was good for this experiment. I’m always super surprised at the type of developer tips that go viral. It’s always something I don’t expect, and often something I’m like awwwww we have an article about that too! I’d never bet on or expect anything going viral. Making stuff that your normal audience likes is the ticket.
  • Being active is pretty important. Any chart I’ve seen has big peaks when posts go out regularly and valleys when they don’t. Post regularly = riding the peaks.
  • None of this compares anywhere close to the real jewel of making things: blogging. Blogging is where you have full control and full benefit. The most important thing social media can do is get people over to your own site.

The post Comparing Social Media Outlets for Developer Tips appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]

“The title ‘Front-End Developer’ is obsolete.”

That title is from the opening tweet of a thread from Benjamin De Cock. I wouldn’t go that far, myself. What I like about the term is that ‘Front-End’ literally means the browser, and while the job has been changing quite a lot — and is perhaps fracturing before our eyes — the fact that the job is about doing browser work is still true. We’re browser people. This was a point I tried to make in my “Ooooops I guess we’re full-stack developers now” talk.

I really like Benjamin’s sentiment though. There is a scourge of implementations of things on the web that are both heavier and worse because they re-implement something that the browser offers better and “for free.” Think sliders: scrolling behavior, snap points, fixed/sticky positioning, form controls, animation, etc.

Our industry seems to have acknowledged that backend and frontend developers require very different skills (even though they often use the exact same language), and yet it’s struggling to see there’s too much bundled into the term “front-end developer”.

That’s the tricky part. That’s at the heart of The Great Divide. There’s an awful lot of front-end developers where their job solely focuses on JavaScript. You could call them “JavaScript Engineers” or “JavaScript Developers,” and that feels OK. However, I’m not sure what you call someone who’s a great front-end developer, not particularly focused on JavaScript, but is on other aspects of the front end.

The modern frontend developer is most often than not a “Jack of all trades” mastering JS (or even just a framework) and barely tolerating HTML/CSS as a necessary evil. That’s understandable. I strongly think it’s a different specialization, and it’s too much for a single person.

Yep, it’s OK! The divide isn’t a bad thing; it’s just a thing. Front-end teams need JavaScript specialists and CSS specialists and accessibility specialists and performance specialists and animation specialists and internationalization specialists and, and, and, and. They don’t have to all be separate people. People can be good at multiple things. It’s just exceptionally rare that people are good at everything, even when scoped only to front-end skills.

The post “The title ‘Front-End Developer’ is obsolete.” appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

What it means to be a front-end developer in 2020 (and beyond)

I wrote a piece for Layout, the blog of my hosting sponsor Flywheel.

Stick around in this field for a while, and you’ll see these libraries, languages, build processes, and heck, even entire philosophies on how best to build websites come and go like a slow tide.​​

You might witness some old-timer waving their fist from time to time, yelling that we should learn from the mistakes of the past. You could also witness some particularly boisterous youth waving their fists just as high, pronouncing the past an irrelevant context and no longer a useful talking point.

​​They’re both right, probably. As long as nobody is being nasty, it’s all part of the flow.

I’ve spent this whole year thinking about how I think the term front-end developer is still pretty meaningful, despite the divide in focus. The widening of the role just brings about more opportunity.

Direct Link to ArticlePermalink

The post What it means to be a front-end developer in 2020 (and beyond) appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

How I’ve Improved as a Web Developer (and a Person) in 2019

We’re sliding into the roaring twenties of the twenty-first century (cue Jazz music 🎷). It’s important that you and I, as responsible people, follow the tradition of looking back on the past year and reflect on the things that went right and wrong in the hopes of becoming the best version of ourselves in the year ahead.

I never do New Year’s resolutions, except for when I was ten years old and wanted to open a local self-run detective agency by the end of the following year (Scooby Doo was in vogue those days.) But I do reflect on the past this time of year, perhaps as an instinctive response.

Over the years, I’ve improved as a web developer, on my own terms and on my own pace, while learning, unlearning, interpreting and executing what the web technology offers. This post is a reflection of my personal experiences from 2019 and the years before that. I’ll share things I’ve learned that might make us all better web developers heading into 2020. Personal experiences aren’t universal, of course, but it’s sometimes neat to get a look into the things other people are processing and learn vicariously through them.

So here we go.

I spent a lot of time in other people’s code

It was unavoidable because my very first professional project involved updating and upgrading an old application. It was only after some time that I realized I gained wisdom from navigating through code written by others, and also, I developed the guts to voluntarily read others’ code and really pay attention to what it’s doing.

It’s not unlike practicing good listening skills. Reading and understanding code written by someone else requires active attention and fighting the temptation to either zone out or inject your own opinion.

What you can try: GitHub is a great place to see a lot of projects. There are so many open source projects out there and they’re all readily available to look at and digest. I think many of us have experienced times when we simply grab a project or a tool without really getting under the hood and understanding what it’s actually doing or how it fits into our own work. Taking the time up front is an excellent way to not only learn new things, but to make better decisions in our day-to-day work as well. Don’t understand something? Open an issue in the repo and ask away!

I’d be remiss not to mention CodePen here. Not only can you search for just about any pattern, feature, or function, but it also offers collections of Pens and even topics, both of which are excellent for seeing how different people tackle similar ideas.

I tried new web standards even if I thought I’d never use them

It’s just my curiosity, but I think it has made me feel more comfortable in learning something new. That might be variable fonts, serverless, JAMstack, prefers-color-scheme , prefers-reduced-motion , and subgrid, among many others. Geez, we’ve seen a lot of new things in the last year or two, haven’t we?

What you can try: I think you’re already ahead of this by following sites like CSS-Tricks. There are many technical blogs and writers out there who share with their readers what’s new. Check out the list of people who have contributed to this blog — many of them have personal sites where they’re frequently sharing new things. A Book Apart is also a great resource for standards, especially for those of you who might enjoy a break from the screen. You can find so many gems there, from Expressive Web Design to The New CSS Layout.

I created an archive of my favorite code snippets

There were times when I’d think that I’d remember the oh-so-simple syntax of new code I tried… but it turns out simple things are easier to forget. So I decided to keep them neatly in a digital folder, like in the good ol’ times. This has allowed me to go back and reference code when questions or ideas pop up. Otherwise, I’d have to go back and research all over again.

What you can try: I personally don’t use tools, just save them in a file. That said, Gist is always a nice place to keep snippets. And, hey, CodePen lets you create your own collections as well!

Another idea is to leverage your browser’s bookmarks. Save links liberally. Organize them into logical groupings so they’re easy to find later.

I created an archive of my notes, flow diagrams, and other stuff I scribble on paper

I have a standard paper notepad at my office that I use to jot down everything from ideas for a project I’m working on, layout sketches and notes from things I read. It’s also the place where I often start work, much like the way Chris writes “pseudo code” heading into a code editor.

I have a habit of working out the visual aspects of a web application, and often, even the source code on paper. So, I keep those papers safe for when I might have to refer back. It has helped me out in a pinch.

What you can try: I would be a hypocrite if I recommend any of the online note taking tools, because I’ve never found them convenient, ironically. There are lots of physical notebook options out there. Moleskine is a popular one. Sarah Drasner recommended one when she wrote her own post on learning how to learn.

I recognized when someone’s teaching and I need to be a student

I used to have a bad habit: if someone’s explaining something about code that I might already be familiar with, I would process and interpret what they were saying based on my own personal experiences, way before I learned what they had to say first.

It could be a millennial thing or it could be an industry thing, but I’ve always found that people package everything as something that’s being shared, that somehow I’m sitting in a round table with them and we are dissecting things over a box of pizza. 🍕

I appreciate that people make their content inclusive because we’re all adults here. But it also has stopped me from genuinely learning what they were trying to teach. I skimmed through useful information, but never really cared about the context. On my worst days, I missed the point completely, all because my brain’s resources were divided trying to learn and analyze at the same time.

Active listening and learning has provided a bunch of benefits for me this past year. For example:

  • I hear what people are saying more clearly.
  • I retain what people share with me more easily.
  • It makes the people I’m interacting with feel at ease with me.
  • It opens my mind to new ideas and possibilities I may not have considered.

What you can try: When you want to learn from something, whether it’s an article, a tweet, a podcast episode, a documentation or something else, save it and use it. I learned to grow out of my bad habit this year and have found this to be my flow for learning and retaining from others:

  1. I learn something.
  2. I save it for later (in my archive!).
  3. I try it out when I have the time.
  4. I play around with it more and try improving on it, if needed.
  5. I eat my pizza.

I trusted my own judgement more

This might sound like the exact opposite of what I just said about active listening, but it’s more of a counter-balance to being overly reliant on others. Active listening doesn’t mean we can’t have our own opinions or even continue holding onto them. It simply means we hear and retain information that can inform our own opinions.

A good professional opinion could be such a blessing, but good or bad, the moment I found myself giving too much weight to other people’s opinions, like I’d read a blog post on someone’s development environment and think I have to do the same thing, or worse, that the way I do things is wrong, that’s a terrible feeling (hello Imposter Syndrome) and who needs more stress?

What you can try: Instead of automatically believing that anything you read is the golden standard, try putting up a little guard. In other words, instead of thinking, “This is how I should be doing it,” perhaps say, “Oh, so this is how this person does that.”

I started seeking others’ experiences that validates my own

I feel happy when I read or hear fellow web developers share their work experiences and find something that resonates with me on a personal level:

  • “I know! I couldn’t set it up the first time, too!”
  • “Yes, that framework made things slower for me, too!”
  • “No way! I tried to center a floating element, too!”

Seeing that I’m not the only one who makes mistakes or struggles in certain areas makes me feel okay for where my skills are at instead of seeing myself as an unskilled developer who’s prone to mistakes. Chris recently shared his thought process working with flexbox elements — that’s exactly the sort of thing I think we can all relate to.

What you can try: We all bear some responsibility here. Let’s make people feel good when asking questions, even if they seem obvious to us. Share your own mistakes and struggles. The web is a vast and constantly evolving space and we’re all starting from different places.

I made myself the only one who decides what to make on my off-work coding marathons

Like all of you, my learning curve involves coding during my non-working hours. It could be just a new code I’m trying out or a full on side-project.

Seeing others share their side projects inspires me… at least that’s what I want them to do. That hasn’t always been the case. They used to make me think I wasn’t doing enough. Not enough GitHub repos. Not enough open source contributions. Not enough self-imposed challenges. Not enough WordPress plugins. And, sorry Chris, not enough CodePen demos.

With experience, however, I’ve realized there’s only one human soul that can optimally select what I should be working on, based on my skills, my preferences, my necessities and my circadian rhythm – the ghost under my bed.

Once I understood that, every single awesome and crazy side project people share online truly inspires me — or at least makes me smile, which is even better.

What you can try: Be intentional with your personal time. Prioritize what you want to learn and decide the best way for you to learn it. This post by Jason Rodriguez outlines how he planned to level up his JavaScript skills. Chris shared a mountain of ideas for learning CSS. Sarah also has great tips on prioritizing your personal and professional time.

I stopped drinking coffee

This is not up for discussion, my dear reader. 😀

What you can try: Masala Chai.

I started prioritizing my health

Here’s a very silly story. I sprained my wrists thrice in a month. I think it was a voodoo spell. The point is: it was getting harder for me to work.

I was a bit embarrassed to tell people I couldn’t work because I was injured, so I continued like nothing happened. Each time, the sprain would eventually go away because of the ointment I applied at home, but would return soon enough because I wasn’t properly resting it. At one point, the pain spread to my arms and I’d to immediately take my hands away from the keyboard and rest them on my lap. It scared me.

The next day, I started wearing a wrist cast (well, two) and informed my colleagues and technical director that I needed to take it slow.

I know this story sounds like a very simple and obvious thing — and it was a very simple thing indeed. But I learned an important lesson: Health comes first.

Our job description doesn’t come with health warning stickers, but there are consequences in reality.

What you can try: Take care of your health first. Physical or mental, chronic or acute, mild or severe, internal or external, when your health problems go away, it improves the quality of your life, personally and professionally. If you’re lucky enough to have good health insurance, use it. Schedule an annual physical exam. Listen to your body when it says it’s hungry, thirsty, or simply needs a rest.

I know, easier said than done. But it’s important nonetheless and something worth striving for.

I’ve started sharing my knowledge with others

Not in a way you might assume. I know the consensus is that we learn when we teach but I haven’t personally experienced that. I don’t learn while I teach. Instead, what I’ve done is focus on how someone I’m teaching could or should learn a particular thing.

  • “Start with the basics.”
  • “Read the documentation.”
  • “Try the demo then proceed to so and so.”

These are some of the statements I found myself repeating to those I’ve mentored.

Those same sentences echo back to me when I’ve to learn something new. When I teach, I pay attention to how it’s learned. And learning is the one skill that never goes out of date, especially in our line of work.

What you can try: I think you’ll probably have to wait a while before you could do this if you’re just starting out as a web developer, but if you’re even somewhat experienced and meet a wide-eyed newbie, don’t miss your chance to teach. Don’t be part of the dark matter. You can teach in a variety of ways, from blogging to making demos. That said, I’ve found real life person-to-person teachable moments to be the most effective.

I realized I can’t read a code once and understand it all. So I use comments.

Here’s my comment about comments: Take them seriously.

Sometimes I can’t even decipher the code that I’ve typed with my two bare hands.

Condensation is a key element of programming languages in addition to something that causes rain. We don’t write, “add one more sheep to the herd.” Instead, we write, i++. Expecting myself to remember and understand everything in one glance simply isn’t practical.

Using well-thought comments cuts back the time it takes me to know what’s happening in the code. This is why I’ve consciously paid attention to using comments this past year. There’s no cost to using them, so go nuts!

What you can try: Take time to go through your code and leave some useful comments each time you’ve coded a module or a feature that works, especially before moving onto what’s next.

I’m not taking working code for granted

I was told margin:auto would center an element. I was told to add return(0) to an onclick event handler. I was also told to use GUID for foreign keys.

I didn’t ask why or how those things worked at the time. I simply did as they said.

I, now, however, know how they work and why I had to use those code.

When I know the basics of a piece of code, it helps me to use the same code or the same logic in scenarios other than the one I learned about it in.

What you can try: Make a quick mental, physical, or digital reminder when you come across a code that you want to know more about. Then remember to go through that list first in your free time. Don’t be afraid to ask someone why code is used a certain way.

I try to mimic extroverted web developers

* takes a deep breath *

I’m an introvert.

My introversion is not so bad that people feel uncomfortable around me. I mean, everybody likes talking to introverts because they mostly listen, right?

Although most of my work is typing in front of a computer I inevitably have to meet people, like clients, users and team members.

Communication is important. And not just the bare minimum.

When you develop a really good relationship with who you work with, your workplace becomes fun. When you develop a good relationship with your users, your work becomes successful; and when you develop a good relationship with your clients, you get more work.

I found there’s no way around it: I had to talk from time to time. I had to put myself out there.

I look at my fellow web developers who are more extroverted for communication pointers. They talk beyond about work. They give their suggestions. They encourage feedback. They drink coffee. And I try to practice that.

What you can try: If you’re an extrovert, I’ve got nothing for you. If you’re an introvert, all I can say is try. And keep trying. And that’s all you ever need to do. We can’t change our personalities, but with some practice and time we’ll learn to manage them better. In fact, it might be worth getting a better understanding of your personality type. Susan Cain’s book Quiet is an interesting (and dense) take on introversion.

I take breaks

I hate this to be true, but I turn into a Shaman soon after I start coding. An unwilling Shaman who gets possessed. The spirit that takes over me likes to only code. It doesn’t like to eat, sleep, talk to people or check Instagram. It’s a very mean spirit.

That’s why I exorcise it regularly to not cloister myself from the world. I pay attention to someone calling me. I leave the desk for tea breaks. I let my laptop’s battery die so I won’t go near it during vacation. I even have a hobby.

I don’t know if taking breaks has improved my performance or not, because I don’t think the mean spirit lacks in performance. I just think it’s good for me to not be always possessed.

What you can try: For those of you with 9-5 job, I would recommend tea breaks at 11AM and 4PM (wow, that came out very specific) And for when you work at home, I suppose you’ll have more things to do, so choose for yourself when you want the break. I like to watch TV, that would be like my ideal break time.


And… that’s it. That’s all the spookiness I could fit into this post. I shared as much of my experience as I could, as well as suggestions you might find helpful. Hope you take something good from it. This might be my final post of the year, so I don’t want to miss this chance to wish you LOTS of good luck as you go into 2020. 🍀

The post How I’ve Improved as a Web Developer (and a Person) in 2019 appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

Web Developer Search History

Sophie Koonin blogged “Everything I googled in a week as a professional software engineer,” which was a fascinating look into the mind of a web developer and what they need to look up during day-to-day work. We all joke that we just Google stuff (or StackOverflow stuff) we don’t know off the bat and copy and paste, but this is more to the heart of it.

A few just from one day:

react-apollo release notes
jest silence warnings – don’t judge me, ok?
semantic HTML contact details – wanted to check if the <address> tag was relevant here
dominos accessibility – popcorn.gif

Gift Egwuenu followed up with “The Art of Googling.”

A few:

  • Filter an Array with JavaScript – I was working on a chore and needed to see how the filter method works
  • Take a screenshot on Mac
  • Center a div with Grid
  • Undo a git commit
  • Grid with React Native – checking if this was a thing with React Native

Reading these, I alternate from “eeeeesh, good luck” to “I wish I could have been there because I could have probably helped.”

This is a fun little blogging trend I’d love to see more people do. (Reminds me of that “How we do CSS at [company]” thing.)

I’ll do my last few days, unearthed from Google’s My Activity area, filtered to search-only.

This was just a couple of hours yesterday morning, with some noise and distracting stuff removed:

  • Sara Vieira – Was looking for her Twitter to credit a tweet.
  • javascript closest – Was looking for the DOM version rather than the jQuery version
  • jquery parent – Confirming that was a real API it had
  • minimap moz element – Finding an article that was a great use case for the
  • element() function in CSS
  • web unleashed – Going to this conference later in the week and needed to look at the site
  • server log analytics
  • states in australia
  • view html source in spark mail
  • bat crypto
  • html validator
  • html unescape
  • should email html have title?
  • window.scrollto
  • useCallback
  • rails rss feed content type
  • content type for rss feeds
  • river city girls

You next! You next!

The post Web Developer Search History appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

New ES2018 Features Every JavaScript Developer Should Know

The ninth edition of the ECMAScript standard, officially known as ECMAScript 2018 (or ES2018 for short), was released in June 2018. Starting with ES2016, new versions of ECMAScript specifications are released yearly rather than every several years and add fewer features than major editions used to. The newest edition of the standard continues the yearly release cycle by adding four new RegExp features, rest/spread properties, asynchronous iteration, and Promise.prototype.finally. Additionally, ES2018 drops the syntax restriction of escape sequences from tagged templates.

These new changes are explained in the subsections that follow.

The Rest/Spread Properties

One of the most interesting features added to ES2015 was the spread operator. This operator makes copying and merging arrays a lot simpler. Rather than calling the concat() or slice() method, you could use the ... operator:

const arr1 = [10, 20, 30];  // make a copy of arr1 const copy = [...arr1];  console.log(copy);    // → [10, 20, 30]  const arr2 = [40, 50];  // merge arr2 with arr1 const merge = [...arr1, ...arr2];  console.log(merge);    // → [10, 20, 30, 40, 50]

The spread operator also comes in handy in situations where an array must be passed in as separate arguments to a function. For example:

const arr = [10, 20, 30]  // equivalent to // console.log(Math.max(10, 20, 30)); console.log(Math.max(...arr));    // → 30

ES2018 further expands this syntax by adding spread properties to object literals. With the spread properties you can copy own enumerable properties of an object onto a new object. Consider the following example:

const obj1 = {   a: 10,   b: 20 };  const obj2 = {   ...obj1,   c: 30 };  console.log(obj2);    // → {a: 10, b: 20, c: 30}

In this code, the ... operator is used to retrieve the properties of obj1 and assign them to obj2. Prior to ES2018, attempting to do so would throw an error. If there are multiple properties with the same name, the property that comes last will be used:

const obj1 = {   a: 10,   b: 20 };  const obj2 = {   ...obj1,   a: 30 };  console.log(obj2);    // → {a: 30, b: 20}

Spread properties also provide a new way to merge two or more objects, which can be used as an alternative to the Object.assign() method:

const obj1 = {a: 10}; const obj2 = {b: 20}; const obj3 = {c: 30};  // ES2018 console.log({...obj1, ...obj2, ...obj3});    // → {a: 10, b: 20, c: 30}  // ES2015 console.log(Object.assign({}, obj1, obj2, obj3));    // → {a: 10, b: 20, c: 30}

Note, however, that spread properties do not always produce the same result as Object.assign(). Consider the following code:

Object.defineProperty(Object.prototype, 'a', {   set(value) {     console.log('set called!');   } });  const obj = {a: 10};  console.log({...obj});     // → {a: 10}  console.log(Object.assign({}, obj));     // → set called! // → {}

In this code, the Object.assign() method executes the inherited setter property. Conversely, the spread properties simply ignore the setter.

It’s important to remember that spread properties only copy enumerable properties. In the following example, the type property won’t show up in the copied object because its enumerable attribute is set to false:

const car = {   color: 'blue' };  Object.defineProperty(car, 'type', {   value: 'coupe',   enumerable: false });  console.log({...car});    // → {color: "blue"}

Inherited properties are ignored even if they are enumerable:

const car = {   color: 'blue' };  const car2 = Object.create(car, {   type: {     value: 'coupe',     enumerable: true,   } });  console.log(car2.color);                      // → blue console.log(car2.hasOwnProperty('color'));    // → false  console.log(car2.type);                       // → coupe console.log(car2.hasOwnProperty('type'));     // → true  console.log({...car2});                       // → {type: "coupe"}

In this code, car2 inherits the color property from car. Because spread properties only copy the own properties of an object, color is not included in the return value.

Keep in mind that spread properties can only make a shallow copy of an object. If a property holds an object, only the reference to the object will be copied:

const obj = {x: {y: 10}}; const copy1 = {...obj};     const copy2 = {...obj};   console.log(copy1.x === copy2.x);    // → true

The x property in copy1 refers to the same object in memory that x in copy2 refers to, so the strict equality operator returns true.

Another useful feature added to ES2015 was rest parameters, which enabled JavaScript programmers to use ... to represent values as an array. For example:

const arr = [10, 20, 30]; const [x, ...rest] = arr;  console.log(x);       // → 10 console.log(rest);    // → [20, 30]

Here, the first item in arr is assigned to x, and remaining elements are assigned to the rest variable. This pattern, called array destructuring, became so popular that the Ecma Technical Committee decided to bring a similar functionality to objects:

const obj = {   a: 10,   b: 20,   c: 30 };  const {a, ...rest} = obj;  console.log(a);       // → 10 console.log(rest);    // → {b: 20, c: 30}

This code uses the rest properties in a destructuring assignment to copy the remaining own enumerable properties into a new object. Note that rest properties must always appear at the end of the object, otherwise an error is thrown:

const obj = {   a: 10,   b: 20,   c: 30 };  const {...rest, a} = obj;    // → SyntaxError: Rest element must be last element

Also keep in mind that using multiple rest syntaxes in an object causes an error, unless they are nested:

const obj = {   a: 10,   b: {     x: 20,     y: 30,     z: 40   } };  const {b: {x, ...rest1}, ...rest2} = obj;    // no error  const {...rest, ...rest2} = obj;    // → SyntaxError: Rest element must be last element

Support for Rest/Spread Properties

Chrome Firefox Safari Edge
60 55 11.1 No
Chrome Android Firefox Android iOS Safari Edge Mobile Samsung Internet Android Webview
60 55 11.3 No 8.2 60

Node.js:

  • 8.0.0 (requires the --harmony runtime flag)
  • 8.3.0 (full support)

Asynchronous Iteration

Iterating over a collection of data is an important part of programming. Prior to ES2015, JavaScript provided statements such as for, for...in, and while, and methods such as map(), filter(), and forEach() for this purpose. To enable programmers to process the elements in a collection one at a time, ES2015 introduced the iterator interface.

An object is iterable if it has a Symbol.iterator property. In ES2015, strings and collections objects such as Set, Map, and Array come with a Symbol.iterator property and thus are iterable. The following code gives an example of how to access the elements of an iterable one at a time:

const arr = [10, 20, 30]; const iterator = arr[Symbol.iterator]();    console.log(iterator.next());    // → {value: 10, done: false} console.log(iterator.next());    // → {value: 20, done: false} console.log(iterator.next());    // → {value: 30, done: false} console.log(iterator.next());    // → {value: undefined, done: true}

Symbol.iterator is a well-known symbol specifying a function that returns an iterator. The primary way to interact with an iterator is the next() method. This method returns an object with two properties: value and done. The value property contains the value of the next element in the collection. The done property contains either true or false denoting whether or not the end of the collection has reached.

By default, a plain object is not iterable, but it can become iterable if you define a Symbol.iterator property on it, as in this example:

const collection = {   a: 10,   b: 20,   c: 30,   [Symbol.iterator]() {     const values = Object.keys(this);     let i = 0;     return {       next: () => {         return {           value: this[values[i++]],           done: i > values.length         }       }     };   } };  const iterator = collection[Symbol.iterator]();    console.log(iterator.next());    // → {value: 10, done: false} console.log(iterator.next());    // → {value: 20, done: false} console.log(iterator.next());    // → {value: 30, done: false} console.log(iterator.next());    // → {value: undefined, done: true}

This object is iterable because it defines a Symbol.iterator property. The iterator uses the Object.keys() method to get an array of the object’s property names and then assigns it to the values constant. It also defines a counter variable and gives it an initial value of 0. When the iterator is executed it returns an object that contains a next() method. Each time the next() method is called, it returns a {value, done} pair, with value holding the next element in the collection and done holding a Boolean indicating if the iterator has reached the need of the collection.

While this code works perfectly, it’s unnecessarily complicated. Fortunately, using a generator function can considerably simplify the process:

const collection = {   a: 10,   b: 20,   c: 30,   [Symbol.iterator]: function * () {     for (let key in this) {       yield this[key];     }   } };  const iterator = collection[Symbol.iterator]();    console.log(iterator.next());    // → {value: 10, done: false} console.log(iterator.next());    // → {value: 20, done: false} console.log(iterator.next());    // → {value: 30, done: false} console.log(iterator.next());    // → {value: undefined, done: true}

Inside this generator, a for...in loop is used to enumerate over the collection and yield the value of each property. The result is exactly the same as the previous example, but it’s greatly shorter.

A downside of iterators is that they are not suitable for representing asynchronous data sources. ES2018’s solution to remedy that is asynchronous iterators and asynchronous iterables. An asynchronous iterator differs from a conventional iterator in that, instead of returning a plain object in the form of {value, done}, it returns a promise that fulfills to {value, done}. An asynchronous iterable defines a Symbol.asyncIterator method (instead of Symbol.iterator) that returns an asynchronous iterator.

An example should make this clearer:

const collection = {   a: 10,   b: 20,   c: 30,   [Symbol.asyncIterator]() {     const values = Object.keys(this);     let i = 0;     return {       next: () => {         return Promise.resolve({           value: this[values[i++]],            done: i > values.length         });       }     };   } };  const iterator = collection[Symbol.asyncIterator]();    console.log(iterator.next().then(result => {   console.log(result);    // → {value: 10, done: false} }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: 20, done: false}  }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: 30, done: false}  }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: undefined, done: true}  }));

Note that it’s not possible to use an iterator of promises to achieve the same result. Although a normal, synchronous iterator can asynchronously determine the values, it still needs to determine the state of “done” synchronously.

Again, you can simplify the process by using a generator function, as shown below:

const collection = {   a: 10,   b: 20,   c: 30,   [Symbol.asyncIterator]: async function * () {     for (let key in this) {       yield this[key];     }   } };  const iterator = collection[Symbol.asyncIterator]();    console.log(iterator.next().then(result => {   console.log(result);    // → {value: 10, done: false} }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: 20, done: false}  }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: 30, done: false}  }));  console.log(iterator.next().then(result => {   console.log(result);    // → {value: undefined, done: true}  }));

Normally, a generator function returns a generator object with a next() method. When next() is called it returns a {value, done} pair whose value property holds the yielded value. An async generator does the same thing except that it returns a promise that fulfills to {value, done}.

An easy way to iterate over an iterable object is to use the for...of statement, but for...of doesn’t work with async iterables as value and done are not determined synchronously. For this reason, ES2018 provides the for...await...of statement. Let’s look at an example:

const collection = {   a: 10,   b: 20,   c: 30,   [Symbol.asyncIterator]: async function * () {     for (let key in this) {       yield this[key];     }   } };  (async function () {   for await (const x of collection) {     console.log(x);   } })();  // logs: // → 10 // → 20 // → 30

In this code, the for...await...of statement implicitly calls the Symbol.asyncIterator method on the collection object to get an async iterator. Each time through the loop, the next() method of the iterator is called, which returns a promise. Once the promise is resolved, the value property of the resulting object is read to the x variable. The loop continues until the done property of the returned object has a value of true.

Keep in mind that the for...await...of statement is only valid within async generators and async functions. Violating this rule results in a SyntaxError.

The next() method may return a promise that rejects. To gracefully handle a rejected promise, you can wrap the for...await...of statement in a try...catch statement, like this:

const collection = {   [Symbol.asyncIterator]() {     return {       next: () => {         return Promise.reject(new Error('Something went wrong.'))       }     };   } };  (async function() {   try {     for await (const value of collection) {}   } catch (error) {     console.log('Caught: ' + error.message);   } })();  // logs: // → Caught: Something went wrong.

Support for Asynchronous Iterators

Chrome Firefox Safari Edge
63 57 12 No
Chrome Android Firefox Android iOS Safari Edge Mobile Samsung Internet Android Webview
63 57 12 No 8.2 63

Node.js:

  • 8.10.0 (requires the –harmony_async_iteration flag)
  • 10.0.0 (full support)

Promise.prototype.finally

Another exciting addition to ES2018 is the finally() method. Several JavaScript libraries had previously implemented a similar method, which proved useful in many situations. This encouraged the Ecma Technical Committee to officially add finally() to the specification. With this method, programmers will be able to execute a block of code regardless of the promise’s fate. Let’s look at a simple example:

fetch('https://www.google.com')   .then((response) => {     console.log(response.status);   })   .catch((error) => {      console.log(error);   })   .finally(() => {      document.querySelector('#spinner').style.display = 'none';   });

The finally() method comes in handy when you need to do some clean up after the operation has finished regardless of whether or not it succeeded. In this code, the finally() method simply hides the loading spinner after the data is fetched and processed. Instead of duplicating the final logic in the then() and catch() methods, the code registers a function to be executed once the promise is either fulfilled or rejected.

You could achieve the same result by using promise.then(func, func) rather than promise.finally(func), but you would have to repeat the same code in both fulfillment handler and rejection handler, or declare a variable for it:

fetch('https://www.google.com')   .then((response) => {     console.log(response.status);   })   .catch((error) => {      console.log(error);   })   .then(final, final);  function final() {   document.querySelector('#spinner').style.display = 'none'; }

As with then() and catch(), the finally() method always returns a promise, so you can chain more methods. Normally, you want to use finally() as the last chain, but in certain situations, such as when making a HTTP request, it’s a good practice to chain another catch() to deal with errors that may occur in finally().

Support for Promise.prototype.finally

Chrome Firefox Safari Edge
63 58 11.1 18
Chrome Android Firefox Android iOS Safari Edge Mobile Samsung Internet Android Webview
63 58 11.1 No 8.2 63

Node.js:

10.0.0 (full support)

New RegExp Features

ES2018 adds four new features to the RegExp object, which further improves JavaScript’s string processing capabilities. These features are as follows:

  • s (dotAll) flag
  • Named capture groups
  • Lookbehind assertions
  • Unicode property escapes

s (dotAll) Flag

The dot (.) is a special character in a regular expression pattern that matches any character except line break characters such as line feed (\n) or carriage return (\r). A workaround to match all characters including line breaks is to use a character class with two opposite shorthands such as [\d\D]. This character class tells the regular expression engine to find a character that’s either a digit (\d) or a non-digit (\D). As a result, it matches any character:

console.log(/one[\d\D]two/.test('one\ntwo'));    // → true

ES2018 introduces a mode in which the dot can be used to achieve the same result. This mode can be activated on per-regex basis by using the s flag:

console.log(/one.two/.test('one\ntwo'));     // → false console.log(/one.two/s.test('one\ntwo'));    // → true

The benefit of using a flag to opt in to the new behavior is backwards compatibility. So existing regular expression patterns that use the dot character are not affected.

Named Capture Groups

In some regular expression patterns, using a number to reference a capture group can be confusing. For example, take the regular expression /(\d{4})-(\d{2})-(\d{2})/ which matches a date. Because date notation in American English is different from British English, it’s hard to know which group refers to the day and which group refers to the month:

const re = /(\d{4})-(\d{2})-(\d{2})/; const match= re.exec('2019-01-10');  console.log(match[0]);    // → 2019-01-10 console.log(match[1]);    // → 2019 console.log(match[2]);    // → 01 console.log(match[3]);    // → 10

ES2018 introduces named capture groups which uses the (?<name>...) syntax. So, the pattern to match a date can be written in a less ambiguous manner:

const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const match = re.exec('2019-01-10');  console.log(match.groups);          // → {year: "2019", month: "01", day: "10"} console.log(match.groups.year);     // → 2019 console.log(match.groups.month);    // → 01 console.log(match.groups.day);      // → 10

You can recall a named capture group later in the pattern by using the \k<name> syntax. For example, to find consecutive duplicate words in a sentence, you can use /\b(?<dup>\w+)\s+\k<dup>\b/:

const re = /\b(?<dup>\w+)\s+\k<dup>\b/; const match = re.exec('Get that that cat off the table!');          console.log(match.index);    // → 4 console.log(match[0]);       // → that that

To insert a named capture group into the replacement string of the replace() method, you will need to use the $ <name> construct. For example:

const str = 'red & blue';  console.log(str.replace(/(red) & (blue)/, '$  2 & $  1'));     // → blue & red  console.log(str.replace(/(?<red>red) & (?<blue>blue)/, '$  <blue> & $  <red>'));     // → blue & red

Lookbehind Assertions

ES2018 brings lookbehind assertions to JavaScript, which have been available in other regex implementations for years. Previously, JavaScript only supported lookahead assertions. A lookbehind assertion is denoted by (?<=...), and enables you to match a pattern based on the substring that precedes the pattern. For example, if you want to match the price of a product in dollar, pound, or euro without capturing the currency symbol, you can use /(?<=$ |£|€)\d+(\.\d*)?/:

const re = /(?<=$  |£|€)\d+(\.\d*)?/;  console.log(re.exec('199'));      // → null  console.log(re.exec('$  199'));     // → ["199", undefined, index: 1, input: "$  199", groups: undefined]  console.log(re.exec('€50'));      // → ["50", undefined, index: 1, input: "€50", groups: undefined]

There is also a negative version of lookbehind, which is denoted by (?<!...). A negative lookbehind allows you to match a pattern only if it is not preceded by the pattern within the lookbehind. For example, the pattern /(?<!un)available/ matches the word available if it does not have a “un” prefix:

const re = /(?<!un)available/;  console.log(re.exec('We regret this service is currently unavailable'));     // → null  console.log(re.exec('The service is available'));              // → ["available", index: 15, input: "The service is available", groups: undefined]

Unicode Property Escapes

ES2018 provides a new type of escape sequence known as Unicode property escape, which provides support for full Unicode in regular expressions. Suppose you want to match the Unicode character ㉛ in a string. Although ㉛ is considered a number, you can’t match it with the \d shorthand character class because it only supports ASCII [0-9] characters. Unicode property escapes, on the other hand, can be used to match any decimal number in Unicode:

const str = '㉛';  console.log(/\d/u.test(str));    // → false console.log(/\p{Number}/u.test(str));     // → true

Similarly, if you want to match any Unicode word character, you can use \p{Alphabetic}:

const str = 'ض';  console.log(/\p{Alphabetic}/u.test(str));     // → true  // the \w shorthand cannot match ض   console.log(/\w/u.test(str));    // → false

There is also a negated version of \p{...}, which is denoted by \P{...}:

console.log(/\P{Number}/u.test('㉛'));    // → false console.log(/\P{Number}/u.test('ض'));    // → true  console.log(/\P{Alphabetic}/u.test('㉛'));    // → true console.log(/\P{Alphabetic}/u.test('ض'));    // → false

In addition to Alphabetic and Number, there are several more properties that can be used in Unicode property escapes. You can find a list of supported Unicode properties in the current specification proposal.

Support for New RegExp Features

Chrome Firefox Safari Edge
s (dotAll) Flag 62 No 11.1 No
Named Capture Groups 64 No 11.1 No
Lookbehind Assertions 62 No No No
Unicode Property Escapes 64 No 11.1 No
Chrome (Android) Firefox (Android) iOS Safari Edge Mobile Samsung Internet Android Webview
s (dotAll) Flag 62 No 11.3 No 8.2 62
Named Capture Groups 64 No 11.3 No No 64
Lookbehind Assertions 62 No No No 8.2 62
Unicode Property Escapes 64 No 11.3 No No 64

Node.js:

  • 8.3.0 (requires the –harmony runtime flag)
  • 8.10.0 (support for s (dotAll) flag and lookbehind assertions)
  • 10.0.0 (full support)

Template Literal Revision

When a template literal is immediately preceded by an expression, it is called a tagged template literal. A tagged template comes in handy when you want to parse a template literal with a function. Consider the following example:

function fn(string, substitute) {   if(substitute === 'ES6') {     substitute = 'ES2015'   }   return substitute + string[1]; }  const version = 'ES6'; const result = fn`$  {version} was a major update`;  console.log(result);    // → ES2015 was a major update

In this code, a tag expression — which is a regular function — is invoked and passed the template literal. The function simply modifies the dynamic part of the string and returns it.

Prior to ES2018, tagged template literals had syntactic restrictions related to escape sequences. A backslash followed by certain sequence of characters were treated as special characters: a \x interpreted as a hex escape, a \u interpreted as a unicode escape, and a \ followed by a digit interpreted as an octal escape. As a result, strings such as "C:\xxx\uuu" or "\ubuntu" were considered invalid escape sequences by the interpreter and would throw a SyntaxError.

ES2018 removes these restrictions from tagged templates and instead of throwing an error, represents invalid escape sequences as undefined:

function fn(string, substitute) {   console.log(substitute);    // → escape sequences:   console.log(string[1]);     // → undefined }  const str = 'escape sequences:'; const result = fn`$  {str} \ubuntu C:\xxx\uuu`;

Keep in mind that using illegal escape sequences in a regular template literal still causes an error:

const result = `\ubuntu`; // → SyntaxError: Invalid Unicode escape sequence

Support for Template Literal Revision

Chrome Firefox Safari Edge
62 56 11 No
Chrome Android Firefox Android iOS Safari Edge Mobile Samsung Internet Android Webview
62 56 11 No 8.2 62

Node.js:

  • 8.3.0 (requires the –harmony runtime flag)
  • 8.10.0 (full support)

Wrapping up

We’ve taken a good look at several key features introduced in ES2018 including asynchronous iteration, rest/spread properties, Promise.prototype.finally(), and additions to the RegExp object. Although some of these features are not fully implemented by some browser vendors yet, they can still be used today thanks to JavaScript transpilers such as Babel.

ECMAScript is rapidly evolving and new features are being introduced every so often, so check out the list of finished proposals for the full scope of what’s new. Are there any new features you’re particularly excited about? Share them in the comments!

The post New ES2018 Features Every JavaScript Developer Should Know appeared first on CSS-Tricks.

CSS-Tricks

, , , , , ,
[Top]

What makes someone a good front-end developer?

We recently covered this exact same thing, but from the perspective of a bunch of developers.

Chris Ferdinandi weighs in:

The least important skills for a front-end developer to have are technical ones.

The nuances of JavaScript. How to use a particular library, framework, or build tool. How the cascade in CSS works. Semantic HTML. Fizz-buzz.

Chris takes that a little farther than I would. I do think that with an understanding of HTML, CSS, and JavaScript, the deeper the better, and that it is an ingredient in making a good front-end developer. But I also agree it’s much more than that. In fact, with solid foundational skills and really good soft skills (e.g. you’re great at facilitating a brainstorming meeting), you could and should get a job before they even look at your language skills.

Direct Link to ArticlePermalink

The post What makes someone a good front-end developer? appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]