Building a Video Blog with Gatsby and Markdown (MDX)

Since the dawn of the web, performance has been an important factor for web development because slow speeds often lead to a loss of visitors and, ultimately, depletion in revenue for commercial sites..

Since the dawn of the web, performance has been an important factor for web development because slow speeds often lead to a loss of visitors and, ultimately, depletion in revenue for commercial sites..


Table of Contents

  • What You'll Build
  • Benefits of Gatsby.js, MDX, and Cloudinary
  • Prerequisites
  • Installation
  • Creation of Gatsby Site
  • Creation of Directories
  • Configuration of Plugins
  • Creation of Layout
  • Creation of Home Page
  • Creation of Video Component
  • Creation of MDX Files
  • Programmatic Creation of Pages
  • Configuration of Webpack
  • Posting of Content on Home Page
  • Summary

The demand for efficient web uploads brought about the rise of the JAMStack, which facilitates the design of interfaces and makes API calls to remote microservices and simple markups with JavaScript. The result? Enhanced security, reduced hosting cost, and lower requirements of programming skills for building web apps.

In the Internet, site generators abound for static, easily-deployable HTML, CSS, and JavaScript files. The evolution of those generators has seen technologies like Gatsby.js being employed for developing dynamic apps using the JAMStack, whose performance far outpaces that of static ones.


What You'll Build

This step-by-step tutorial shows you how to build and deploy a simple video blog with Gatsby.js 2.0, leverage React components in Markdown documents with MDX, and store and serve media assets with Cloudinary.


Benefits of Gatsby.js, MDX, and Cloudinary

Blogs are usually content heavy. Markdown enables easy creation of content, which is subsequently generated into HTML for the web. Gatsby is one such generator, transforming Markdown documents into HTML files that are served through dedicated routes.

Toward that end, Gatsby builds fast, static, progressive web apps with React.js components, querying data with GraphQL. In addition, Gatsby can, through plugins, pull in data from almost anywhere, including content management systems (CMSs), to populate your website.

Adding interactivity to the rather bland Markdown text would enhance the appeal. Enters MDX. With the Gatsby-MDX plugin, you can run MDX features on Gatsby sites and thus easily compose content in Markdown and build interactive user interfaces on your pages.


The Cloudinary Video Player affords you the ability to store and retrieve videos for all devices, either via a dynamic URL or through APIs. Storing videos on Cloudinary not only greatly reduces the bundle size of your apps but also ensures that those videos are served at an amazing speed and tailored for the devices in use.


Prerequisites

This tutorial requires proficiency in JavaScript.. Knowledge of React and Gatsby would be helpful but not required.


Installation

First, install Node.js and its package manager, NPM. To check if installation is complete, run this command:

npm -v && node -v

The output displays the Node.js version number.

Next, install the Gatsby-CLI tool. Gatsby ships a powerful CLI tool to help accelerate development of Gatsby apps. Type this command to install the latest stable version globally:

npm install -g gatsby-cli
Creation of Gatsby Site

Accompanying Gatsby are starters, which are templates that help you start building sites. (You can contribute starters, too!) Create a video blog using the Hello World starter. Create a new Gatsby project with:

gatsby new scotch-video-blog https://github.com/gatsbyjs/gatsby-starter-hello-world

This creates a directory with the project folder scotch-video-blog and we are ready to build out the site!

To see your Gatsby site, open your development server on port 8000 with this command:

gatsby develop

Gatsby uses GraphQL to query data. When the development server is running, GraphiQL - The GraphQL IDE (or playground as I like to call it) can be used to visualize the GraphQL queries. It runs on http://localhost:8001/___graphql.

To create a static site of just HTML, CSS and JS, run the build command:

gatsby build

Now install the other dependencies with this command:


npm install --save @mdx-js/mdx @mdx-js/tag cloudinary-core cloudinary-video-player gatsby-mdx gatsby-plugin-typography gatsby-source-filesystem jquery lodash react-typography typography typography-theme-bootstrap

Here's a description of each of the dependencies:

Below are the dependencies property values in package.json:

... "dependencies": { "@mdx-js/mdx": "^0.15.5", "@mdx-js/tag": "^0.16.1", "cloudinary-core": "^2.5.0", "cloudinary-video-player": "^1.1.1", "gatsby": "^2.0.33", "gatsby-mdx": "^0.2.0", "gatsby-plugin-react-helmet": "^3.0.4", "gatsby-plugin-typography": "^2.2.2", "gatsby-source-filesystem": "^2.0.11", "jquery": "^3.3.1", "lodash": "^4.17.11", "react": "^16.5.1", "react-dom": "^16.5.1", "react-helmet": "^5.2.0", "react-typography": "^0.16.13", "typography": "^0.16.18", "typography-theme-bootstrap": "^0.16.18" } ...
Note the version numbers of the installed packages. Problems sometimes occur with new but unstable releases.
Creation of Directories

The Gatsby Hello World starter creates a pages subdirectory in the src directory. All JavaScript files under pages are transformed to HTML pages on build, as shown in the default index.js file.

Gatsby usually creates static pages with React components Now proceed to create folders for the components, blog posts, and utilities, such as typography config, in the src directory. Run the following command to go to src and create those three folders:

Free Node eBook

Build your first Node apps and learn server-side JavaScript.
📧

cd src && mkdir components posts utils


Next, set up the basic configurations for your site. See the next section.
Configuration of Plugins

Gatsby extends its functionality with plugins and there's just about a plugin for everything! In this tutorial, you configure them in a Gatsby-recognized file named gatsby-config.js in the root directory. Proceed to create that file in the root directory of your project folder.


Typography.js

For this project, we use the gatsby-plugin-typgraphy to provide global styling. The bootstrap theme installed earlier provides the Bootstrap default font style. In gatsby-config.js export an object in the module with a plugins property, as follows:

module.exports = { plugins:[ { resolve: `gatsby-plugin-typography`, options:{ pathToConfigModule: `src/utils/typography.js` } } ] }

The above snippet uses the typography plugin and looks to the typography.js file for configuration. Specify that configuration as follows:

Go to the src/utils/ directory and create a typography.js file with the following content to create and export an instance of Typography with the Bootstrap theme:

import Typography from "typography"; import bootstrap from "typography-theme-bootstrap"; const typography = new Typography(bootstrap) export default typography

Other Plugins

In similar fashion to gatsby-plugin-typography but without the configuration, configure each installed plugins in gatsby-config.js as follows:

//gatsby-config.js module.exports = { plugins:[ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `src`, path: `${__dirname}/src/`, }, }, { resolve: `gatsby-source-filesystem`, options:{ name: `posts`, path: `${__dirname}/src/posts/` } }, { resolve: `gatsby-plugin-typography`, options:{ pathToConfigModule: `src/utils/typography.js` } }, { resolve: `gatsby-mdx`, options: { defaultLayouts: { posts: require.resolve("./src/components/layout.js"), default: require.resolve("./src/components/layout.js") } } }, ] }

This configuration points to the files in src and posts the directories respectively according to gatsby-source-filesystem. Subsequently, the appropriate transformer plugin that is introduced can make use of the sourced files. Note that, as a time saver, gatsby-mdxhas been preconfigured with the default layouts for all the MDX files in this tutorial..

Next, follow the procedure in the next section to build the layout.


Creation of Layout

One of the beauties of Gatsby is that you can create a consistent layout across all the pages with a single component. Thanks to Gatsby, which can build a default layout from the file layout.js in the src/components directory, navigation bars and footer inconsistencies are now ancient history.

Here’s what to do: In src/components, create a layout.js file and a layout.css file to style layout.js. In layout.js, write a stateless React component like this:

import React from "react" import {Link, StaticQuery, graphql} from 'gatsby' import "./layout.css" export default ({children})=> ( <StaticQuery query={graphql`query { site { siteMetadata { title } } }`} render={data => ( <div> <div className="nav"> <Link to={'/'} style={{textDecoration: 'none', color: 'inherit'}}> <h1>{data.site.siteMetadata.title}</h1> </Link> </div> <div className="child"> {children} </div> </div> )} /> )

See a mix of GraphQL there? Gatsby ships with GraphQL with which to query data. Remember that speed is key and GraphQL is known for speed. Gatsby 2.0 introduces the API StaticQuery to make data queries in static components like layouts. A similar API is PageQuery, which queries data solely in page components.

Recall that in layout.js, you imported the required modules, Link, StaticQuery, and graphql from gatsby. You also created a default export of a function that takes a children argument. With StaticQuery, you made a graphql query to fetch the site title from siteMetadata through the default query attribute.

Subsequently, the render attribute renders HTML elements with JSX. The queried data also comes into play here. Add the siteMetadata property to the gatsby-config.js file, as follows:

... siteMetadata: { title: `Scotchy-Vid-Blog`, }, ...

With the above setup, your layout is consistent across all the pages, including the header, which is sourced from siteMetadata.

Next, style the layout component in layout.css with this snippet:

.nav{ background: black; color: white; display: flex; align-items: center; justify-content: center; font-family: Arial, Helvetica, sans-serif; padding: 1% 0; } .child{ width: 60%; margin: 0 auto; max-width: 1000px; margin-top: 2%; } h1{ margin: 0; padding: 0; }

You can now import the layout into any page.


Creation of Home Page

Similar to how you configured the layout component, edit the src/pages/index.js file to import the layout component and child elements, as follows:

//index.js import React from "react" import Layout from '../components/layout' import './index.css' export default ({data}) => { return ( <Layout> <div> <header> <h2>Let's place video memes here!</h2> </header> </div> </Layout> ) }

Create a CSS file index.css in the same directory to style the homepage.

body{ margin: 0; padding: 0; } .post-item{ margin-top: 5%; } .post-title, .post-date, .post-excerpt{ margin: 10px; } .post-date{ font-size: 0.8em; font-style: italic; color: darkolivegreen; }

Restart the development server for a display of the home page:

Now that you’ve hammered together your basic home page with a working layout, create the video component. See the next section.


Creation of Video Component

A goal of this tutorial is to demonstrate how to use components in Markdown. So, create a simple react component for fetching videos that are stored in Cloudinary and then serve a video with the robust Cloudinary Video Player.

First, [create a free Cloudinary account](https://cloudinary.com/users/register/free\). Second, in the Media Library tab, upload a few videos.

Note: In this tutorial, the values of the variables, such as cloud_name and publicID, are those for my Cloudinary account. Replace those values, including the public ID of any media asset you want to use, with the ones for your account, which are displayed on the Dashboard of your account.

Third, create a file called VideoPlayer.js in the src/components directory. This is a stateful component that fetches Cloudinary videos according to their public IDs. Import all the required modules by adding this snippet to VideoPlayer.js:

import React from "react"; import "lodash/lodash.js"; import cloudinary from "cloudinary-core"; import "cloudinary-video-player/dist/cld-video-player.js" import "cloudinary-video-player/dist/cld-video-player.min.css" import "jquery/dist/jquery.js" import './videoplayer.css'

Next, create and export the component with this code:

[...] class VideoPlayer extends React.Component { componentDidMount(){ const {publicID, title, subtitle, muted} = this.props let cl = cloudinary.Cloudinary.new({cloud_name: "chuloo", secure: true}) let videoPlayer = cl.videoPlayer('cl-vp',{ loop: true, controls: true, muted: muted ? true : false, }) videoPlayer.source(publicID ? publicID: "", {info:{title: title ? title : "", subtitle: subtitle ? subtitle : ""}}) } render(){ return ( <div className="video-player"> <video autoPlay id="cl-vp"> </video> </div> ) } } export default VideoPlayer

In the componentDidMount lifecycle method, you created a Cloudinary instance with a cloud name and a video-player instance with the basic configurations to display the controls and to loop and mute the video, depending on the props received by the component.

Also, you assigned the video player a unique public ID (publicID), which is passed from props, also a title and subtitle is passed too. We then proceed to render the component in the render method before export.

In the same folder, create the imported css file videoplayer.css with:

.video-player{ display: flex; justify-content: center; margin: 5% 0; }

A complete VideoPlayercomponent is now available for use anywhere.


Creation of MDX Files

MDX enables the creation of React components in Markdown files with .mdx file formats. gatsby-mdx primarily helps you achieve that, and even processing normal .md Markdown files.

In src/posts create 4 MDX files: post01.mdx

--- title: "Simpson's Megaphone" date: "2018-12-11" --- // import VideoPlayer from "components/VideoPlayer" ## Spread Love! Supersonic Love! Got the trick yet? Wait for it and i hope, you don't have headphones on! {/_ <VideoPlayer publicID = "headphones" title = "Headphones" muted /> _/} Just so you know, this video is from Cloudinary!

post02.mdx

--- title: "Absolutely Nothing!" date: "2018-12-10" --- // import VideoPlayer from "components/VideoPlayer" ## What's for the season? When I'm asked, "are you getting me anything this Christmas?" {/_ <VideoPlayer publicID = "nothing" title = "Absolutely Nothing" subtitle = "Nothing ft. Santa" muted /> _/} Just so you know, this video is from Cloudinary!

post03.mdx

--- title: "Bedroom Magic!" date: "2018-12-09" --- // import VideoPlayer from "components/VideoPlayer" ## Trust the Process From a chase through a refining process to an interrogation! {/_ <VideoPlayer publicID = "impossible" title = "Cut the chase" subtitle = "...or not" /> _/} Just so you know, this video is pulled from cloudinary!

welcome.mdx

--- title: "Poor" date: "2018-08-10" --- // import VideoPlayer from "components/VideoPlayer" ## Rude Machines! Feeling broke or out of cash? Here's a sign that there's hope for you! {/_ <VideoPlayer publicID = "weirdatm" title = "Rude ATM" subtitle = "Take ya card!!" /> _/} Just so you know, this video is from cloudinary!

Note that in the above MDX files, you commented out the import statements and components. Omitting that step would cause Gatsby to throw an error on gatsby develop because gatsby-mdx does not support relative imports. Later in this tutorial, you will set up a webpack configuration to specify the absolute path of each of the MDX files before importing them.

You’re now ready to create pages from the four MDX files.


Programmatic Creation of Pages

Creating pages programmatically is done in the gatsby-node.js file. Follow these steps:

Step 1: Create a file called gatsby-node.js in the root directory. To programmatically create pages from MDX content, you'll use two API exported by Gatsby, onCreateNode and createPages APIs. These are used to create node fields in the GraphQL schema and create pages from GraphQL queries of the MDX content.

Step 2: Create the route node field, which is the route for each of the pages. Import the required modules and create the path in gatsby-node.js file with this code:

const componentWithMDXScope = require("gatsby-mdx/component-with-mdx-scope"); const path = require("path") const {createFilePath} = require("gatsby-source-filesystem") exports.onCreateNode = ({node, getNode, actions}) =>{ const {createNodeField} = actions if (node.internal.type === 'Mdx') { const route = createFilePath({node, getNode, basePath:'posts'}) createNodeField({ node, name: 'route', value: route }) } }

Page creation requires the scope of the MDX files, hence the import. Here, you also generated the route values from the individual file names with createFilePath from gatsby-source-filesystem.

Step 3: Restart your development server. Afterwards, open the GraphiQL interface and run a sample GraphQL query like the one below, to verify that the route fields are in place.

Perform step 4 to create pages and access them through their individual routes newly created.

*Step 4: *In gatsby-node.js , using createPages, fetch the scope, route, name, and sourceInstanceName using a GraphQL query.

exports.createPages = ({ graphql, actions }) => { const { createPage } = actions; return new Promise((resolve, reject) => { resolve( graphql( `{ allMdx { edges { node { fields { route } id parent { ... on File { name sourceInstanceName } } code { scope } } } } }` ).then(result => { if (result.errors) { console.log(result.errors); reject(result.errors); } result.data.allMdx.edges.forEach(({ node }) => { createPage({ path: node.fields.route, component: componentWithMDXScope( path.resolve("./src/components/post-layout.js"), node.code.scope ), context: { id: node.id, postRoute: node.fields.route } }); }); }) ); }); };

Here, with the data queried, you’ve created pages for each of the MDX files, specifying the path as the route and the context object, whose properties are available as page variables. You’ve also specified the component for each of the pages.

Step 5: Create a file called post-layout.js in the src/components directory to serve as the component for each of the new pages. Populate post-layout.js with this content:

import React from "react" import Layout from '../components/layout' import { graphql} from "gatsby"; import MDXRenderer from 'gatsby-mdx/mdx-renderer' export default ({data}) => { return ( <Layout> <div> <header> <h1 className="article-title">{data.mdx.frontmatter.title}</h1> </header> <div> <MDXRenderer>{data.mdx.code.body}</MDXRenderer> </div> </div> </Layout> ) } export const pageQuery = graphql`query ($postRoute: String!) { mdx(fields: {route: {eq: $postRoute}}){ frontmatter{ title } fields{ route } rawBody internal{ content } code{ body scope } } }`

Here, you rendered the content of the MDX filesby the means of MDXRenderer. Notice how you queried with pageQuery each of the required data points. Also, the page's route is determined from the context passed to the page.

Step 6: Restart your development server and, as a test, visit a wrong page, say, localhost:8000/mjnb. Besides the error message, also displayed are all the available pages, including those that you created earlier.

The building blocks for your video blog are now all set.


Configuration of Webpack

Because Gatsby-mdx does not support relative paths, you'll have to make a webpack config in gatsby-node.js. Also, the cld-video-player file contains the window object which throws an error during a build (Gatsby uses node.js during builds in which the window browser object is absent). In light of all that, call the onCreateWebpackConfig API in gatsby-node.js to get around the errors.

Add the following code to gatsby-node.js:

// gatsby-node.js exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => { actions.setWebpackConfig({ resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], }, }) if(stage === "build-html"){ actions.setWebpackConfig({ module:{ rules: [ { test: /cld-video-player/, use: loaders.null() } ] } }) } }

The above snippet excludes the cld-video-player module during the build process and only runs in the browser. This same principle applies to all browser-dependent modules.

With the preceding setup, you can delete the comments in the MDX files for importing the videoplayer component.


Posting of Content on Home Page

Now that all the pages with video content are working, populate the individual links on the home page (the index.js file). By querying all the MDX files with GraphQL, you can obtain enough data for the home page. In the src/pages/index.js file, add a page query to the component:

export const query = graphql`query PageList{ allMdx(sort: { fields: [frontmatter___date], order: DESC }){ edges{ node{ fields { route } frontmatter{ title date } timeToRead excerpt } } } }`

With the data for all the MDX files in descending order, update the default export of the component to make use of the data:

[...] export default ({data}) => { const posts = data.allMdx.edges return ( <Layout> <div> <header> <h2>Let's place video memes here!</h2> </header> <div> {posts.map(({node}, index)=> ( <Link to={node.fields.route} style={{textDecoration:'none', color: 'inherit'}} key={index}> <div className="post-item"> <h3 className="post-title">{node.frontmatter.title}</h3> <p className="post-excerpt">{node.excerpt}</p> <p className="post-date">{node.frontmatter.date}</p> </div> </Link> ))} </div> </div> </Layout> ) } [...]

Finally, restart your development server for a display of the the completed website.


Summary

You've now learned how to create video blogs having React components in Markdown files and also how to programmatically create pages from those files. The development opportunities with this process are limitless because you can make API calls within Markdown pages and make use of the data fetched on the DOM.

Run a build version of this tutorial. As reference, see the deployed version to Netlify and the repository.

Is this tutorial helpful to you? Do tell us your take in the Comments section below. We would also appreciate your sharing this post as you deem appropriate.

Understand and Use Pipe Function in JavaScript

Understand and Use Pipe Function in JavaScript

In this post, I will talk about pipe or pipeline which is important when it comes to functional programming and how to write them. Functional Programming and the Pipe Function in JavaScript

When you want to do something but it’s quite complex to be in one function, how do you solve this problem? What if you want to separate the function into many pieces but you want to do something more elegantly?

There’s an interesting proposal on TC39 GitHub at stage 1. Although it’s still unsettled as it’s mentioning, the idea of the proposal is quite fun to take a look at.

In this post, I will talk about pipe or pipeline which is important when it comes to functional programming and how to write them.

Before Reading

This post is under the premise that you are aware of JavaScript basics and some of the built-in methods in the Array.prototype.

If you aren’t familiar with those, I recommend you read the documentation about them. And, the way I make pipeline functions might be different from other pipelines in the JavaScript world. But the core concept wouldn’t be so different.

  • Reduce in MDN
  • Arrow function in MDN

Plus, I will explain pipe and how to create it step-by-step for people who have no idea about it.

Definition of Pipeline in JavaScript

So, first things first, let’s talk about what a pipe is in JavaScript. What do you think of when you hear “pipe”? Yes, you’re right. A bunch of pipes on the ceiling for gas or something, or under the ground for water.

What those pipes are for is to be a tunnel for resources to go from A to B. It doesn’t do anything to the resources except for being the space for the resources to pass through.

The idea of pipe functions in JavaScript came from the pipeline in the real world.

Pure Functions

This is a really important concept for pipe. What is a pure function? A pure function is a function that does the things below.

  1. Returns the same output with the same input.
  2. Doesn’t change any values out of its function scope.

But then why is a pure function important for pipe? As I explained above, pipe delivers a given value to the next pipe. But if the function could return a different value, then the next function in the pipeline can’t assure the stable result.

Without Pipe

OK. Let’s take a look at a simple example.

const addFour = a => a + 4;
const minusFive = a => a - 5;

const nine = addFour(5);
const four = minusFive(nine);

We have two functions, addFour and minusFive. We can easily get a return from each function. And when we want to add and subtract numbers at once, we can do this:

addFour(minusFive(0)); // -1

Then, multiply by 10.

multiplyByTen(addFour(minusFive(0))); // -10

But since we don’t like a negative number, we want to change it to the positive.

Math.abs(multiplyByTen(addFour(minusFive(0)))); 10

What do you think of this process? Doesn’t this look quite messy? Especially as there are so many closing-parentheses at the end of the statement.

Of course, it doesn’t cause any programmatic errors or problems. But this may reduce the readability of codes.

How To Write Pipe

To make pipe work, you should make the functions so they run consecutively. In the Array class, there’s a very useful method for this, Array.prototype.reduce. What reduce does is to loop over an array and to make one compact result.

For example, if you want to get the total score of all students, you may write your function like this, below:

const scores = [90, 100, 40, 50, 10];
let total = 0;

scores.forEach(score => total += score); 
console.log(total); // 290

This example used forEach because map or filter produces a new array. But this example has a problem, because total has to be declared with let, since total has been changed in the loop of forEach.

In contrast, however, reduce returns a value that has been calculated over the loop.

const scores = [90, 100, 40, 50, 10];
const total = scores.reduce((acc, cur) => acc + cur, 0);
console.log(total); // 290

Step 1. Put all of the functions that we want to enqueue into reduce

const pipe = (funcs) => {
  funcs.reduce((acc, cur) => {
    ...
  });
}

OK, now what? Each argument of func.reduce has to return the values that the next function requires.

From the perspective of the next function, the parameter that should be passed into it should come from the previous call of reduce. In reduce, acc is the return value and cur is the current value of an array.

Good. Then, let’s change the names of parameters for better readability.

funcs.reduce((res, func) => {
  ...
});

Step 2. Fill the body part

Now you know each return value will be the passed argument for the next function. To make this happen, we should run the function with the parameter, res.

funcs.reduce((res, func) => {
  return func(res);
});

But, this is still quite strange. Why? Even if the functions will be executed properly with the parameter they need, what if the very first function also wants to take the parameter?

In this example, since initialValue of reduce doesn’t exist, the first element of an array will be used as initialValue and this will be a function and it will be omitted from execution.

Then, the second element of an array will be used as the first cur of the loop.

So, you need to set the initialValue for the first function in the array, but as what? You didn’t take any values into the pipe.

Step 3. Set the InitialValue

We will take the value for the function.

const pipe = (funcs, v) => {
  funcs.reduce((res, func) => {
    return func(res);
  }, v);
};

Now, let’s try to run this function to see if it works as expected.

const addFive = v => v + 5;

pipe([
  add,
  console.log
], 5); 
// 10

It works! But, there’s actually a problem, because pipe only takes an array. So, you can’t run the pipe function like this, below:

pipe(add, 5);
//   ~~~
// Uncaught TypeEror: funcs.reduce is not a function

Step 4. Generalization

It seems like it’d be better if pipe can take a single function as well. At this point, I’m going to use the rest parameter.

What the rest parameter does is to allow a function to take any parameters as an array.

// Rest parameter must be last formal parameter !!
const pipe = (v, ...funcs) => {
  funcs.reduce((res, func) => {
    return func(res);
  }, v);
};

Now, let’s see if it works.

const subtract = v => console.log(v - 5);

pipe(10, subtract); // 5

It works, but now the value passed into the pipe for the first parameter of the first call should be the first parameter. Because we’ve changed the order of parameters due to the rule of the rest parameter.

I don’t like this. Then, how can we fix this?

We will use a closure. A closure is a function that returns a reference to the outer function that is already finished executing. If you aren’t familiar with closure, you might want to check out my previous post.

So, finally, the pipe can be changed like this:

const pipe = (...funcs) => v => {
  funcs.reduce((res, func) => {
    return func(res);
  }, v);
};

pipe(add)(5) // 10

Now, the pipe returns another function that takes v. Until the return function takes v, it doesn’t fulfil reduce. As the last step, let’s confirm if it works properly.

Final step: Testing
const minusFive = v => v - 5;
const addFour = v => v + 4;
const multiplyByTen = v => v * 10;

pipe(
  minusFive,
  addFour,
  multiplyByTen,
  Math.abs,
  console.log
)(0); // 10

// it works !
Conclusion

pipe is one of the very useful functions in functional programming. It reduces the complexity of reading your codes and, in contrast, increases the readability.

The important thing to remember is that each function that will be used with pipe should be a pure function.

Thank you for reading, Please share if you liked it!

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Watch this JavaScript tutorial for beginners to learn JavaScript programming from scratch. 👍

⭐️Course Contents⭐️

01 | Introduction

Get an introduction from Bob, as he kicks off the course, sets expectations, and gives you a little guidance for the road ahead.

02 | Setting Up the Development Environment

See how to install Node and Visual Studio Code, and learn why you need each. Watch as Bob writes a first tiny line of code to make sure that the installation is ready.

03 | Basic JavaScript Syntax

Hear about the basics of the JavaScript syntax, including how JavaScript is executed, how to create a properly formed statement, and more.

04 | Variables

Learn what variables are and how to declare, initialize, set, and get values from them.

05 | Data Types

JavaScript works with data types differently than other programming languages do. Learn from Bob as he explains some of the most basic data types and how to determine the type held by a variable.

06 | Type Coercion and Conversion

Sometimes you need to explicitly convert the data type of a value into a different data type. Sometimes JavaScript will do this automatically for you. Bob explains how and why this happens.

07 | Expressions and Operators

Learn how to spot a well-formed expression and how to compose expressions through the combination of operators and operands.

08 | Arrays

Watch as Bob demonstrates how to use arrays, how to add/remove elements of an array, how to access elements of an array using the index, how to get the number of elements in an array, and more.

09 | Function Declaration

Get an introduction to functions, as Bob shows you one way to define a function, how to call the function, how to pass parameters into a function, how to return values from a function, and more.

10 | Function Expressions

Sometimes a function declaration is more than you need. Get details in this lesson, as Bob demonstrates how to use a function expression and how to create an immediately invoked function expression.

11 | Decision Statements

Learn how to add logic to your applications by testing conditions using if / else statements, switch / case statements, and the ternary operator.

12 | Iteration Statements

Watch as Bob introduces the For and While statements, which enable you to loop through lists of values and perform operations on them.

13 | Basics of Scope

Hear an explanation of the notion of the lifetime of variables and their reach into other code blocks, in this discussion of scope.

14 | Returning Functions from Functions

As a building block toward a more sophisticated approach to building JavaScript applications, see how you can return functions from functions.

15 | Object Literals

Objects contain properties and functions that describe attributes of the object and its behavior, respectively. Watch as Bob demonstrates how to create object literals.

16 | Module Pattern and Revealing Module Pattern

Learn how to introduce variables and functions without leaving an unnecessarily large footprint on the global scope.

17 | Closures

Closures allow developers to bind functions to their execution context, including variables, so you can build specialized versions of functions. Learn how closures work and how to create them.

18 | this Keyword

Get the details on the "this" keyword, which causes a lot of confusion for JavaScript developers. Listen as Bob explains what this mysterious object is and how to bend it to your will.

19 | Destructuring

See how to use destructuring, a new feature in JavaScript that allows you to unpack array elements or object properties in a concise syntax.

20 | String Template Literals

Learn about the new string template literal syntax to enable string interpolation, multi-line string formatting, and more.

21 | Regular Expressions

Working with string data, Bob explains how use regular expressions to determine such things as whether a string matches a specific pattern or whether an instance of the pattern exists in a string.

22 | Built-In Natives

Join Bob as he examines native, built-in JavaScript functions that return objects that box the primitive types in order to provide additional helper methods on your values.

23 | Constructor Function Calls with the new Keyword

Learn how constructor functions work, see how to make key distinctions in what they are, and find out why they’re helpful.

24 | Objects and the Prototype Chain

Moving past the absolute beginner matter, listen in as Bob explains how objects work in JavaScript and how you can create an object that is linked to another object.

25 | JavaScript Classes

Bob demonstrates how “syntactic sugar” works on top of the existing functions and prototype chaining to help JavaScript resemble more traditional object-oriented programming languages.

26 | Arrow Functions

The latest version of JavaScript added arrow functions, a shorthand syntax for creating functions. Watch as Bob demonstrates how to create them and shows where they’re useful.

27 | Truthy and Falsy Values

Listen is as Bob circles back to topics that are important (but didn’t easily fit into earlier topics) and looks at the odd way in which JavaScript evaluates certain expressions as truthy and falsy.

28 | null Type

Similar to the undefined primitive type, the null type represents a variable that has no reference to an object when one was expected. Hear an explanation of how and why we should think about nulls.

29 | Date Objects

No discussion of JavaScript would be complete without understanding the Date built-in native function which provides properties and methods for working with dates and times.

30 | String Methods

The built-in native String function provides several very useful methods for manipulating and evaluating strings. Watch Bob demonstrate how to use a few of the most useful ones.

31 | Array Methods

We’ve worked with arrays throughout this course. Now Bob takes a few minutes to show you some of the most useful methods provided by the Array built-in native function.

32 | Error Handling with Try Catch

See how to wrap a try/catch/finally statement around potentially problematic code to anticipate everything that could go wrong with it, and learn other error-handling tips.

33 | Understanding the Document Object Model

Watch Bob examine the web browser environment and how it creates an object graph of nodes that represent elements, their attributes, and text, plus how to properly attach your code to an HTML page.

34 | Working with DOM Nodes

Continuing from the previous video, Bob demonstrates a slightly more compelling example that helps us understand how to manipulate, create, and delete element nodes and attribute nodes.

35 | Course Conclusion

In this final video, Bob briefly adds some closing comments and well wishes. You can also optionally complete a survey to provide insight into how Microsoft can improve this course.

Thanks for watching

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

20 Things to Learn and Effective tips to becoming JavaScript Master

20 Things to Learn and Effective tips to becoming JavaScript Master

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you. In this post, we will for you 20 things to learn and Simple Effective tips on the way to becoming a JavaScript Master

10 THINGS TO LEARN

I guess you are a web developer. Hopefully you are doing fine and you have a great job, maybe you are even self-employed or working as a freelancer. Maybe you are just starting out as a web developer, maybe you have been working as a programmer for a longer period already.

However comfortable you are with JavaScript, it is always good to get a refresher on some topics to read up about or get them on the radar in the first place. Here are 10 things you definitely have to learn before you can call yourself a master in JavaScript.

1. Control Flow

Probably the most basic topic on the list. One of the most important, maybe the most important one. If you do not know how to proceed with your code, you will have a hard time. Knowing the ins and outs of basic control flow is definitely a must.

  • if else — If you don’t know these, how did you write code before?
  • switch — is basically if else in a more eloquent way, use it as soon as you have multiple of different cases.
  • for — Do not repeat yourself, this is what loops are for. Besides the normalfor -loop for of and for in come in very handy. The big advantage of for -loops is that they are blocking, so you can use async await in them.
  • Advanced conditionals — Using the ternary and logical operators can make your life a lot easier, especially when you try to do things inline, meaning that you don’t want to save values to use them later. Example:
// ternary
console.log(new Date().getHours() < 12 ? 'Good Morning!' : 'Time for a siesta')
// logical operators
const isJsMaster = prompt('Are you a JavaScript master?') === 'true'
console.log(isJsMaster && 'proficient coder')

2. Frontend Framework

The big three are React.js, Angular and Vue.js. If you are looking for a job nowadays, you will almost always have one of those listed as a prerequisite. Even if they change quite quickly, it is important to grasp the general concept of those to understand how applications work. Also, it is just easier to write apps that way. If you haven’t decided which train you want to jump on, my suggestions is React.js. I have been working with it for the last couple of years and did not regret my decision.

3. Asynchronity

This is a very important aspect of JavaScript, Either you are fetching data from the backend or you are processing requests asynchronously in the backend itself. In pretty much all usecases, you will encounter asynchronity and its caveats. If you have no idea what that is, you will probably get a weird error, which you will try to fix for a couple of hours. If you know what it is, but you don’t really know what to do about it, you will end up in callback-hell. The better approach is to use promises and/or async await in your apps.

4. Node.js / Express

Even as a frontend developer, you should know the basics of node.js. Ideally, you would also know how to spin up a simple express server and add some routes or change existing ones. JavaScript is great for writing scripts to help you automate a lot of tasks. Therefore, knowing how to read files, work with filepaths or buffers gives you a good toolset to build anything.

You may also like: Best Design Patterns for writing JavaScript Web applications

5. Error handling

This took a while for me. It does not matter if you are working on frontend or backend, the first year or so, you will probably default to console.log or maybe console.error for ‘handling’ errors. To write good applications, you definitely have to change that and replace your lazy logs with nicely handled errors. You may want to check out how to build your own Error constructor and how to catch them correctly, as well as showing the user what the actual problem is.

6. Data Models

Similar to moving through your application continuously, you have to decide where to group specific information chunks and where to keep them separate. This does not only apply to building database models, but also function parameters and objects or variables. Example:

const calcShape = (width, height, depth, color, angle) => {...}
const calcShape = ({width, height, depth, color, angle}) => {...}

7. DOM Manipulation

This is an interesting topic. Normally it is somewhat left out in the day today life as a developer. Maybe you learned jQuery and never felt the need to pick up some native DOM manipulation skills, maybe you are just using a frontend framework, where there is rarely a need for custom DOM manipulation. However, I think this is a crucial part of understanding JavaScript, at least in the frontend. Knowing how the DOM works and how to access elements gives you a deep understanding of how websites work. In addition, there will be the point where you have to do some custom DOM manipulation, even when you use modern frontend frameworks, and you definitely do not want to put jQuery in your package.json just to access an element.

8. Functional Approach

There is an everlasting debate about functional vs. object-oriented programming. You probably can achieve the same thing with both of the approaches. In JavaScript, it is even easier, you have both of the approaches available. Libraries like lodash give you a really nice collection of tools for building applications with a functional approach. Nowadays, it is not even necessary to use external libraries any more. A lot of the most important functions have been implemented in the official JavaScript specification. You definitely should know how to use map reduce filter forEach and find.

9. Object Oriented Approach

Similar to the functional approach, you also have to get familiar with object oriented JavaScript, if you want to master it. I neglected that part for a long time in my career and just worked my way through with a workaround, but sometimes it is definitely better to use objects/classes and instances to implement specific functionality. Classes are widely used in React, MobX or custom constructors.

10. Bundling / Transpilation

Unfortunately, this is a big part of web development. On the one hand I should not say unfortunate, because it is great to be able to write code with all the newest features. On the other hand, the reason why I’m saying that is that we always have to keep in mind that there’s older browsers around that may not support these features, therefore we have to transpile our code into something else that the old browsers understand. If you work with node.js, you will probably have less exposure to transpiling your code. The de-facto standard for transpilation is babel.js, so get familiar with it. As for bundling your code and tying everything together, you have a couple of options. Webpack was the dominant player for a long time. Some time ago, parcel popped up out of nowhere and is now my preferred solution, since it is so performant and easy to configure, although not perfect.

This is not specific to JavaScript, but incredibly helpful in a lot of use cases. Just as confusing as well. Getting to know the syntax of Regular Expressions definitely takes some time and remembering all of the different options is impossible.

10 SIMPLE and EFECTIVE TIPS

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you.

Why JavaScript?

Javascript is the scripting language of the internet and one of the most essential web technologies along with HTML and CSS. It’s a high-level, interpreted programming language that conforms to the ECMAScript specification. In more simplistic terms, it’s what allows you to implement and display complex things on your webpage, to create content, to animate images and tons of other amazing possibilities with just a few lines of code.

There’re plenty of reasons to learn this wonderful programming language. The most important one is the fact that JavaScript runs everything and everywhere. Most of the prominent websites are built on the backbone of JavaScript while currently there are more than 3 billion devices be it Smartphones or desktops. JavaScript went through a massive surge of popularity and quickly become the most dominant language in the world of software. In light of this, it’s obvious that Javascript skills are in high demand by companies everywhere. For all these reasons and more, it’s lucrative to have JavaScript skills on your resume.

Why is it challenging?

Learning JavaScript is easier said than done. Newcomers often run into similar kinds of problems such as difficulties in understanding confusing concepts. Not only that, but JavaScript also has an ever-changing tooling landscape one that makes it even far more grueling to understand. It’s hard to find the motivation to complete a demanding task such as this. JavaScript is also a vigorously un-typed language which means that the same thing in one code can easily mean something different depending on the context and medium. It also is extremely hard to debug due to a non-existent support system for different classes.

Tips for JavaScript Beginner

So the question is how to learn JavaScript? Similar to every complicated thing in life, you can learn JavaScript coding through constant practice and by never giving up. To help you in this task, we have written down the best way of learning this skill just for you! Try to follow these tips to enhance your learning experience.

1. Keep experimenting & Interact with veterans

Find and make your own way to solve problems related to JavaScript. Keep experimenting with the problems and what you have learned so far. Also, do interact with the veterans as the large community lead to more support and help you’ll be able to receive. Fortunately, JavaScript has one of the largest internet communities that is all about giving and receiving help and exploring the world of JavaScript. Take advantage of that! Meet up with the experts to not only motivate yourself to study but to learn as well. You might even be offered a mentorship! By being a part of a community, you’ll also be able to keep up to date with new, innovative tools!

2. Do not rush! Go step by step

I know it’s tempting to move on immediately once you understand a concept, but don’t! Instead, play with what you have learned, get comfortable and even combine it with the previous lessons. Start from beginner’s level and cover all the topics from tutorials, check resources, implement what you have learned and when you are finally confident of your beginner level skills, then move on to the intermediate level and after that, to advance level. By limiting the learning content and keeping in touch with the previous lessons, you’ll be able to retain the material in your head and find it easier to remember key concepts. The process seems long for sure but it actually takes far less time since you don’t have to keep revising and is actually quite fun. There’s really nothing that you cannot do with JavaScript in regards to web development.

3. Look out for JavaScript Resources

The internet has millions of sources available for you to use. Take “JavaScript: The Definitive Guide” by David Flanagan. It’s a book that has been forever considered a bible for JavaScript programmers across the world. In it is a comprehensive guide that is well-organized and detailed for new programmers to learn and old programmers to revise. Another book that you can read is “You Don’t Know JS: Up and Going” by Kyle Simpson which provides the necessary background for those with limited knowledge about programming. The entire series introduces more complex and harder parts of the JavaScript language as you read on one book at a time. Furthermore, there are tons of articles, blog posts and even YouTube videos available for reference. Don’t waste these valuable resources!

You may also like: Keeping your JavaScript code clean forever and scalable

4. Right attitude

The first thing you need to do is to go with the right attitude to learn JavaScript. Learning JavaScript is going to become needlessly more bothersome if you approach it with the wrong mindset. Trying to learn it with an “I need to get this over” mindset is not going to take you anywhere. It’s a huge struggle to face and you truly have to be passionate about code to learn it. Not only that, you need to remind yourself to have fun with what you’re learning as JavaScript code is capable of astonishing things once you get the hang of it.

5. Start Slowly

A mistake many beginners make is that they directly start working on frameworks such as jQuery, AngularJS, Backbone, etc. You should never do it. Instead, you should start working on DataTypes and in-built methods. After getting enough of the fundamentals, you can try NodeJS. Trust me, NodeJS is very simple, just a JavaScript code backed up with inbuilt libraries. Then, you can try frameworks.

6. Find the perfect editor for JavaScript

You can’t code without a text editor. Fortunately, you have tons of options to choose from. To write JavaScript code, you can either use your Windows notepad or even download programs such as Notepad++ or Visual Studio Code. Either way, after going through all possible editors, choose the one that you’re most comfortable to work on as this is where you’ll be spending most of your time. Also when you’re starting out, it’s essential to choose an editor that has a simplistic interface and will support you as a beginner.

7. JavaScript Tutorials!

If you search the web for JavaScript tutorials, there are a vast number of tutorials available online on sites such as CodeAcademy, FreeCodeCamp, etc. If you’re a beginner then you should start from beginner level JavaScript tutorials and then move on to intermediate and advanced level. Tutorials are like doing grammar exercises and the sites with JavaScript tutorials are ideal for learning the basics and getting used to the syntax. Learning JavaScript is no different than learning French or Spanish. It takes time.

8. Start Ajax and Async after getting a hang of the basics

After you have spent quite a lot of time on JavaScript, start working on Ajax and Async concepts. Learn how to use different functions on JavaScript and use classes as well. All of these things take quite a lot of time to master but trust me; all your hard work will surely be rewarded.

9. Challenge yourself! Explore JavaScript and learn

When it comes to learning JavaScript, there is always something you can learn as it is a never-ending process. A lot of people end up never improving their JavaScript coding by spending too much time only doing what they are confident about. Make sure that you’re not one of them. Every time you finish a lesson, ask yourself if you have learned something you didn’t know before. That is the key to success. Be mindful of what you want to learn or improve your knowledge of. Make sure that you’re challenging yourself and growing as a developer instead of conforming to a single comfort zone.

10. Keep yourself up to date and be prepared

JavaScript isn’t an easy skill to learn. If it was, it wouldn’t be held with the same reverence as it is in the labor market now. You need to understand the fact that learning JavaScript would require a huge amount of time and dedication. It’s not going to be an easy road. Not only is JavaScript already a complex and intricate skill to master, but it is also a growing field which would require you to stay updated with the new web development practices. Prepare yourself that it’s going to consume a majority of your time. Be patient too. You’re not going to learn JavaScript in a month and maybe not even in a year. All the time spent is going to be grilling, demanding but remember that it will also be completely worth the trouble.

BONUS

Learning JavaScript is constant work and quite difficult but with the right attitude and determination, learning it can be an extremely satisfying experience. All you need is passion and a hunger to learn. Hopefully, with the above-mentioned tips, as well as the other brilliant and detailed materials available online, you’ll be able to grasp JavaScript as quickly as possible while also having a great enjoyable ride.

Hopefully you know all of the topics listed above already. If not, put in the work and try to become a master in JavaScript! It is definitely worth it. Remember that practicing is everything when it comes to coding, so even if you are not familiar with these concepts or know them but you don’t really know how to apply them, it will come in the future.

What do you think about the list? Is something missing? Do you think other topics are more important when coding? Let me know in the comments!

Thank for visiting and reading this post! I'm highly appreciate your actions! Please share if you liked it!