JavaScript Functional Programming Explained: Fusion & Transduction

JavaScript Functional Programming Explained: Fusion & Transduction

Fusion and transduction are probably the most “blow-my-mind” practical tools I’ve picked up in my time studying Functional Programming.

Fusion and transduction are probably the most “blow-my-mind” practical tools I’ve picked up in my time studying Functional Programming.

They’re not tools I use every day, nor are they strictly ever necessary…But, they completely changed the way I think about programming, modularity, and abstraction in software engineering, permanently, and for the better.

And to be clear, that’s really the point of both this article in particular, and series in general: Not to evangelize FP, offer a silver bullet, or illuminate some magic secret sauce that’s “better” than what you do now. Rather, the point is to shed light on different ways of thinking about programming, and broaden your sense of possible solutions to everyday problems.

Table of Contents

These aren’t easy techniques to use fluently, and it’ll probably take some time, tinkering, and deliberate practice to fully comprehend what’s going on here. This isn’t a read-and-grok concept: For most, it’s an entirely new level of abstraction.

But, if you put in the time, you might just come out with the sharpest sense of abstractions around functions that you’ve ever had.

In other words: This is going to make you a helluva lot smarter, if you put in the work.

If that sounds like your bag…Let’s get straight to it.

A Quick Example

Recall the definition of pure functions as functions which have no side effects, and always returns the same value for any given input.

Since pure functions always return the same value for a given input1, we can safely pass their return values directly to

This enables such niceties as:

// niceties
colorBackground(wrapWith(makeHeading(createTitle(movie))), 'div')), 'papayawhip')

Here, we use makeHeading to create a string heading out of movie; use this string to create a new heading (makeHeading delegates to document.createElement); wrap this heading in a div; and finally, call colorBackground, which updates the element’s styling to set a background of papayawhip…Which is my favorite flavor of CSS.

Let’s be explicit about the composition at work in this snippet.

At each step of the pipeline, a function accepts an input, and returns an output, which the input determines completely.

More formally: At each step, we add another referentially transparent function to the pipeline.

Yet more formally: papayaWhipHeading is a composition of referentially transparent functions.

It’s worth pointing out that a functional eye might spot the below possibility, as well.

…But you’re not here for illustrative-yet-contrived examples.

You’re here to learn about fusion.

And I’m here to talk about it.

So…Let’s dash through the rest of those prerequisites, and look at chaining Array methods, next.

Chaining map and filter expressions

One of the nicer features of map is that it automatically returns an array with its results.

const capitalized = ["where's", 'waldo'].map(function(word) {
  return word.toUpperCase();
});

console.log(capitalized); // ['WHERE\'S', 'WALDO']

Of course, there’s nothing particularly special about capitalized. It has all the same methods any other array does.

Since map and filter return arrays, we can chain calls to either method directly to their return values.

const screwVowels = function(word) {
  return word.replace(/[aeiuo]/gi, '');
};

// Calling map on the result of calling map

const capitalizedTermsWithoutVowels = ["where's", 'waldo']
  .map(String.prototype.toUpperCase)
  .map(screwVowels);

This isn’t a particularly dramatic result: Chained array methods like this are common in JS-land. But, it merits attention for its leading to code like the below:

// Retrieve a series of 'posts' from JSON Placeholder (for fake demonstration data)
// GET data
fetch('https://jsonplaceholder.typicode.com/posts')
  // Extract POST data from response
  .then(data => data.json())
  // This callback contains the code you should focus on--the above is boilerplate
  .then(data => {
    // filter for posts by user with userId == 1
    const sluglines = data
      .filter(post => post.userId == 1)
      // Extract only post and body properties
      .map(post => {
        const extracted = {
          body: post.body,
          title: post.title
        };

        return extracted;
      })
      // Truncate "body" to first 17 characters, and add 3-character ellipsis
      .map(extracted => {
        extracted.body = extracted.body.substring(0, 17) + '...';
        return extracted;
      })
      // Capitalize title
      .map(extracted => {
        extracted.title = extracted.title.toUpperCase();
        return extracted;
      })
      // Create sluglines
      .map(extracted => {
        return `${extracted.title}\n${extracted.body}`;
      });
  });

This is maybe a few more map calls than is common, sure…But, consider map alongside filter, and this style becomes a lot more believable.

Using simple, “single-purpose” callbacks in sequential calls to map and filter lets us write simpler code, at the cost of overhead due to function invocation and the requirement for “single-purpose” callbacks.

We also enjoy the benefi of immutability, as map and filter don’t modify the array you call them on. Rather, they create new arrays each time.

This lets us avoid confusion due to subtle side effects, and preserves the integrity of our initial data source, allowing us to pass it to multiple processing pipelines without issue.

Intermediate Arrays

On the other hand, allocating a whole new array on every invocation of map or filter seems…A little heavy-handed.

The sequence of calls we made above feels a bit “heavy-handed”, because we only care about the array we get after we make all of our calls to map and filter. The intermediate arrays we generate along the way are throwaways.

…Literally. We create them for the sole purpose of providing the next function in the chain with data in the format it expects. We only hang on to the last array we generate. The JavaScript engine eventually garbage collects the intermediate arrays that we built up but didn’t need.

If you’re using this style of programming to process large lists, this can lead to considerable memory overhead.

In other words: We’re trading memory and some incidental code complexity for testability and readability.

Eliminating Intermediate Arrays

For simplicity, let’s consider a sequence of calls to map.

// See bottom of snippet for `users` list
users
  // Extract important information...
  .map(function (user) {
      // Destructuring: https://jsonplaceholder.typicode.com/users
      return { name, username, email, website } = user
  })
  // Build string... 
  .map(function (reducedUserData) {
    // New object only has user's name, username, email, and website
    // Let's reformat this data for our component
    const { name, username, email, website } = reduceduserdata
    const displayname = `${username} (${name})`
    const contact = `${website} (${email})`

    // Build the string want to drop into our UserCard component
    return `${displayName}\n${contact}`
  })
  // Build components...
  .map(function (displayString) {
      return UserCardComponent(displayString)
  })

// Hoisting so we can keep the important part of this snippet at the top
var users = [
    {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "[email protected]",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    }
  }
]

To restate the problem: This produces an intermediate, “throwaway” array with every invocation of map.

This implies we don’t allocate intermediate arrays if we can find a way to execute all of our processing logic, but only invoke map once.

One way to get away with a single call to map is to do all of our work inside of a single callback.

const userCards = users.map(function (user) {
    // Destructure user we're interested in...
    const { name, username, email, website } = user

    const displayName = `${username} (${name})`
    const contact = `${website} (${email})`

    // Create display string for our component...
    const displayString = `${displayName}\n${contact}`

    // Build/return UserCard
    return UserCard(displayString)
})

This eliminates intermediate arrays…But, this is a step backwards. Throwing everything into a single callback loses the readability and testability benefits that motivated sequenced calls to map in the first place.

One way to improve the readability of this version is to extract the callbacks into their own functions, and use them within the call to map, rather than the literal function declarations.

const extractUserData = function (user) {
    return { name, username, email, website } = user
}

const buildDisplayString = function (userData) {
    const { name, username, email, website } = reducedUserData
    const displayName = `${username} (${name})`
    const contact = `${website} (${email})`

    return `${displayName}\n${contact}`
}

const userCards = users.map(function (user) {
    const adjustedUserData = extractUserData(user)
    const displayString = buildDisplayString(adjustedUserData)
    const userCard = UserCardComponent(displayString)

    return userCard
})

This is logically equivalent to what we started with, due to referential transparency (!). But, it’s definitely easier to read, and arguably easier to test.

The real victory here is that this version makes the structure of our processing logic much clearer: This should be ringing bells—sounds like function composition, doesn’t it?

We can go one step further. Instead of saving the result of each function invocation to a variable, we can simply pass the result of each call directly to the next function in the sequence..

So…How about:

const userCards = users.map(function (user) {
    const userCard = UserCardComponent(buildDisplayString(extractUserData(user)))
    return userCard
})

…And, because I’m vain and like my code pretty and terse:

const userCards = 
  users.map(user => UserCardComponent(buildDisplayString(extractUserData(user))))

Composition & Fusion

This restores all of the testability, and some of the readability, of our original chain of map calls.

And, since we’ve managed to express this transformation with only a single call to map, we’ve eliminated the memory overhead imposed by intermediate arrays.

We did this by converting our sequence of calls to map, each of which received a “single-purpose” callback, into a single call to map, in which we use a composition of those callbacks.

This process is called fusion, and allows us to avoid the overhead of intermediate arrays while enjoying the testability and readability benefits of sequenced calls to map.

Explicit is better than implicit. ~ The Zen of Python
One last improvement. Let’s take a cue from that other language, and be explicit about what we’re doing.

const R = require('ramda');

// Use composition to use "single-purpose" callbacks to define a single transformation function
const buildUsercard = R.compose(UserCardComponent, buildDisplayString, extractUserData)

// Generate our list of user components
const userCards = users.map(buildUserCard)

We can write a helper to make this even cleaner.

const R = require('ramda')

const fuse = (list, functions) => list.map(R.compose(...functions))

// Then...
const userCards = fuse(
    // list to transform
    users, 
    // functions to apply
    [UserCardComponent, buildDisplayString, extractUserData]
)

It works with filter, too.

//TODO: Example with filter

It’s like having your cake and eating it, too.

…Except this cake improves your memory profile.

Some cake.

Meltdown

If you’re like me, this is the part where you start using map and filter just everywhere.

Even stuff you probably shouldn’t use it for.

Just for the excuse to fuse everything in sight.

But, the high doesn’t last long with this one. Check this:

users
  // Today, I've decided I hate the letter a
  .filter(function (user) {
      return user.name[0].toLowerCase() == 'a'
  })
  .map(function (user) {
      const { name, email } = user
      return `${name}'s email address is: ${email}.`
  })

Fusion works fine with a sequence of map calls. It works just as well with a sequence of calls to filter.

Unfortunately, it breaks with sequential calls involving both methods. Fusion only works for sequenced calls to one of these methods.

That’s because they interpret the return values of their callbacks differently. map takes the return value and pushes it into an array, regardless as to what it is.

filter, on the other hand, interprets the truthiness of the callback’s return value. If the callback returns true for an element, it keeps that element. Otherwise, it throws it out.

Fusion doesn’t work because there’s no way to tell the fused function which callbacks should be used as filters, and which should be used as simple transformations.

In other words: This approach to fusion only works in the (very) special case of a sequence of calls to map and filter.

So…Game over?

Transduction

As we’ve seen, fusion only works for a series of calls only involving map, or only involving filter.

This isn’t very helpful in practice, where we’ll typically invoke both.

If you tear your hair out about it long enough, you’ll realize that there’s a trick. Recall that we were able to express map and filter in terms of reduce.

// Expressing `map` in terms of `reduce`
const map = (list, mapFunction) => {
    const output = list.reduce((transformedList, nextElement) => {
        // use the mapFunction to transform the nextElement in the list 
        const transformedElement = mapFunction(nextElement);

        // add transformedElement to our list of transformed elements
        transformedList.push(transformedElement);

        // return list of transformed elements
        return transformedList;
    }, [])
    // ^ start with an empty list

    return output;
}

// Expressing `filter` in terms of `reduce`
const filter = (list, predicate) => {
    const output = list.reduce(function (filteredElements, nextElement) {
        // only add `nextElement` if it passes our test
        if (predicate(nextElement)) {
            filteredElements.push(nextElement);
        }

        // return the list of filtered elements on each iteration
        return filteredElements;
        }, [])
    })
}

In theory, this means that we can replace our calls to map and then filter with calls to reduce. Then, we’d have a chain of calls involving only reduce, but which implements the same mapping/filtering logic we’re already using.

From there, we can apply a technique very similar to what we’ve seen with fusion to express our series of reductions in terms of a single function composition.

Step 1: mapReducer and filterReducer

The first step is to re-express our calls to map and filter in terms of reduce.

Previously, we wrote our own versions of map and filter, which looked like this:

const mapReducer = (list, mapFunction) => {
    const output = list.reduce((transformedList, nextElement) => {
        // use the mapFunction to transform the nextElement in the list 
        const transformedElement = mapFunction(nextElement);

        // add transformedElement to our list of transformed elements
        transformedList.push(transformedElement);

        // return list of transformed elements
        return transformedList;
    }, [])
    // ^ start with an empty list

    return output;
}

const filterReducer = (list, predicate) => {
    const output = list.reduce(function (filteredElements, nextElement) {
        // only add `nextElement` if it passes our test
        if (predicate(nextElement)) {
            filteredElements.push(nextElement);
        }

        // return the list of filtered elements on each iteration
        return filteredElements;
        }, [])
    })
}

We used these to demonstrate the relationship between reduce and map/filter.

But we need to make some changes if we want to use this in reduce chains.

Let’s start by removing those calls to reduce:

const mapReducer = mapFunction => (transformedList, nextElement) => {
    const transformedElement = mapFunction(nextElement);

    transformedList.push(transformedElement);

    return transformedList;
}

const filterReducer = predicate => (filteredElements, nextElement) => {
    if (predicate(nextElement)) {
        filteredElements.push(nextElement);
    }

    return filteredElements;
}

Note that: Earlier, we filtered and mapped an array of user names. Let’s start rewriting that logic with these new functions to make all this a little less abstract.

// filter's predicate function
function removeNamesStartingWithA (user) {
    return user.name[0].toLowerCase() != 'a'
}

// map's transformation function
function createUserInfoString (user) {
    const { name, email } = user
    return `${name}'s email address is: ${email}.`
}

users
  .reduce(filterReducer(removeNamesStartingWithA), [])
  .reduce(mapReducer(createUserInfoString), [])

This produces the same result as our previous filter/map chain.

Recapping: This is quite a few layers of indirection involved. Take some time to step through the above snippet before moving on.

Step 2: Generalizing Our Folding Function

Take another look at mapReducer and filterReducer.

const mapReducer = mapFunction => (transformedList, nextElement) => {
    const transformedElement = mapFunction(nextElement);

    transformedList.push(transformedElement);

    return transformedList;
}

const filterReducer = predicate => (filteredElements, nextElement) => {
    if (predicate(nextElement)) {
        filteredElements.push(nextElement);
    }

    return filteredElements;
}

Rather than hard-code transformation or predicate logic, we allow the user to pass in mapping and predicate functions as arguments, which the partial applications of mapReducer and filterReducer remember due to closure.

This way, we can use mapReducer and filterReducer as “backbones” in building arbitrary reduction chains by passing the predicate or mapFunction appropriate for our use case.

If you look closely, you’ll notice that we still make explicit calls to push in both of these reducers. This is important, because push is the function that allows us to combine, or reduce, two objects into one:

// Object 1...
const accumulator = ["an old element"];

// Object 2...
const next_element = "a new element";

// A single object that combines both! Eureka!
accumulator.push(next_element);

// ["an old element", "a new element"]
console.log(accumulator)

Recall that combining elements like this is the whole point of using reduce in the first place.

If you think about it, push isn’t the only function we can use to do this. We could use unshift, instead:

// Object 1...
const accumulator = ["an old element"];

// Object 2...
const next_element = "a new element";

// A single object that combines both! Eureka!
accumulator.unshift(next_element);

// ["a new element", "an old element"]
console.log(accumulator);

As written, our reducers lock us into using push. If we wanted to unshift, instead, we’d have to re-implement mapReducer and filterReducer.

The solution: Abstraction.

Rather than hard-code push, we’ll let the user pass the function they want to use to combine elements as an argument.

const mapReducer = combiner => mapFunction => (transformedList, nextElement) => {
    const transformedElement = mapFunction(nextElement);

    transformedList = combiner(transformedList, transformedElement);

    return transformedList;
}

const filterReducer = combiner => predicate => (filteredElements, nextElement) => {
    if (predicate(nextElement)) {
        filteredElements = combiner(filteredElements, nextElement);
    }

    return filteredElements;
}

We use it like this:

// push element to list, and return updated list
const pushCombiner = (list, element) => {
    list.push(element);
    return list;
}

const mapReducer = mapFunction => combiner => (transformedList, nextElement) => {
    const transformedElement = mapFunction(nextElement);

    transformedList = combiner(transformedList, transformedElement);

    return transformedList;
}

const filterReducer = predicate => combiner => (filteredElements, nextElement) => {
    if (predicate(nextElement)) {
        filteredElements = combiner(filteredElements, nextElement);
    }

    return filteredElements;
}

users
  .reduce(
      filterReducer(removeNamesStartingWithA)(pushCombiner), [])
  .reduce(
      mapReducer(createUserInfoString)(pushCombiner), [])

Step 3: Transduction

At this point, everything’s in place for our final trick: Composing these transformations to fuse those chained calls to reduce.

Let’s see it in action first, and then review.

const R = require('ramda');

// final mapReducer/filterReducer functions
const mapReducer = mapFunction => combiner => (transformedList, nextElement) => {
    const transformedElement = mapFunction(nextElement);

    transformedList = combiner(transformedList, transformedElement);

    return transformedList;
}

const filterReducer = predicate => combiner => (filteredElements, nextElement) => {
    if (predicate(nextElement)) {
        filteredElements = combiner(filteredElements, nextElement);
    }

    return filteredElements;
}

// push element to list, and return updated list
const pushCombiner = (list, element) => {
    list.push(element);
    return list;
}

// filter's predicate function
const removeNamesStartingWithA = user => {
    return user.name[0].toLowerCase() != 'a'
}

// map's transformation function
const createUserInfoString = user => {
    const { name, email } = user
    return `${name}'s email address is: ${email}.`
}

// use composition to create a chain of functions for fusion (!)
const reductionChain = R.compose(
    filterReducer(removeNamesStartingWithA)
    mapReducer(createUserInfoString),
)

users
  .reduce(reductionChain(pushCombiner), [])

We can go one further by implementing a helper function.

const transduce = (input, initialAccumulator, combiner, reducers) => {
    const reductionChain = R.compose(...reducers);
    return input.reduce(reductionChain(combiner), initialAccumulator)
}

const result = transduce(users, [], pushCombiner, [
    filterReducer(removeNamesStartingWithA)
    mapReducer(createUserInfoString),
]);

…And that, as they say, is that.

Takeaways & Next Steps

This was a bit of a whirlwind, so it pays to step back from the details and consider a summary and next steps.

So, in summary:

As for next steps and more advanced concepts:

…But, at the end of the day, I think the most important takeaway is this: There are more solutions to almost any problem than anyone could ever enumerate; the more of them you meet, the clearer you’ll think about your own, and the more fun you’ll have doing so.

I hope meeting Fusion and Transduction piques your interest, helps you think more clearly, and, ambitious as it is, was at least a little bit fun.

As always, questions, comments, and feedback are encouraged—drop a line.

And don’t forget to have some fun.

Learn More

Machine Learning in JavaScript with TensorFlow.js

ES5 to ESNext — here’s every feature added to JavaScript since 2015

12 Concepts That Will Level Up Your JavaScript Skills

Vuejs 2 Authentication Tutorial

Vue Authentication And Route Handling Using Vue-router

The Complete JavaScript Course 2019: Build Real Projects

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!

Learn JavaScript in 60 Minutes | JavaScript Crash Course | JavaScript Tutorial |

This video on "JavaScript" will help you learn JavaScript basics and fundamental concepts in 60 minutes. This will provide you in-depth knowledge about the JavaScript fundamentals that will help you write your own code in JavaScript and build a website. This JavaScript tutorial covers following topics..

==================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Svelte.js - The Complete Guide

The Complete JavaScript Course 2019: Build Real Projects!

Advanced CSS and Sass: Flexbox, Grid, Animations and More!

CSS - The Complete Guide (incl. Flexbox, Grid & Sass)

CSS Bootcamp - Master CSS (Including CSS Grid / Flexbox)

Build Responsive Real World Websites with HTML5 and CSS3

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

JavaScript - Step By Step Guide For Beginners

JavaScript | How to use classes in JavaScript

JavaScript | How to use classes in JavaScript

Classes in JavaScript are a special syntax for its prototypical inheritance model that resembles class based inheritance in other object oriented languages. Classes are just special functions that can be declared to resembles classes in other languages. In JavaScript, we can have class declarations and class expressions, because they are just functions. So like all other functions, there are function declarations and function expressions. Classes serve a templates to create new objects.

Defining Classes

To declare a class, or make a class declaration, we use the class keyword to do so. For example, to declare a simple class, we can write:

class Person{
  constructor(firstName, lastName) {
    this.firstName= firstName;
    this.lastName = lastName;
  }
}

Class declarations aren’t hoisted so they can used before they are defined in the code, as the JavaScript interpreter will not automatically pull them up to the top. So the class above won’t work before it’s defined in the code like the following:

const person = new Person('John', 'Smith');
class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

We will get a ReferenceError if we run the code above.

We can also define a class by a class expression, which is an alternative syntax for defining a class. They can be named or unnamed. We can also assign a class to a variable like we do with functions. If we do that, we can reference the class by its name. For example, we can define:

let Person = class {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

To get the name of the unnamed classes above, we can get the name with the name property, like so:

console.log(Person.name);


We can also undefined a named class like the following:


let Person = class Person2{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

Then to get the name of the class, we can use the name property again. So we if we write:

console.log(Person.name)


we get Person2 logged.

The class body is defined with curly brackets. We define the class members inside the brackets. The body of the class is executed in strict mode, so everything defined in strict mode applies to the definition of a class, so we can’t define variables with out some keyword before it like var , let or const , and many other rules apply when you define a class. Classes in JavaScript also have a constructor method that lets us set fields when the object is instantiated with a class . Each class can only have one constructor method in it. If there’s more than one, then SyntaxError will be thrown. A constructor have to also call the super method to call the constructor of the super class inside if it the class extends a parent class.

Methods that aren’t declared static constitutes of the prototypical methods of the class. They are called after an object has been created by using the new keyword. For example, the following class have only prototypical methods:


class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName(){
    return `${this.firstName} ${this.lastName}`  
  }
  sayHi(){
    return `Hi, ${this.firstName} ${this.lastName}`
  }
}

In the Person class above, fullName and sayHi are prototypical methods. They are called like this:

const person = new Person('Jane', 'Smith');
person.fullName() // 'Jane Smith'

Static methods are methods that can be called without creating an object from the class using the new keyword. For instance, we can have something like the following:


class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  static personCount() {
    return 3;
  }
}

We can call the personCount function without using the new keyword to create an instance of the class. So if we write:

Person.personCount

We get 3 returned.

The this value inside prototypical methods will be the value of the object. For static methods the value of this has the class that the static method is in as the value.

Getters and Setters

JavaScript classes can have getters and setter functions. Getters, as the name suggests, is a method that lets us get some data from a class. Setters are methods that gives us the ability to set some fields of the class. We denote getter functions with the get keyword and setters with the set keyword. For example, we can write a class that has getters and setters like the following:

class Person {
  constructor(firstName, lastName) {
    this._firstName = firstName;
    this._lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  get firstName() {
    return this._firstName
  }
  get lastName() {
    return this._lastName
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  set firstName(firstName) {
    this._firstName = firstName;
  }
  set lastName(lastName) {
    this._lastName = lastName;
  }
}

Then when we use the new keyword to construct a Person object, we can use them in the following way:


const person = new Person('Jane', 'Smith');
person.firstName = 'John';
person.lastName = 'Doe';
console.log(person.firstName, person.lastName)

Since we have the getter and setter functions, we can use them to set the data directly to set the data for firstName and lastName of the Person class. In the setter functions, which start with the keyword set , what we assign to them get passed into the parameters and set in the member of the class. In the getter functions, which are denote by get we return the member values so that we can use them.

JavaScript Inheritance

In JavaScript, we can create classes where the properties can be included in the properties of a child class.

So, we can have a high-level class that contains the properties that are common to all the child classes, and the child class can have its own special properties that are not in any other classes.

For example, if we have an Animal class with the common properties and methods, like name and the eat method, then the Bird class can just inherit the common properties in the Animal class. They don’t have to be defined in the Bird class again.

We can write the following to do inheritance in JavaScript:

class Animal {
  constructor(name) {
    this.name = name;
  }
  eat() {
    console.log('eat');
  }
}
class Bird extends Animal {
  constructor(name, numWings) {
    super(name);
    this.numWings = numWings;
  }
}
const bird = new Bird('Joe', 2);
console.log(bird.name)
bird.eat();

In the example above, we have the parent class, Animal, that has the eat method, which all classes that extends from Animal will have, so they don’t have to define eat again.

We have the Bird class which extends the Animal class. Note that in the constructor of the Bird class, we have the super() function call to call the parent’s class constructor to populate the properties of the parent class in addition to the properties of the child class.

Classes cannot extend regular objects, which cannot be constructed with the new keyword. If we want to inherit from a regular object, we have to use the Object.setPrototypeOf function to set a class to inherit from a regular object. For example:

const Animal = {
  eat() {
    console.log(`${this.name} eats`);
  }
};
class Cat{
  constructor(name) {
    this.name = name;
  }
}
class Chicken{
  constructor(name) {
    this.name = name;
  }
}
Object.setPrototypeOf(Cat.prototype, Animal);
Object.setPrototypeOf(Chicken.prototype, Animal);
let cat = new Cat('Bob');
let chicken = new Chicken('Joe');
cat.eat();
chicken.eat();

If we run the example code above, we have see Bob eats and Joe eats logged because we have inherited the eat function from the Animal object.

this Keyword

The this keyword allows us to access the current object’s properties inside an object, unless you’re using arrow functions.

As we can see from the above example, we can get the properties of the instance of the child and the parent class in the object.

Mixins

We can use mixins to do multiple inheritance in JavaScript. Mixins are templates for creating classes. We need mixins to do multiple inheritance because JavaScript classes can only inherit from one super class, so multiple inheritance isn’t possible.

For example, if we have a base class, we can define mixins to incorporate the members from multiple classes into one by composing the mixins by calling one and then pass the returned result into the next one as the argument, an so on, like so:

class Base {
  baseFn() {
    console.log('baseFn called');
  }
}
let classAMixin = Base => class extends Base {
  a() {
    console.log('classAMixin called');
  }
};
let classBMixin = Base => class extends Base {
  b() {
    console.log('classBMixin called');
  }
};
class Bar extends classAMixin(classBMixin(Base)) {}
const bar = new Bar();
bar.baseFn()
bar.a()
bar.b()

In the code above, we have the Base class which we pass into the classBMixin to get the b function into the Base class, then we call the classAMixin by passing in the result of classBMixin(Base) into the argument of the classAMixin to return the a function from classAMixin into the Base class and then return the whole class with all the functions from all the classes incorporated into one.

If we call all the functions above like we did by creating an instance of the Bar object and then call the baseFn , a and b functions, then we get:

baseFn called
classAMixin called
classBMixin called

This means that we have all the functions from the mixins incorporated into the new Bar class.

In JavaScript, classes are just syntactic sugar to make the prototypical inheritance of JavaScript clearer by letting us structure the code in a way that’s more like typical inheritance class based object oriented inheritance pattern. This means that we write classes to and use the new keyword to create objects from the classes, but underneath the syntactic sugar, we are still using prototypical inheritance to extend objects. We can extend classes from objects and we can also use mixins to do multiple inheritance in of JavaScript classes.