Blog

Advent of Gutenberg – 7

For me personally, one of the main improvements in Gutenberg, compared to the classic WordPress editor, is the speed at which you can create content. A lot of this is due to the keyboard efficiency. There are a lot of hidden keyboard tools that we will look at, and some tips on how to quickly get content going in Gutenberg. I am on a Windows PC, so the quick keys mentioned will be different for MacOSX users. My daughter tried out the mobile experience as well for her website and thought it was relatively easy to use as well. I am very excited about getting more youth involved in using WordPress, which will be covered in future posts.

Back to the topic at hand.

Keyboard efficiency

Microsoft Word was in many ways the killer app of early PC days. It was most likely the culprit leading to the end of the typewriter. The typewriter in many ways has never died, as many are still stuck using the QWERTY keyboard layout, designed around the mechanical functionality of the typewriter, not the ease of human typing. Alternatives of keyboard layout have received minimal adoption. The speed at which we type can have a great impact. Time is the most valuable resource. Although most of us may be tied to a slower keyboard layout, we are definitely tied to a slower method of expressing thought. Gutenberg is a step in the right direction towards a more responsive interface for quickly getting our thoughts onto a canvas.

When I first started using Gutenberg I used all of the visual graphical elements to insert content. Now I have dug a bit deeper into the keyboard shortcuts, and do almost all of my posts entirely via the keyboard. It is an incredibly fluid experience, that will only improve from here. One of the biggest speed increases is using the slash commands (/). When a new block line is inserted you can access a list of blocks to insert by pressing /, similar to Slack.

Typing in forward slash on a new line opens the slash command palette.
Type slash on a new block line to open the command palette.

Once you type in the slash you will see a list of the most recently used blocks tailored to your needs. The pop up window will not be a complete list of every command available, and you will need to find those out for yourself, generally the name of a block is also the name of a command to insert a block. As you type after the slash command you will get an autocomplete functionality of the potential block command you are trying to do. So typing /media will bring me to creating the media and text below.

Typing after the slash command drives an autocomplete functionality.

Typing a command will start to trigger an autocomplete. Very nifty.

When dealing with images and other layout elements I noticed it was sometimes tricky to create a new block, and relying on hitting the “Enter”/”Return” key was not always feasible. Luckily there is a keyboard shortcut to add a block either above or below the currently focused block. I typically add one after by using “Ctrl + Alt + Y”. To add a block before you can do “Ctrl + Alt + T”. Knowing these two commands coupled with the slash command has greatly increased the speed at which I can get my thoughts out. No more, cut/copy paste. Very fluid.

Another cool thing is duplication, by using “Ctrl + Shift + D”.

Another cool thing is duplication, by using “Ctrl + Shift + D”.

Keyboard shortcuts

You might be wondering where the shortcuts are found, and it was not super apparent to me where most of these are found. The quickest way to view all shortcuts is to type “Shift + Alt + H”. It will look something like this:

Keyboard shortcuts menu accessible via Shift + Alt + H

How did we get here in the first place though? In the top toolbar there is a “Show more tools & options” menu, represented by three dots. Under the Tools section there is the Keyboard Shortcuts menu, with the keyboard shortcut displayed next to it.

From here we get an extensive overview of the keyboard shortcuts for the editor. These really open up a lot of keyboard efficiency, and will greatly reduce the amount of time we spend creating content. I am not aware if there was anything similar in the classic WordPress editor experience.

Speech to text

I can also see some cool improvements in the future surrounding a speech to text interface for Gutenberg. It would be cool to be able to say a command like, “Gutenberg, insert an image block”, which would trigger an image block to be inserted below the current block selection. Due to our new access to the underlying data model of content, new interfaces for creating content beyond keyboard and mouse will become more feasible. It’s all about the blocks.

Wrapping Up

One of the many gifts that Gutenberg is bring to the web is a new more efficient medium of representing our thoughts and ideas. I think the level of creativity we are going to see over the next years will profoundly shape the future of the web. As always stay tuned for the rest of the series and drop some comments for ideas of your own.

Advent of Gutenberg – 6

With the block concept coming into WordPress, we will see new opportunities to share content. Services like Gutenberg Cloud will most likely pop up, and of course the WordPress.org plugin repository will also be available. One thing about something like Gutenberg Cloud is that you could potentially just grab blocks directly from within the editor. Pretty neat.

Due to Drupal also adopting the Gutenberg editor, any CMS that implements blocks the WordPress way, will be able to leverage the content from both ecosystems. This is very exciting and interesting.

Block sharing

For the most part, I am excited about this new idea. Unfortunately, there are people with malicious intention, and I definitely fear that with an explosion of small reusable pieces, we will see an increase of security vulnerabilities around the sharing of blocks. More on that later.

The positives are very exciting. There is the potential to limit how frequently you will go to the plugins tab. It’s definitely also possible that themes themselves will go away as well. I think a lot of this will be due to block sharing. Let’s say I build a block that allows you to apply a snapchatesque filter to your images. Since this would most likely be implemented in JavaScript (not necessarily the filter itself), it will be easy to share to all of the different platforms that support the block model present in Gutenberg. That would be a specific block and if you wanted to build a lot of weird goofy dog face pictures on your site, it would be perfect.

There will be many niche blocks, but there will also be general purpose blocks. Much like the internal parts of WordPress itself, the nav menus, widgets, shortcodes, etc. are all reasons why we use WordPress. They allow us to create content quickly and with relatively minimal headache. Blocks will supplant the need for a lot of these core APIs. There has been worry over the reduced role of meta boxes, but most likely it will all succumb to a block based implementation, which will probably be better anyways.

Currently, which we haven’t touched on too much in Gutenberg is the concept of reusable blocks. This is where I am the most excited about block sharing.

Reusable blocks

Right below is the first reusable block I am using on my site.

There is a weird bug, currently where I get an extra list item. Oh well not too big of a deal. The main exciting part is that I can use this across all of my posts now. Click on any of the links to see the same list being used across all. We get to share content within our own WordPress install. Pretty cool. But with things like the REST API available, we can potentially even provide content that can be widely distributed as a “reusable block”. I think there is a lot of room for innovation around this. Essentially since the reusable block is also essentially just a custom post type.

Although there is a lot of potential for creativity and sharing, I am somewhat concerned about the potential negatives.

The downsides

There are a two main downsides that are apparent to me: security, and code sprawl.

Security

As mentioned above, security, and education around security is going to be critical. If we make it too easy to grab whatever block from wherever, we are most likely in big trouble. This isn’t necessarily anything new, as you could make the argument that the WordPress.org plugin repository can be a major attack vector as well. This is definitely a reasonably fair assessment. The only difference with blocks, is that they will most likely be more prolific than plugins.

Blocks in their nature are most likely going to be smaller than an entire plugin. Purely due to the reduced amount of code needing to be written for a block, I can see a lot more blocks being created. Blocks are also mainly written in JavaScript, which we have established as the most widely used language. A lot of people are going to be creating a lot of block. In this massive mess of blocks, it will definitely be easy for bad actors to sneak in. If it becomes very easy to just grab a block from some platform, how will users be alerted around the potential dangers ahead? We need to start coming up with good solutions now.

Code Sprawl

We are probably in an era of immense code sprawl already. It might get worse. We will most likely see a lot of blocks that are pretty much the same block. Does this benefit the users? Will we be able to encourage new coders if there are clear winners already established for certain blocks? I think the ability to share blocks will potentially cut down on the creation of the same blocks, but I can definitely see the flip side where it increases. Maybe this isn’t a bad thing at all either. I tend to think that it is, but maybe it really does not matter all that much.

With the rise of distributed computing platforms, I think it will matter, as we will want a way to condense the amount of information we are sharing amongst each other to only what is necessary. The efficiency gains in distributed computing won’t mean very much if everyone has a slightly different file that does 99.9% the same thing. We will need some sort of block unifier, that can take the contributions of many and turn it into one singular block.

Wrapping Up

Gutenberg really opens up a lot of unique opportunities that were not previously possible. I am excited for the future and to see what comes. We will definitely need to be aware of the potential pitfalls ahead and start implementing some safeguards or strategies against them.

Advent of Gutenberg – 5

We are going to look at the editor UI in greater detail now. From a technical perspective the user interface is written in JavaScript leveraging the React library. There has been great effort to make the editor experience extensible like the rest of WordPress, which we will look at more in the future. The tech choices for Gutenberg are also almost as important as the project itself.

Significance of JavaScript

JavaScript is the leading client side language of the web. JavaScript is also most likely the most widely used language as well. Popularity doesn’t necessarily have a positive connotation, but it does mean that there is a wide group of people fluent in JavaScript.

This familiarity enables a lot of things. It enables new developers to more easily and quickly get involved with WordPress, as the client side shifts more and more to JavaScript functionality. In the goal of democratizing publishing, it might make sense to make one of the widely used programming languages a flagship aspect of the platform. JavaScript usage is not anything new to WordPress, but Gutenberg definitely takes it to a new level.

The widespread use of JavaScript also is largely due to JavaScript being a key language of the web. JavaScript’s unique position over time has made it a language available across many platforms. It has become a very large compilation target as well, allowing cross platform codebases to slowly become a concrete thing. Tools like Electron allow for targeting Windows, MacOS, and Linux. Tools like React Native allow JavaScript to become this interop layer for targeting iOS and Android. The shared thread between these is you guess it; JavaScript! Since the web is a cross platform thing, we will probably see more and more web technologies creeping into the native space, or at least that is the current trend.

The direction WordPress is taking technically, will hopefully enable it to reach an even wider audience. This does not mean PHP is going anywhere. PHP is by some estimations still the most widely used server side language. Even if or when PHP is no longer a bedrock of web applications, it is unlikely the entirety of WordPress core will be replaced with another language. Most likely something else would have replaced WordPress. The block concept in a lot of ways though does detach WordPress from it’s underlying server implementation, so only the future will tell what happens.

Editor Areas

Enough jarbling around! The editor has three main areas currently. The header, sidebar, and content area. Each of these plays an important part to shaping our editing experience. Out of the box it is pretty straightforward to just start typing content into the editor like you normally would.

Header

The editor header toolbar is featured at the top of the screen.
The header is the area at the top of the editor.

The editor in the picture above is set into the Top Toolbar mode, meaning that we see the block controls in the top toolbar as opposed to hovering over each block, in a more Google Docs, Microsoft Word fashion. Remember Word in many ways was the killer app of computers for many decades.

Left side of header

The first tool we see in the header is the block inserter. The block inserter is very important, as that is the main way we add new blocks. There are keyboard shortcuts available, but if you are a more visual, the plus button will be your most widely used button.

Next to that we have redo and undo controls. The undo and redo feature keyboard shortcuts as well, but they can be visually accessed here in the header. From my experience, the undo and redo functionality is pretty darn good in Gutenberg. This is partially due to the tech choices made for the project, as well as the great team behind it.

The next two parts of the header are really interesting.

Content Structure

One of the coolest features is the content structure menu, where we get a quick overview of our document.

Content structure menu provides a quick overview of the current document.
This current document at time of inserting this image.

I love this feature. I can see how many words I have typed, headings used, paragraphs used and how many blocks. We also get a nifty document outline. Remember we now have a data model of our content, things like this are more at hand and easy to implement. I see very quickly that there is an error in my heading structure, which I have just now fixed. Would I have noticed that in the classic editor? I highly doubt I would have. It’s all about the blocks.

Next on the list is the block navigation.

Block Navigation

When we open the block navigation we get a pretty neat menu of all of the current blocks. We can see our currently selected block, and select the focus for another block in the menu, or just get an overview of the blocks.

block navigation menu is accessed via the header.
Block navigation can also feature child blocks.

We get child block views available as well scoped to this particular block.

On first glance the menu seems very humble, straightforward, and helpful. The reality is that as the future of WordPress evolves, this block navigation will most likely evolve into a central way of interacting within WordPress.

There is an entire scheduled post on this.

That wraps up the left part of the header. The left part of the header is more content focused. The section to the right is more control and document focused.

Right side of Header

We won’t dive into this too much now, but you can save your post, preview it or save a draft from this area. You can close the sidebar as well by clicking on the gear icon. The sidebar is referred to in this case as Settings. Next to that is another hidden gem the “Show more tools & options menu”. We will look in more depth on this in a follow up post.

The right side of the header toolbar focuses on settings.
This area focuses around publishing and settings.

Sidebar

The sidebar, or Settings area of the editor is another cool part. At the top of the sidebar we have tabs: Document and Block. This allows us to separate different controls into different areas within the sidebar. The document controls, are mainly the features we have grown accustomed to in WordPress like: Visibility, Permalink, Categories, Tags, Taxonomies, Featured Image, and excerpt.

The sidebar document tab houses familiar controls.

Some of the areas that were meta boxes below the post content are now present in this document tab. If you don’t see something you are used to seeing, it has most likely been snuck into the document tab.

As we saw in earlier posts, depending on what block is selected, we will also get contextual controls for each block presented in the sidebar. This is one of the primary areas ripe for exploring extensibility of the editor interface.

Content area

The content area is maybe the most important part, but honestly all three parts synergize together. One is not as complete without the others. We will not be talking about the content area for now. This is mainly to outline it is one of the three key parts to the new editor interface.

Wrapping Up

This should give you a more clear picture of Gutenberg, and outline some of the more hidden gems of the experience. The editor will evolve, but I have a sense that the general UI will be the foundation for years to come. As always, stay tuned for the next post and drop any comments in the comment box.

Advent of Gutenberg – 4

So far we have looked at some of the fundamental content types, text and media. In this post we are going to do a very quick overview of all of the blocks available by default in WordPress. We can see all of the blocks available via the block inserter. By default you can access this via the plus icon in the top left of the screen.

Gutenberg block inserter

Now for every block!

Heading Block!

Above is the heading block, this is a paragraph block.

List Block

  • The list block by default is a unordered list.
  • It supports sub items
    • Like this
    • And this
  • We can also use a list block to do ordered lists.
  1. Within the lists we still have our rich text controls
  2. So we can do bold text
  3. As well as italic and links!

Image Block

image of a pier with birds flying
This is an image block with a caption.

Code Block

/**
 * Sometimes, when dealing with the web, you might want to share a code 
 * snippet. Luckily we have a code block!
 */

function gutenbergIsGreat( opinion ) {
  return opinion;
}

share( gutenbergIsGreat( true ) );

The code block is not much different than the preformatted text block.

Preformatted Block

With preformatted text,
We can do Poetry or other artsy versions of text.
Text that depends on custom whitespace is a great fit for a

Preformatted text block.

Next up is our friendly twitter embed!

Verse Block

Verse block
Is pretty much the same as preformatted text.
It happens to use the main font family instead of a monospace font.

Embed Block

Choyce Design; check it out!

Quote Block

Check out the great post above. This is a quote block. Next is a gallery

-Edwin Cromley

Gallery Block

Cover Block

Cover image block here

Audio Block

File Block

Video Block

My Daughter’s first music video! Please subscribe she needs to get to 100 subscribers!

Pullquote Block

Pull quotes are extra special fancy!

-Anonymous 2018

Table Block

Number of Gutenberg Blocks Used so far35
Number of Gutenberg Advent posts written so far4

There is some really cool stuff I have in store for tables! Stay tuned for future posts!

HTML Block

Even though we see a form on the front end, when creating this block we simply add in HTML. Oila!

Button Block

Columns Block

We can get two columns as well. Columns allow us to nest blocks within other blocks. Pretty neat!

Content, layout is going to be a future focus for the Gutenberg editor, and columns block will most likely play an integral role in that.

Media & Content Block

flowers and a dock

Flowers

Separator Block


Spacer Block

On a project recently, whitespace was critical to the marketing team for whatever reason. Down the exact pixel. There was no real way to accommodate the client, with Gutenberg however, they could have added a spacer block and set the height. I am not excited about this, but it is still very cool to have, and illustrates the creativity that Gutenberg enables.

Above is a 60px spacer block.

Archives Block

Categories Block

Comments Block

Posts Block

Shortcode Block

Embed Blocks

There is an insane amount of embeds out of the box available to WordPress, and these all use the Embed Block as their base. This was already possible in the classic WordPress editor, but now it is just clear that we can post content from:

  • Youtube
  • Twitter
  • Instagram
  • Flickr
  • Soundcloud
  • Spotify
  • Flickr
  • Animoto
  • Funny Or Die
  • Hulu
  • TED
  • PollDaddy
  • Many more…
  • And most importantly WordPress

Phew! That’s a lot of blocks. It will be very important in the coming future to figure out how to create more baseline blocks, and compose new blocks out of existing blocks. We do not want to create some ridiculous proliferation of blocks overwhelming us with options. The embed block is maybe my favorite block so far. One block that allows us to embed any content from the web directly into our posts. Great stuff.

Wrapping up

Now that we see the various content that Gutenberg makes readily available out of the box, next up we will do a more thorough overview of the editor interface, from both a technology perspective and usability perspective. As always, stay tuned! Drop a comment to share your thoughts on Gutenberg so far.

Advent of Gutenberg – 3

Gutenberg logo

Text is a primary content type, but more and more the interactions taking place are going beyond text. Images, audio, video, and visualizations are all becoming more prevalent. Text is a great medium. In most cases, it is more accessible, and easy to produce. Text does have some barriers, like video, you have to actively engage it by observing it, where audio allows you to passively consume the content, while working on something else. Video in some ways can also be a much quicker way of learning how to do something and is a great instructional medium, as it combines both the audio and visual aspects together. WordPress already has great support for different web media types, and Gutenberg will help make these easier to access and interact with.

Media in WordPress

WordPress in its current form has a media library allowing you to manage the media on your site. We’ll come back to this. One of the best parts of WordPress is that it plays nice with other content platforms, allowing us to share information more easily.

Embedding content

The current editor also allows for embedding content from other sites. For example you might add a video to your page by pasting a YouTube link into your content, and clicking enter. This process is one step easier in Gutenberg as you just paste the link, and the editor understands you are trying to embed a video, and creates a new block for you.

The current way of adding a YouTube video.

WordPress was ahead of the game as far as embedding other content, but now it is even further ahead. It is just so easy to add embeds. You can also add embed blocks. They look something like this:

Image of embed block, features a URL input field, and submit button.
Embed block

We simply just enter the link, and if the link is embeddable, we magically get our embedded content. Super cool. So far in this series I have been embedding twitter links. Twitter can be crazy, but there is a lot of great stuff on it. Instead of expanding on tweets in the limited character set, where lots of bickering can happen, we can add commentary via a more thorough blog post. This was possible before in the classic editor, but something about this process is just so nice in Gutenberg.

Link to the gutenstats.blog site, outlining how widespread the usage of Gutenberg is.

Try out adding a tweet to one of your posts:

  1. Go to twitter
  2. Find the tweet you want to embed.
  3. In the top right you will see a downward arrow. Click there to expand the menu and “Copy link to Tweet”.
  4. In the editor on a new block line, paste the link. It will automatically start embedding the tweet. You can get to a new block line by hitting Enter, or the down arrow at the end of the current block you are typing in. ( More on this in the future. )
  5. See the tweet immediately appear in a stylish format.

Not much of a difference between the classic editor, but it is still a great experience. So far we have looked at embedding media and content from outside sources. Let’s look at a staple in WordPress; images.

Image handling in Gutenberg

Image block, featuring an upload button, media library button, or the option to insert via URL.
Image block in Gutenberg.

The above shows the default view of an image block, before we have selected an image. This view is known as a placeholder. Placeholders are great for a number of reasons. One of the most important is content layout. If we wanted to layout our content ahead of time, we could set a bunch of image blocks in various places, with the placeholders ready to go. We could then hand that off to our coworker in charge of selecting what media gets used. This is typically done in the current editor by using placeholder images, but with blocks, it will become more straightforward. It’s all about the blocks.

We have three options for adding an image: upload, media library, and “insert from URL”. Upload allows us to directly upload an image. I personally have had mixed results with this, and do not use it ever. Media Library will open up our media library and let us select the image to use.

The WordPress media library.

I have basically opened two tabs, one with my editor open, and one with the media library open. I simply just upload new images to the library, then switch to Gutenberg and pull in the new image. It’s all JavaScript powered, so no page refresh is necessary. It is actually a very quick workflow. Insert from URL seems to work well too, enjoy wapuu:

Wapuu

You can also drag and drop images into the editor. Currently, like the upload, my own experience has not been the best. Images start to upload but fail. The functionality has been tested rigorously, but for whatever reason my setup makes that extra hard. Don’t let little things like this take away from the Gutenberg experience. This is just the beginning. WordPress has a track record of fixing and accommodating all sorts of issues. WordPress has a strong people-centric focus.

All of the above is currently available in the classic editor. Gutenberg adds some new cool image features.

What’s new about images?

The cover image block!

cover image controls including color overlay settings

One of the coolest blocks is the cover image block, shown above. We get some text over a full cover image background. We can even set a fixed background effect for a nice visual touch. Like any block a lot of the extra options are found in the sidebar, when that block is selected. Always check out the sidebar to see what is available!

Right off the bat we see the fixed background control set to on. We also see the overlay controls. In the post we see a nice dark blue overlay, by default it is a black overlay. You can also just set the opacity to 100%, and get a full screen background with text.

Remember that each of these sidebar areas are available for developers to extend the functionality of each block type. Who knows what people will come up with.

Working with images in the new editor.

Let’s look a bit more in depth at what options there are to work with in Gutenberg. We will start with the block toolbar.

image block toolbar

Here you can see an image block selected with the toolbar above it. We currently have the center alignment set. You can left or right align an image which will float the content to the left or right, allowing the text to wrap around the image. The left and right alignment experience could use some tweaking, but it does work. We can quickly also change the image by accessing the Edit button, represented by a pencil. We also get sidebar controls.

Image block sidebar controls contain alt text attributes, image dimensions, link settings, and additional css.

We can edit the alt text, image dimensions, link setting, and additional CSS class from the sidebar by default. If you can imagine a setting that is missing from this menu, plugins will become available to fill these gaps, or you can make your own!

Remember this is the foundation. Unlike the classic editor, room for extending the functionality is possible, and available.

With the new block model, galleries become much more engaging. We will look at galleries more in the future.

What lies ahead for images?

There is a lot of future room for improvement around images. With the block concept available to us, we will potentially be able to make different crops for different screen sizes or have an image set that serves a different image to different audience segments. This area is a big struggle for web content in general, and I feel that Gutenberg puts WordPress in a unique position to solve this problem.

Responsive images will become easier to manage, currently it is very challenging. This will greatly improve the mobile experience, a major win for the web.

I can also see new image editing tools being built into WordPress. You could upload a raw image, do a custom crop, maybe apply some filters, do some various light editing. The possibilities are very open, and I think we will see a lot of these new experiences being provided via plugins. Maybe the best will get rolled into core itself. Google docs has great image editing tools for this purpose. With the foundation presented by Gutenberg, this might allow WordPress to even surpass that experience.

Wrapping up

The media library plays a critical role in the new editing experience, allowing us to quickly add in content. Below we see a list of some of the common media blocks available:

List of common content blocks.

Image, galleries, cover image, audio, file, and video are all media blocks ready to go out of the box. These were all possible previously in the classic editor, but now everything is a bit more discoverable. In the past I might have to go to an external source and read about WordPress to understand how to use it. This problem is not fully solved, or ever will be, but the new editor interface is more inviting to explore, and you can figure things quickly by just poking around.

Leave any comments or feedback on what you would like to hear about next in the series!

Advent of Gutenberg – 2

Gutenberg logo

One of the core parts of WordPress, ever since I have used it, has been the rich text editing experience. That experience is powered primarily by TinyMCE. TinyMCE helps manage some of the oddities of HTML’s contenteditable interface. The new Gutenberg editor, by default, also uses TinyMCE in a more stripped down form. You can access the classic editor experience from within Gutenberg, by using the classic block. To add in a classic block, we need to open up the block inserter, and search for Classic. Once we find it we can just click to insert it into our content.

The block inserter is used to insert new blocks into the content.

I am now typing in the classic block. It won’t be distinguishable when you are reading this post, but it is nonetheless a classic block. We can do most of the things we are accustomed to in WordPress’s content area.

  • Here is a bulleted list
  • With items
    • Sub items!
  • Woo!
  1. An ordered list.
  2. Very similar experience to content editing.

Strikethrough text

Different color text.

Insert media.

It is the same classic editing experience of WordPress embedded within the new content editor. If Gutenberg is really not jiving with you, I would encourage you to at least work with the classic block, and then start exploring new blocks. This might serve as a smoother transition.

We are now exiting the classic experience. The downside of the classic experience is that we do not have blocks. It is just one big block of rich text. We lose control over the individual units. Remember, it’s all about the blocks. If I want to move anything, I have to use cut and paste. In Gutenberg we have controls to easily move blocks up and down.

When a block is selected, positional controls become available.

As you can see above, when we focus on a block, we get some extra controls around it. Cut and paste in particular, has been something that I see people struggle with. It is definitely a wide spread convention that any computer user is familiar with, but in my town, maybe shocking to some, computer usage is probably not something that everyone is totally familiar with. Copy and paste are an assumption we rely upon. I have seen people delete entire paragraphs to re order their content. Mastering copy paste can be much trickier than simply using the up and down buttons to shift around content; a small win.

When we are working with blocks, we get many additional controls. Let’s look at some of the new and familiar aspects of text in Gutenberg.

Managing text

As we type, the block controls fade into the background, allowing us to fully focus on our words. When we select a block, we see the block toolbar popup, let’s break that down a bit.

Block toolbar

Blocks now feature a block toolbar when the block is selected.

Above, we see the block toolbar hovering on top of the text. The first control is the block type switcher, allowing us to convert the block to another type. We aren’t going to worry about that right now. Next to the switcher we see the text alignment controls. We can left align, center, and right align our text on a paragraph by paragraph basis very easily.

Right aligned.

Center aligned

Left aligned.

Next up after that are our classic text formatters. We have bold, italic, link and strikethrough. Very neat, and readily available to use, as they appear right above the block we are working on. After the formatters is the more options control, represented by three vertical dots.

The more options menu enables quick access to generic block funcionality.

More options will feature generic options for the block, like duplicating, deleting etc. It will also show the quick keys for any actions that have a quick key. Each block toolbar as a whole, will have its own unique controls that are specific to it.

Each toolbar is also very customizable from a developer perspective; allowing new controls, or user specific controls to be added and removed. The block controls don’t stop there either. We also get another area of the editor that allows us to interact with blocks, the sidebar.

Sidebar controls

With the paragraph block, by default we have some cool sidebar controls. This paragraph is using the drop cap style. Which, looks really neat and adds a nice stylistic touch, all we have to do is toggle on the drop cap for a paragraph in the sidebar and we are good to go. We can also adjust the font size. In general it is probably not best to mess with the font sizes too much, but it is there if you really need it. Pretty neat.

Drop caps for paragraphs can be toggled form the sidebar

The sidebar controls are really going to be an amazing area to explore what can be done with content. This is an area where plugins can really do a lot of incredible things. I can also see some plugins going completely overboard and ruining the experience. Let’s try to not go overboard.

My favorite part is definitely the color options. I think a lot of really cool designs will come about from these basic controls. They also have built in accessibility helpers for managing the contrast of colors. Awesome.

Color settings for paragraphs are located in the sidebar.
Color options for paragraph blocks.

This is one of the many things to come that will really bring out a lot of creativity in people. I can’t wait. The web is going to get a whole lot more interesting.

We will go into more depth around the sidebar in the future. Essentially it is another area to feature controls for interacting with blocks. Remember without blocks, these controls and features are simply not possible. It’s all about the blocks.

Managing headings

Another great aspect of the block concept is that we can very easily add in features like anchor text. Here is a link to the managing headings area. All I had to do was add anchor text to the “Managing headings” block, and then create a link with the URL matching that text, #managing-headings. You can set the anchor text to whatever you want, just make sure it matches up with the links you want to use. Before, without the block model, this would require manual editing of HTML, which you can still do, but in my opinion it is much easier to use the new interface. What if you don’t know HTML, or care to know? Well now you don’t have to.

Adding anchor text to headings can be accessed in the sidebar.

The anchor text for a heading can be accessed from the sidebar controls, in the advanced tab.

Headings serve as a way to structure our documents, in a semantic manner. Now that Gutenberg brings the block model to us, it is relatively simple to add a table of contents to our posts now, organized by heading structure. This could be done as a block, which we will see in the future.

Heading block toolbar

Another quick win for headings is the ability to easily select your heading size. In the classic editor this was more in line with Microsoft Word. There is something more satisfying about clicking the size button, and immediately seeing the update. No more selecting over text with your mouse, making sure the selection is perfect, and then finally selecting the perfect heading from the dropdown. Just select the block, and click a button. Nice. Additional sizes are in the sidebar controls area.

Headings can be quickly controlled in the block toolbar and sidebar areas.

Wrapping up

Headings and paragraphs are really the backbone of a lot of web content. Here are some of the benefits of switching to Gutenberg so far:

  • All of the same core content experience we are accustomed to, is available in Gutenberg, nothing has been left behind.
  • By having blocks, we now have more fine grained control over the structure of a document.
    • Text color, and background color.
    • Drop caps.
    • Font size.
  • We can do important tasks more easily that used to be a pain.
    • Heading anchor text.

It’s not as though these tasks were impossible in the classic editor, it is that they were not as at hand, ready for us to grab and use. I feel so much more creative when writing in the Gutenberg editor. It’s just fun.

Text is only one part of content experience. Next we will be looking at how Gutenberg handles media elements. I hope you are enjoying the series so far, and comeback tomorrow for the next post!

Advent of Gutenberg – 1

The WordPress space, and other open source communities are building anticipation around the new content editor, Gutenberg. The development of the editor and overall process, has been controversial, inspiring ClassicPress, a fork of WordPress. I think the controversy is definitely perceived at a higher level of severity, being amplified by the current cultural climate permeating many things. Controversy aside, new things are on the way and in this season of gift giving, I am very excited for the world to receive the gift of this new content editing foundation.

It’s all about the blocks

The new foundation of WordPress is not being built on the editor persee, instead it is being built upon the block concept. Gutenberg does feature a new UI that is different from the current editor. The current WordPress editor always felt boxed in, closed off, and subconsciously limiting to creativity. Your content was in a small box surrounded by all of these other distracting elements. The new user interface for WordPress will be more open; with a pure focus on content. I can focus so much more easily on the words as I type in Gutenberg. That’s just the new interface; great, but not groundbreaking. It’s all about the blocks.

What’s in a block?

The idea of a block is vague, and abstract. A block is essentially an individual unit or grouping of content. This post so far has been comprised of headings, and paragraphs. Each is its own block, and as a whole, the entire post becomes a block containing this content. So what’s the big deal?

Unlike the previous editor or really any content editor I know of, there is now a deeper fundamental connection between the visual layer and underlying data model. This connection is made possible by having a more accessible, programmable, data driven content layer. Sure, the posts end up being stored as HTML, or more specifically WP Post Grammar, but that isn’t necessarily the data model of blocks. WP Post Grammar is just the current storage format. So although we had content before, and now we can make the same content with the block editor, there is a very subtle and fundamental shift occurring.

To explore this shift further, let’s think about numbers. A number is this vague abstract concept, much like a block. Most of us have become accustomed to using a base ten numerical system using 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. So much can be expressed with just different variations of these numerals. If we want to figure out what 9 x 9 is, with sufficient learning, we get an answer of 81, fairly easily. Let’s use another system to represent the same numbers; Roman Numerals. Now we have IX * IX which is equivalent to LXXXI. Math is usually not widely loved, but let’s be thankful for not having to learn it in Roman Numerals.

There was a time when many people who needed to figure something out had to use this terrible number system. The very syntax itself made certain thoughts unthinkable, certain ideas inexpressible. If I lived in that time, I would have never questioned it, I would have carried right along unaware of this other world that had not been discovered. The very foundations of arithmetic would not be as discoverable with a system like Roman Numerals. With the web, and the computational medium in general, we are in its infancy. I am excited to see what worlds we can open by having a new creative foundation. Gutenberg and the block concept, I think will play a part in opening up new creative outlets.

WordPress’ content as it is now

With Roman Numerals there are all of these rules around each character, and the placement of each character can effect its meaning and the meaning of other characters. It is really terrible. No one uses Roman Numerals anymore. Let’s look at them if you are not familiar, so you can see how confusing they are. “I” is 1, so “II” would be 2, “III” 3. You might think four would be “IIII”? Wrong; “IV” ( :facepalm: ). “IV”, what the hell is this? Let’s see. “V” means 5, and “X” means 10. Somehow putting “I” before “V” or “X”, means subtract 1 from the following value. So “IX” is 9, and “IV”, is four. But “VX” is just not a number, it doesn’t mean subtract 5 from 10. It only gets worse from here.

Roman Numerals just really do not make any sense at all, or there are too many different rules that govern them. You can’t keep track of it all in your head. I can’t help but feel this same problem plagues WordPress. I have seen many people struggle learning WordPress, including myself. Like Roman Numerals, once you learn them you can navigate your way around, but you do not realize what you are missing out on.

In WordPress we have widgets, nav menus, post types, meta boxes, shortcodes, links (not used anymore), media, post formats, page templates, and whatever else is brought in by the plugin ecosystem. There are so many things you have to keep track of when building content with WordPress. We are just used to it. On top of that each of these content types can have many super confusing interactions, and special cased rules. The block concept unifies these content types. Blocks on their own will not solve the woes of WordPress, but they afford us the ability to start building a new future.

Future of blocks

Dennis Snell shared a really cool block on twitter:

Dennis Snell is a really nice person, and has been very active on the parser for WP Post Grammar.

So here I am, in the moment of thinking about this, grabbing Dennis’s tweet, and sharing it in my post as a tweet block. Super fast, super easy. I can see it right now as I type. Imagine how this will allow us to share ideas more quickly, more expressively, and with WordPress, unlike other platforms, I have sovereignty and authority over the content I interact with.

Dennis, in only 137 lines of code, created a drawing tool. Would you imagine drawing in the current state of WordPress? Would it only take 137 lines of code? When I complete my doodle, because it is now a block, maybe I can just send it to you, and you can add your own doodle on top and send it back?

It goes further. It is maybe an insensitive or uninformed opinion, but I believe Gutenberg will be even better for things like accessibility. Why? Since Gutenberg is now connecting us with the underlying content in a new way, we will have new ways to represent content, and represent how to interact with content. Although the design stance has centered around making a uniform experience, I can see plugins providing alternate editing experiences accommodating everyone’s needs to a further level. This doesn’t mean that the core should not be accessible, but I think perhaps even our current ideas around what web accessibility means could change.

Reality of today

Gutenberg is not without its faults. There have been communication failures in the process. There are bugs. There are outstanding issues. As I write, on my host, I see warnings of updates failing. This could be very scary to a non technical user, as they will believe their work is not saving. Even though I see these warnings, my content is saving. I have never lost content using Gutenberg. I lost power a couple weeks back, right in the middle of writing a post. When I checked back, not a single letter was missing. That is the level of care put into this editor. I am sure there will be Gutenberg horror stories, but in the WordPress community one thing that I have seen and can guarantee is that people care. They will work hard to try and help as many people as possible with an open ear and heart.

Even though Gutenberg could change a lot of things, maybe it won’t. Maybe it will be just a more pleasant writing experience, or not. Maybe it will be incredibly underwhelming. Maybe some of the technical decisions will sink WordPress into further technical debt. The reality is that nobody knows what is going to happen. As Gutenberg stands today, it is not a radical shift from how we currently use WordPress, but to me it symbolizes a new road ahead, that is open and awaiting new visions to guide the way. 

What’s next?

For this season of generosity, I will be making 25 posts in honor of advent, to show the gifts that I think Gutenberg will bring to WordPress and the web. Each day we will learn something new about Gutenberg, what it can do, and where it could go. I leave the rest up to you!

JavaScript Fundamentals – Part 3 / Fun with functions

One of the most powerful parts of JavaScript is the function. Functions serve as a way of breaking programs into smaller repeatable parts. Functions have three parts themselves: name, arguments, and body. There are two phases of working with functions, declaration and call.

Function fundamentals

Let’s look at a function declaration.

// Name: addOne
// Arguments: number
function addOne( number ) {
  // Body: return number + 1;
  return number + 1;
}

We named the function addOne, because in the body we are taking our argument number, and returning the value of it plus one. After a function is declared we can call it like so:

function addOne( number ) {
  return number + 1;
}

// Outputs 3 to the console.
console.log( addOne( 2 ) );

When we call a function, we supply the needed arguments, and the body of the function is evaluated, and run. The body is like a mini program inside of our program we can also use functions previously declared inside of other functions.

function addOne( number ) {
  return number + 1;
}

function three() {
  return addOne(2);
}

// Outputs 3 to the console.
console.log( three() );

We declared two functions above, addOne and three. Three pulls in addOne from the upper scope and calls it passing in a 2. We get 3 as the return value. This ability to use functions we declare inside of other functions is very powerful as it allows us to build programs out of small repeatable patterns.

JavaScript allows us to create functions without names, which can be useful for a number of reasons.

Anonymous functions

Anonymous functions are useful when your particular function you create does not need to be used across your program in multiple parts, they serve as sort of “one use” mini programs. An anonymous function might look like this:

function( message ) {
  console.log( message );
}

There isn’t very much special about this at first glance it is just a function declaration without a name. There is not even a way to call this function, so what’s so interesting about anonymous functions? Well they are still a declared value like this:

var log = function( message ) {
  console.log( message );
}

// Outputs "Hello!"
log( "Hello!" );

So we can have alternate ways of “naming” functions, it is important to note that the function does not have a name it is just bound to a variable that we named log. This next example is going to be a little weird and might take a bit to understand:

// Outputs "Calling immediately!" tot he console.
( function ( message ) {
  console.log( message );
} ( "Calling immediately!" ) );

This is known as an immediately invoked function expression or IIFE for short. It is definitely a little strange. We wrap the entire thing in a set of parentheses to mark the expression. We declare an anonymous function, and then immediately call it with "Calling immediately!". It is weird, but it is an important aspect of understanding JavaScript. The reason this works is because in JavaScript functions are values.

Functions as values

Values can be passed around and used anywhere an expression can be used in JavaScript, expressions as you remember from part 2 are pieces of code that should evaluate to some value. It can get a bit weird thinking about a function as a value as it is a bit abstract. It is much more easy to thing of values like 1, 2, 3, and “Strings”. Let’s look at some cool things that come from functions as values:

function Tim() {
  console.log( "Hi Tim!" );
}

function Xi() {
  console.log( "Nǐ hǎo" );
}

function Emilie() {
  console.log( "Bonjour Emilie!" );
}

function greet( greetFunction ) {
  greetFunction();
}

// Outputs "Hi Tim!"
greet( Tim );

// Outputs "Xi"
greet( Xi );

// Outputs "Bonjour Emilie!"
greet( Emelie );

We have three greeting functions for three different people. We then create a generic function greet which takes a function as its only argument, and calls whatever the function is. So we create one greet function that can handle and call another function at any point we choose. Pretty neat.

Scope

JavaScript has different types of scoping to it, but at it its core it is mainly a functionally scoped language. What is that exactly? Understanding scope is best achieved through looking at examples:

var myVarInUpperScope = 1;
var myVar = 2;

// Always will output 2 in this scope.
console.log( myVar );

function coolFunction( myVar ) {
  // Will output whatever the argument is that is passed to this function, creating a new scope.
  console.log( myVar );

  // Always returns 1, because there is no other variable named in this scope, so JavaScript looks to the higher scope.
  return myVarInUpperScope;
}

// Outputs 3, returns 1.
coolFunction( 3 );

// myVar is still 3
console.log( myVar );

// Outputs 1, and returns 1.
coolFunction( myVarInUpperScope );

We can also declare new variables inside a function that will only be accessible to that scope, or other scopes within that function let’s look at a more complex example:

var upperScope = 'Upper';

// Always will output 'Upper' in this scope, unless reassigned later.
console.log( upperScope );

function changeUpperScope() {
  // Grabs the upperScope variable and changes its value.
  upperScope = 'Reassigned!';
}

function defineNewUpperScope() {
  // Make a new variable declaration inside this function scope.
  var upperScope = 'Function';
  var functionScope = 'FunctionScope';

  return upperScope;
}

// Outputs 'Upper', since that is the currently declared value.
console.log( upperScope );

// Returns 'Function', from within the functions scope.
defineNewUpperScope();

// Even though upperScope was defined inside the previous function it
// does not affect the variable at the global scope.
// Still outputs 'Upper'
console.log( upperScope );

// Now the global scope will get reassigned from within a function.
// It grabs the reference from the upperscope and reassigns it.
// Make note of how changeUpperScope does not use a var declaration.
// Instead it uses the same reference as the upperscope, watch what
// happens.

// Call our reassigning function.
changeUpperScope();

// Outputs 'Reassigned!'
console.log( upperScope );

Scope can be complicated in JavaScript, so experimenting with it and really getting a strong grasp on it is critical to understanding JavaScript. We will see how powerful functional scoping can be as well as how catastrophic it can be if not used properly. A common scope problem that can arise is a collision.

Avoiding collisions

JavaScript is a dynamically typed language. This is a fancy way of saying that any value or reference can essentially be overwritten at any point. Any variable, or object we find, can be rewritten on the fly and be something completely different. This crazyness is what often turns people away from using dynamic languages, on highly critical applications, because it is much easier to introduce bugs into dynamic programs. Let’s look at a very common example; collisions. In JavaScript you end up using a lot of other people’s code. Here is Dinesh’s write function.

function write() {
  document.write( 'I am Dinesh' );
}

write();

Here is Arjana’s write function.

function write() {
  document.write( 'I am Arjana' );
}

write();

Both functions are written into the global scope, so if we loaded both of them at the same time in our project, the later loading function would override the other and become the actual function. Resulting that " I am Arjana" is written twice. We can avoid collisions by leveraging IIFE’s like we saw before. Here are what Dinesh’s and Arjana’s files should look like to prevent collisions.

// Dinesh
( function () {
  function write() {
    document.write( 'I am Dinesh' );
  }

  write();
} () );

// Arjana
( function () {
  function write() {
    document.write( 'I am Arjana' );
  }

  write();
} () );

In this case both write functions will now work, because they are independently scoped first. We create an anonymous function, which creates a new function scope, and place the code we want to run inside of it. We then call the function with (), and wrap the entire expression in another set of parentheses. This immediately calls the function we created, and executes the code inside the body of the function with it’s own scope.

We will look at collisions and dependencies in the future more, this is a rough example that probably does not illustrate the issue the best. This technique is known as using a function closure.

Closures

Closures are a special way to use functions to “close over” values and references into a particular scope. Let’s look at an interesting example:

function myClosure ( start ) {
  return {
    next: function() {
      return start++;
    }
  }
}

const counter = myClosure( 1 );

// Returns 1
counter.next();

// Returns 2
counter.next();

// Returns 3
counter.next();

const newCounter = myClosure( 10 );

// Returns 10
newCounter.next();

// Now for something a little weirder.

const newerCounter = myClosure( counter.next() + newCoutner.next() );

// Returns 15
const newerCounter.next();

// Returns undefined, start only exists inside the closure.
console.log( start );

In the future we will see how the above example is actually quite useful. Let’s look at myClosure and what exactly is going on. It is a function that takes an argument start. It returns an object, with a property next. Next’s value is an anonymous function, that returns the post increment value of start; meaning, we get the current value and then the number is incremented by one.

Inside of the next function the start variable is being grabbed from the upperscope of myClosure. Once we call myClosure with a number, we can no longer access what number was passed in, we can only interact with that number by using next; a very powerful property known as encapsulation. Encapsulation means that certain data can no longer be accessed from the outer scope, we “close over” those values. They can still be interacted with from the outer scope, but they do not exist in the outer scope. It definitely takes a bit to fully understand so don’t worry if it does not sink in immediately. We will look more in depth at this example coming up soon, and the different capabilities this provides.

Wrap Up

Functions serve as a powerful tool in JavaScript to allow us to build complex programs out of small reusable parts. We will be checking out some more advanced function features in JavaScript coming up next. If this did not fully set in, take time to reread and experiment on your own, if you get stuck leave something in the comments section.

JavaScript Fundamentals – Part 2

We will be focusing on JavaScript syntax, or the way JavaScript is written, in this section. If some of these concepts are not super clear, try starting with the first article in this series.

Syntax

The art of programming is more like a conversation with a computer than writing. Like any conversation, if you want it to go well, you need to communicate well and in a way that is understood between both parties. Syntax is the set of rules that govern how a language will be interpreted by a computer. We need to follow the syntax of JavaScript in order to be able to use JavaScript to get the computer to do what we want.

In our conversation with the computer there are three basic parts: statements, declarations and expressions. The lines do get a bit blurry so don’t worry about the distinctions too much.

Expressions

Expressions produce values and can be written wherever a value is expected. Here are some basic expressions:

1 + 2;

( 1 + 2 ) * 3;

"String";

[ 1, 2, 3 ];

[ 1, 2, 3 ][0];

{ name: 'Taco' };

function () { console.log(10); };

Each expression can be evaluated for its value.

1 + 2;
// Evaluates to 3

( 1 + 2 ) * 3;
// The ( 1 + 2 ) evaluates to 3, and then we get 9.

"String";
// Evaluates to "String"

[ 1, 2, 3 ];
// Evaluates to the array with [ 1, 2, 3 ]

[ 1, 2, 3 ][0];
// Evaluates to 1

{ name: 'Taco' };
// Evaluates to { name: 'Taco' }

function () { console.log(10); };
// Evaluates to fn () { console.log(10); }

Each of these expressions evaluates to a value in JavaScript. If you need to brush up on values checkout JavaScript Fundamentals Part 1. Arrays and objects are expressions in JavaScript that evaluate to themselves. The trickiest part here is probably the last one the function expression. Here we are creating a function that console.logs 10. In JavaScript functions are also values, known as first class functions. So in this use of a function it is an expression because it is just another value. We will look at this in more depth in the future, but it is important to take a mental note that functions are values in JavaScript.

Most of what you will work with in JavaScript are expressions. Statements in JavaScript serve the purpose of being more fundamental building blocks that do things.

Statements

Expressions only get us so far in JavaScript, statements are things that cause things to happen, but do not return or evaluate to any values. Let’s look at the if statement. if has special meaning in JavaScript, and an if statement is written like this:

if ( true ) {
  "This code is executed.";
}

if ( false ) {
  "This code is never executed.";
}

"this code is executed";

if ( false ) {
  "This code is never executed.";
} else {
  "This code is executed.";
}

As we see above the if statements direct which code is executed and which is not. Inside of the () parentheses we have an expression that must evaluate to either true or false. If that expression is true we run the code inside of the {} curly braces.

Another very common statement in JavaScript is the for loop statement, which allows us to run a section of code multiple times.

for ( var index = 0; index < 100; index++ ) {
  console.log( index + 1 );
}

We have a couple parts to the for statement. Inside the () parentheses we have three expressions, one declares starting variables, the next is the condition for the loop, if true, then we execute the code, after the code runs we run the third expression. When we run this code it will log to our console 1, 2, 3, 4 … 100. So instead of writing out each of those we use the for loop to run the same code over and over. If the for loop doesn’t make much sense don’t worry about it, we will look at it more in depth in the future.

The main takeaway with statements is that they do not evaluate to value, and instead are code we right to affect how our code executes. There are other types of statements in JavaScript, but these are two very important ones.

Declarations

In the for loop above we see var index = 0;, this is a variable declaration. Declarations are parts of our code that create references. References allow us to name a value and reference it later in time. These references and their associated value are stored in the computer’s memory. Let’s look at some basic declarations in JavaScript:

// Variable Declarations.
var ten = 10;
let six = 6;
const seven = 7;

// Function Declaration.
function myFunction() { console.log( ten ); }

The variable declarations above use the assignment operator, =, to assign a variable a value. Above we have the variable ten, and its value is 10. six is 6, seven is 7. We also have a function declaration so now there is a reference myFunction which contains the value fn() { console.log( ten ) }.

References are super useful let’s look at how they are useful in our programs.

var number = 11;

number;
// Outputs 11

number * 2;
// Outputs 22

number;
// Outputs 11

number = 12;

number;
// Outputs 12

number = number * 2;

number;
// Outputs 24

var number = 3;
number;
// Outputs 3

We can see above that we can use the reference number to do all sorts of stuff, and at the end we use the var declaration to redeclare the variable again. By naming these variables we can write code that is more understandable. The above could also be written like this.

var number = ( 11, 12, 12 * 2, 3 );

Not as easy to read, or know what the values are, or even know what is going on. Even though it is more concise we lose a lot of what happened above.

Each declaration however only applies to the scope we are currently executing in.

Scope

Scope can be very confusing in JavaScript, and when you are first starting out it can lead to unexpected results. JavaScript scopes based off of functions, and in some cases block scope. The more important scope to understand is function scope. If we are not inside a function, then our scope is at the global level. Let’s look at how scope impacts our references and declarations.

var number = 10;

function getAScopedNumber () {
  var number = 1;
  return number;
}

function getNumber () {
  return number;
}

function changeGlobalNumber () {
  number = 3;
  return number;
}

getNumber();
// Evaluates to 10

getAScopedNumber();
// Evaluates to 1

changeGlobalNumber();
// Evaluates to 3

getNumber();
// Evaluates to 3

getAScopedNumber();
// Evaluates to 1

There are a couple of things going on here. We declare a variable number in the global scope and give it the value 10. We create a function getAScopedNumber that declares a variable number and gives it the value 1. When we call getAScopedNumber(), we will always get 1 returned for number because we are declaring a variable number in that scope. We have getNumber, which returns the reference to number. Since there is no reference declared in this function’s scope, JavaScript looks for an upper scope and finds the number we declared in the global scope, in this case it is ten if we call that function.

We have a third function changeGlobalNumber, which assigns number the value 3, because we are not using a declaration like var, const, or let this is telling JavaScript we are looking for the reference number, and because we have not declared one in this function scope, it grabs the one from the upper scope, so now our global value for number is 3. You can see this by calling getNumber() again. Functional scoping is confusing, but also very powerful. It might take a while to get the hang of how variables and scope work in JavaScript, and there are some things to look out for that we will cover in the future. For now, you actually have a great understanding of the fundamentals of writing JavaScript.

Putting it all together

var luckyNumber = 7;

for ( var index = 0; index < 10; i++ ) {
  if ( index === 7 ) {
    changeNumber();
  }

  console.log( luckyNumber );
}

function changeNumber () {
  luckyNumber = 13;
}

luckyNumber;
// Evaluates to 13.

This will output the following to the console:

7
7
7
7
7
7
7
13
13
13

Mastering these fundamentals will greatly strengthen your skills when you need to use JavaScript to do something more practical.

Up next

Up next we will be looking at cool things we can do with functions in JavaScript, as they are a fundamental aspect of JavaScript.

JavaScript Fundamentals – Part 1

If you are looking to start learning JavaScript from the ground up, try this article about getting started with JavaScript first. JavaScript is a unique and widespread language. At its core the language is built out of primitive values, and objects.

Primitive Values

undefined, null, strings, numbers, functions, arrays, objects and booleans, are the primitive values that make up JavaScript.

undefined & null

One of the mysteries of working with JavaScript is knowing when undefined and null are used. It is also a mystery why two null values exist. For the most part these are used to signify the absence of something. They can have some pretty quirky behavior that we will look at later on.

strings

Strings are a super useful primitive value in JavaScript. Their main role serves to hold values of text, or sequences of characters. They are enclosed within quotes like this:

"I am a string withing double quotes";

'I am another string in single quotes';

To reiterate, strings are used to process and store text within JavaScript. The programs we right are just sequences of characters, mastering strings opens very interesting worlds. You can learn more about the basics of strings, in a more practical fashion.

numbers

There is only one kind of number in JavaScript, and they are double precision floating point numbers. Don’t worry too much about the name, but basically the numbers in JavaScript are not as precise as we are used to when dealing with decimals.

0.2 * 0.1
// Outputs 0.020000000000000004

20 * 1
// Outputs 20

As you can see, floating point numbers can do some pretty crazy unexpected things, especially when dealing with decimals, integers are. If you are going to be creating programs that highly depend on the precision of numbers and arithmetic, JavaScript might not be the right fit. It is however a great language the large majority of applications.

This type of number in JavaScript has a maximum and minimum value:

maximumInteger = 9007199254740991;
minimumInteger = -9007199254740991;

When you start dealing with really big integers in JavaScript that pass out of these bounds, other weird things can happen.

9007199254740991 + 4
// Outputs 9007199254740996

Above we see an extra 1 being added at the end, which is related to the floating point arithmetic being used. So, as a fundamental takeaway, numbers as we are used to are weird in JavaScript, don’t expect them to work the way you expect, always check what is happening. Numbers are actually relatively complicated across most programming languages.

There are other flavors of numbers in JavaScript.

0b11
// Binary number 3 0b starts the number and digits follow. Base 2

0b111
// Outputs 7

Oo11
// Octal number 9 0o starts the number and digits follow. Base 8

0o111
// Outputs 73

0x11
// Hexadecimal number 17. 0x prefix followed by digits. Base 16

0xff
// Outputs 255

There are some cool binary operators that you can use to work with these numbers for lots of interesting things. In my experience, working with binary digits is not necessarily a fundamental, but they are great to know about and keep in mind. Another type of number in JavaScript is an exponential.

1e5 * 2e20
// Outputs 2e+25

The way they are written is a little odd but basically it breaks down like this:

1e5 is the same as:
1 * 10 ^ 5, which is the same as
1 * 10 * 10 * 10 * 10 * 10

Which is just 100,000.

The first part before the e is the base and then we multiply that number by 10 the number of times after the e. So 1e5 is 1 * 10 to the fifth. Numbers like strings, are very critical part of any program, and mastering them helps lead to mastery of JavaScript.

booleans

Booleans are a very useful and basic value. A boolean can only be one of two values true or false. The clear cut nature of booleans makes them easy to work with and allows us to add logical reasoning to our programs.

var jsIsAwesome = true;

if ( jsIsAwesome ) {
  console.log( 'Woo! Learning JavaScript!' );
} else {
  console.log( 'I am sad.' );
}

The above code will log Woo! Learning JavaScript! to our console, because jsIsAwesome is true, if it was false, we would get I am sad..  Booleans and truth values allow us to take different paths in our programs, and in many ways are highly related to binary numbers and the foundation of how computers even work in the first place.

arrays

Arrays are at their core a way to create a list or collection of other JavaScript values. They become really useful for organizing and grouping different parts of our programs, and the data that powers them. You can learn more about working with arrays here. They look like this:

// Array below!
var array = [ 'I', 'Am', 'an', 'array', 1, 2, 3, true, false ];

// You can access the items like this
array[0];
// Outputs 'I'

array[4]
// Outputs 1

There are many more ways to work and interact with arrays, and they are another fundamental part of JavaScript to understand.

Functions

Functions are a huge part of JavaScript. They allow us to create mini programs within our programs, and so much more. Getting started with functions is really important, as they lead to some very advanced concepts in JavaScript. Functions are a key pillar of JavaScript as a language.

Objects

Objects hold a special place in JavaScript, most of the primitive values we have looked at are also special types of objects. Most objects will look something like this in JavaScript:

var myCoolObject = {
  isCool: true
};

// Access looks like this.
myCoolObject.isCool // Outputs true

Like arrays, objects serve as a way to group various things, in this case, we are taking the property isCool and associating a value of true to it. So when we ask whether our object isCool or not, we get the value associated with that property. The main function for objects is to associate names of things with values. This helps us more easily reason about our programs. Working with objects is a fundamental part of JavaScript.

The difference between objects and values

If the primitives are special forms of objects in JavaScript what is the difference? The main difference is that strings, numbers, booleans, undefined, and null, cannot change; immutable. Objects, and arrays on the other hand can change, referred to as mutable. Here is a quick look at the difference.

var ten = 10;
10 + 1; // Outputs 11
ten; // Outputs 10, ten does not change even though we added 1.

var string = 'Hi';
string + ' World!'; // Outputs "Hi World!"
string; // Outputs "Hi" string stays the same.

var array = [ 1, 2, 3 ];
array.push( 1 ); // Adds 1 to the end of the array.
array; // Outputs [ 1, 2, 3, 1 ] the value has changed.

var object = { name: 'Joe' };
object.name = 'Aadhya';
object; // Outputs { name: 'Aadhya' }, the value has changed at our stored reference.

You can see that the immutable values stay the same, even though we did operations with them. The immutable operations just return new values, they do not change the existing value. Understanding how different operations affect our programs is very important in JavaScript, and takes time to master. For now, don’t worry about it too much. I did somewhat lie above, as JavaScript does have some number operators that are mutable.

var ten = 10;
ten++; // Outputs 10
ten; // Outputs 11
++ten; // Outputs 12
ten; // Outputs 12

The increment operators can mutate our references here so in someways numbers can be mutable as well.

Other aspects of JavaScript

JavaScript has a lot of unique characteristics. It is a dynamic scripting language, with elements of functional, and object oriented languages mixed together. As a scripting language, JavaScript can run in all sorts of different places, which is why it is probably the most widely usable language in existence currently. JavaScript also has some meta programming capabilities as well; programming programs that change our programs. Due to the dynamic and meta aspects of JavaScript, a lot of wild things can happen, so enjoy your adventures in JavaScript!

In part 2 we will look at the fundamentals of JavaScript syntax.