JavaScript Fundamentals - A Dinosaurs Cheat Sheet

JavaScript Fundamentals – A Dinosaurs Cheat Sheet

This tutorial demonstrates the fundamentals of JavaScript, such as variables, rendering techniques, libraries, functions, etc, with examples.

Notepads, table cells, table rows, these were some of the few jargons you needed decades ago to build a simple static website. However, suppose you time traveled from that era, back when Adobe Flash Player was still a thing, to this internet-driven world we’ve created for ourselves today. In that case, you’ll be surprised to see the enormous advancement we’ve made, especially in the web development space. For instance, websites are now more dynamic and responsive. In addition, we are talking about sites that communicate effectively with servers that host them, thanks to relatively new and complex programming languages such as JavaScript, PHP, and MySQL. 

Speaking of JavaScript, it is an essential part of web development, and it also makes designing a responsive website easier. As SEO professionals and web developers, we long for times when websites were static. But gone were the days when developers could get by designing a simple client-side webpage using a simple line of CSS and HTML. 

JavaScript is easy to learn, though it can be pretty complex when learning about frameworks and libraries. 

JavaScript unarguably remains one of the world’s most popular programming languages. On the flip side, however, it can be a complex language to comprehend, one that’s difficult to get a hold of. Yet, it has never been more essential to learn because it is fast becoming prevalent on the websites we encounter on the internet. And as the web programming world continues to evolve, its importance rises too.

What is JavaScript?

JavaScript is a well-known programming language that allows programmers to incorporate complex features on their website to make it more interactive and dynamic. It has become intrinsic to a positive internet experience, thanks to developers who constantly design sites with more fluid and interactive features. Content management systems, e-commerce, phone apps, social media, and search engines would not exist without it. 

Furthermore, the javascript language will execute after the web browser parses the code fetched from the HTML and CSS present in the source code.

Next, it (the JavaScript) will trigger any variables and functions specified within it. After the browser parses the web page, the activated code will update the Document Object Model (DOM). Thus, showing the newly edited file to users in the web browser window.

Both HTML and CSS are the frame and foundations of all website page structures. On the other hand, JavaScript is added to make the final alterations and adds the functionality, fluidity, and responsiveness your website needs.

What is the Document Object Model (DOM)?

The browser creates the Document Object Model (DOM) whenever a web page loads. It consists of objects and nodes which map out the different attributes and elements on a web page. Hence, you’ll then get a mapped-out page that can be manipulated and further modified by other programs in terms of content, styling, and structure. Thanks to JavaScript, modifying elements present on a page’s DOM is possible and very easy.

What is transpiling?

Transpiling is used in programming to describe taking source code written in a particular language and transforming them into a new language with the same abstraction level. Meanwhile, transpilers are tools designed to help transform source code into different programming languages. The concept behind this is similar to Google Translate, but for code. The source code, the language used in a source program, can be converted into a different target language.

What are some JavaScript frameworks?

There are many JavaScript frameworks on the internet right now, each equipped with its unique perks. With lots of options to pick from for backend and front-end developers, choosing the right framework that’s perfect for your requirements can be a daunting task. But here is a list of the best JavaScript frameworks:

Backend JavaScript Frameworks

One massive reason behind JavaScript’s popularity today is its versatility. Thanks to Node.js, JavaScript can also be used as server-side development. But there are different backend server-side JavaScript frameworks to pick. The catch is that you have to note some essential factors like flexibility, performance, scalability, and the nature of your website development. The four top frameworks to pick from include:

Expres.js

Express.js is an open-source un-opinionated, and minimal web framework for Node.js. It is used for developing different web applications and APIs. Expres.js is well known in the web development sphere and is considered the de facto best JavaScript framework for backend server-side with Node.js. 

It was built initially by T Holowaychuk a decade ago, and then almost five years later, IBM acquired it in 2015. One of the key advantages of using this framework is its rapid server-side coding. Thanks to Express.js, some complex tasks that typically require hours of coding now take minutes to create. But, that’s not all; a rugged routing mechanism for controlling highly dynamic URLs is one of the numerous perks Expres.js offers. Some popular web applications designed with Express.js include Uber, Sony PlayStation, Accenture, Nike, Ripjar, Yandex, to name a few.

Gatsby.js

Founded by Sam Bhagwat and Kyle Mathews, Gatsby was originally called GraphQI and Flexible Reach Static Site Generator in 2015. It’s a perfect tool for creating high-performance and SEO-friendly static websites. Gatsby also lets users source data from any data bank imaginable CMS like WordPress, Contentful, Drupal, etc., or simple markdown, databases, or APIs. 

So, what exactly makes this framework interesting? Well, for starters, it’s high performance. Websites developed with Gatsby are 2 – 3 times faster than typical web applications built with another tech stack. Examples of web applications built with Gatsby.js include Airbnb, Ghost, Nike, Impossible, Sendgrid, PayPal, Snapkit, React, to name a few.

Next.js

Next.js is an end-to-end server-side rendering framework. Vercel (a Dutch company previously known as ZEIT) developed Next.js in 2017. And though Gatsby and Next use React, there’s one significant difference between the two. While Next is SSR – Server – Side renderer, Gatsby is essentially a static site generator. 

Some of the advantages of Next.js include automatic code-splitting, automatic routing, and built-in handling of Search Engine Optimization (SEO). On the downside, the performance benchmarks of Next.js are relatively inferior to both Gatsby and Nuxt. Available web applications built with Next.js include Trulia, Uber, Coinbase, Hulu, Docker, Magic Leap, Starbucks, Netflix, to name a few.

Nuxt.js

Fast setup and development are just some of the significant advantages of using Nuxt.js. Setting up a new web project with this framework only takes a few minutes. Thanks to its starter template, it can do this, created using the command line. Furthermore, Nuxt.js is an open-source framework based on the Vue ecosystem, a progressive framework used to develop website applications. Though it’s referred to as an enhancer for Vue, it isn’t a substitute for it. And that’s because Nuxt.js can’t function independently. On the downside, however, debugging issues tend to pop up when using this framework, and of course, this can be pretty frustrating. Examples of web applications built with Nuxt.js include MyScript, Aircall, Todoits, Upwork, Bootstrap, Amplitude, to name a few.

Front-end JavaScript Frameworks

From Vue, Angular, to React, these front-end frameworks have garnered a massive legion of followers while the new competitors are still gaining ground. However, JavaScript has been used to develop different applications for two decades.

Vue.js

“Evan You” first launched Vue.js back in 2014 while still at Google. He took inspiration from Angular. As a result, he delivered a lightweight and efficient alternative in the form of Vue.js. Though Vue has picked some features from Angular and React, without a doubt, it has made groundbreaking improvements on those adopted features to help deliver a much improved, easy-to-use framework. For example, unlike React, it has a built-in MVC, making for a better and easier configuration. But on the downside, it doesn’t enjoy the backing of big tech IT tech companies like Google and Facebook.

React.js

React.js is one of the top open-source front-end JavaScript libraries created by a team of Facebook developers back in 2011. And though it isn’t a full-fledged framework, it can be considered one of the biggest influential disruptors in the IT world. Without a doubt, React.js’ influence has helped shape the web applications we see today. The developers achieved this goal by introducing a component-based and declarative programming style for designing interactive UIs for single-page web applications. Moreover, it has reusable components, which help app/web developers import user interface components with ease rather than dealing with the complexity of coding them from scratch.

Angular.js

Angular.js by Google is an open-source JavaScript library. Some client-side single-page websites use, Angular.js, the typescript-based platform. The progressive framework reached popularity when it was first released through the emergence of React (the previous framework we highlighted), making sure the widespread fame was short-lived. Thus, Angular.js was overhauled and completely rewritten in 2016; hence, Angular 2. Thanks to its unique caching capabilities and many integrated features, the framework was revered for its top-notch server performance.

JavaScript Testing Frameworks

Developers can also use JavaScript to test different websites and web-based applications. This “JavaScript testing framework” form is gradually becoming the go-to automation testing platform for many popular organizations. End-to-end testing, integration testing, and unit testing use JavaScript testing frameworks.

Mocha

Mocha is exclusively a JavaScript testing framework, and it runs solely on node.js and is a feature-rich framework for asynchronous testing. The tests in Mocha run serially, and the reports it produces are accurate and, of course, flexible. Moreover, it supports BDD and TDD platforms for JavaScript automated testing for selenium test automation.

So, what are some of the prominent websites built with Mocha? Some of these websites include Wix, Yahoo, UX Planet, Triplebyte, to name a few.

Jest

Jest is arguably the best framework designed for testing. Developed by Facebook, it focuses more on simplifying the entire testing process. It appropriately combines with Selenium and functions as an efficient JavaScript automated testing tool. It also provides sophisticated cross-browser support for automated browser testing. Currently, it ranks as the best JavaScript framework for testing. Prominent websites designed using Jest include One football, Airbnb, Twitter, The New York Times, Spotify, Intuit.

Jasmine

Jasmine is more of a behavior-driven development testing framework. As a result, it is flexible and compatible with other frameworks or libraries you might want to work with. Without a doubt, Jasmine is the most flexible JavaScript testing framework on the internet right now.

What is a Single-Page Application?

Single–Page Application (also known as SPA) is a web platform designed to dynamically rewrite and re-render different web pages as the users interact with them, rather than creating separate requests to fetch data in the form of HTML and content from the server. JavaScript frameworks support the changing elements of SPAs.

Pre-rendering

Just as the name suggests, it involves rendering the web content before you (the user) requests the source or search engine to receive a static webpage containing the needed content. Preloading a page means the content will be accessible to the search engine or have the user’s browser render them (the web page) themselves.

JavaScript Rendering

JavaScript uses DOM to manipulate its (the Document Object Model) elements. So, what exactly is JavaScript Rendering? It refers to displaying the output of the parsed codes in the web browser. DOM establishes adjacent sibling and parent-child relationships among the various HTML elements. In simple terms, rendering in this context involves taking the script, processing it, and running it so that the output displays in the web browser.

Interestingly, there are different methods you can use to manage how JavaScript renders. But it would help if you took note of the fact that rendering JavaScript can impact your web pages in two key areas:

  • Search Engine Crawling and Indexing
  • Site Speed

Depending on the method used, one can reduce page load time and ensure the content on the web page is accessible to search engines for crawling and indexing.

Server-Side Rendering

Server-side rendering is an application’s ability to convert files fetched from the server into a rendered web page for the user or “handed” over to the search engine crawler when it’s needed. In simple terms, the browser requests data from the server, which instantly forwards a rendered page to the user. That’s like getting a PC that’s fully assembled rather than having to build it yourself after purchasing it. 

The server-side rendering process helps reduce strains on the web browser by reducing Javascript on the client-side, leading to increased page load speed.

JavaScript Server-side Rendering
JavaScript Server-side Rendering

Server-side rendering also ensures the user can see the complete content on the HTML page, and the search engine crawlers can index it.

Client-Side Rendering

Just as you might have guessed, the client-side is the complete opposite. It means that a web page’s JavaScript is rendered right there in your web browser. 

We are using the PC analogy again. Think of it as ordering a PC from eBay. However, eBay doesn’t send the PC to your house already assembled. Instead, they send you the components that you have to build into a PC once they arrive at your doorstep. Because all of the heavy tasks will run in your web browser, it’s the cheaper option for the site’s owner because it ultimately reduces the load on their hosting server. Moreover, client-side rendering is the default state for JavaScript-powered websites. 

As a developer, using this client-side rendering option won’t make your site more user-friendly because it causes a delay between Google crawling pages and rendering them simultaneously. 

Pages that need to render are less prioritized. Instead, Google puts them in a queue until there are enough resources to make them available for billions of users. That’s why relying on Google to render your web page client-side will be counterproductive, as this can delay the page’s indexing by up to a week.

JavaScript Client-side Rendering
JavaScript Client-side Rendering

Hybrid Rendering

Hybrid rendering does a little bit of both, and by both, we mean server-side and client-side rendering. It combines these two functionalities to give users a unique web browsing experience.

JavaScript Hybrid Rendering
JavaScript Hybrid Rendering

The page’s HTML content is pre-rendered server-side and transferred to the user (through the user’s web browser or the search engine crawler). Once the page is loaded, the extra JavaScript renders client-side, primarily the interactive JavaScript.

Dynamic Rendering

Dynamic rendering is the process of delivering content based on the user agent that fetches for it. It means there’s a client-side rendered version of a web page for humans and another version for search engines.

JavaScript Dynamic Rendering
JavaScript Dynamic Rendering

If a web page that’s client-side rendered detects Googlebot (Google’s web crawler), the bot fetches the page using a mini client-side renderer to make the content viewable instantly. Examples of mini client-side renderers include Rendertron and Puppeteer.

JavaScript Fundamentals

With JavaScript, you can implement complex features on a website, including dynamic elements or interactivity. JavaScript has functions, objects, and primitives, and however, all of them are valued and treated as objects.

Primitive

There are seven primitive types in JavaScript. They are:

  • Boolean
  • Number
  • Null
  • Undefined
  • BigInt
  • Symbol
  • String

Of course, the value “null” is also primitive. Though technically, null is the origin of all objects. In JavaScript, a primitive is data with no methods or an object. Most times, primitive values are represented directly at the lowest level of the language implementation.

You can consider all primitives are immutable, which means users can’t alter them. Therefore, do not confuse one for the other (primitive itself with a variable assigned primitive value). Though it’s possible to reassign a new value, developers can’t change the current value the same way you would with functions, arrays, and objects.

Examples:

The example below shows the reason why primitive values are immutable.

// Using a string method doesn't mutate the string
var bar = "baz";
console.log(bar);               // baz
bar.toUpperCase();
console.log(bar);               // baz

// Using an array method mutates the array
var foo = [];
console.log(foo);               // []
foo.push("plugh");
console.log(foo);               // ["plugh"]

// Assignment gives the primitive a new (not a mutated) value
bar = bar.toUpperCase();       // BAZ

What are the primitive wrapper objects in JavaScript?

Except for “undefined” and “null,” the rest of the primitive values have objects equivalents that wrap around them.

  • Symbol: meant for the symbol primitive
  • String: meant for the string primitive
  • BigInt: meant for the bigint primitive
  • Number: meant for the number primitive. And;
  • Boolean: meant for the Boolean primitive

Side note: You can’t directly alter a primitive, but you can replace it.

Variables

Variables are placeholders for information, and they play the role of a memory bank that stores data. To declare a variable and give it a name, all you have to do is use the keyword “var.”

var foo = 'bar' // foo is now bar

When a variable isn’t assigned the “var” keyword, it automatically tags as “undefined.” “Undefined” means that the variable initializes, but there’s nothing in its memory bank. So, it means that there is no value in the memory bank.

var foo; // foo is now undefined.

Null

Remember, you have to assign “null” manually. It represents the conscious absence of any object value, which means you haven’t forgotten to fill it with a name or that something disrupted the process.

var foo = null; // foo is now null.

Number

When a script uses a number as a function, it converts a string or other value to the Number type. The value returns NaN, Not-a-Number if you cannot convert them.

It’s also crucial to point out that the number type in JavaScript is a 64-bit binary floating-point value.

As you probably know by now, numbers inherit methods from the “Number.prototype” object. Developers can call methods on each number:

Array

Arrays are indexed collections of values; each represents an element. And each element can be ordered and accessed by its respective index number. 

JavaScript has array-type objects You can implement (Arrays) by using objects. For example, indexes can be converted to strings and used simply as names for retrieving values. A simple array such as this one let arr = [‘X,’ ‘Y,’ ‘Z’] is emulated using an object like the one highlighted below:

{
  '0': 'X',
  '1': 'Y',
  '2': 'Z'
}

Functions

Functions are known as independent units of behavior. It’s a set of statements that calculate a value or perform a task. Functions are objects you can assign to variables, store in arrays or objects, and parse to execute other functions. There are multiple ways to define functions.

  • Arrow function 
  • Function Declaration (also known as Function Statement)
  • Function Expression (also referred to as Function Literal)

Function Declaration

  • You can use them before definition. Next, these functional declarations are moved or hoisted to the top of their scope. 
  • It must have a name.
  • The function is the first keyword on the line.
function doSomething(){}

The Function Expression

  • The function can auto-execute after the definition (referred to as “IIFE” Immediately Invoked Function Expression) 
  • The function is not the first keyword on the line.
  • There can be a named function expression or an anonymous function express. The name is entirely optional
  • And to execute, it needs to be defined
let doSomething = function() {}

(function () {
    console.log('Immediately invoked function execution');
})

Arrow Function

The arrow function is a sugar syntax whose job is to create an anonymous function expression, and it is a “compact” alternative to traditional function expressions. However, the arrow function is limited, and only in some situations can you use it. So, what are the differences and limitations?

  • You can not use them as “Constructors.”
  • It doesn’t have anything new. target keyword 
  • It doesn’t have its bindings to super or this, and you shouldn’t use it as a method. 
  • Can’t use yield within its body 
  • It’s not suitable for apply, bind, and call methods, which often rely on establishing a scope
const materials = [
  'Chipman,'
  'Tyler',
  'Tosin,'
  'Jennifer'
];

console.log(materials.map(material => material.length));
// expected output: Array [7, 5, 5, 8]

The creators first introduced the Arrow functions in ES6. It allows developers to write shorter functions syntax. For example:

let myFunction = (y, z) => y * z;

What a function expression looked like without the arrow function:

hello = function() {
  return "Good Morning!";
}

But what does this same function look like after?

hello = () => {
  return "Good Morning!";
}

The summary is, the code gets shorter. In a scenario where the function has just one statement, and the statement returns a value, you can remove both the brackets and the return keyword. By default, arrow functions will return the value.

hello = () => "Good morning!";
Arrow Function with Parameters
hello = (val) => "Good Morning " + val;

Feel free to try this out yourself; here’s the complete code. You can play around with it:

<!DOCTYPE html>
<html>
  <body>

    <h2>Arrow Function with Parameters</h2>

    <p>Here’s what you’ll get</p>

    <p id="sample"></p>

    <script>

      var hello;

      hello = (val) => "Good Morning " + val;

      document.getElementById("sample").innerHTML = hello("Tosin!");

    </script>

  </body>
</html>

Arrow Function without Parentheses:

Interestingly, you can skip the parenthesis if there’s only one parameter.

hello = (val) => "Good Morning " + val;

Here’s the complete code if you wish to try this out yourself. You can play around with it:

<!DOCTYPE html>
<html>
  <body>

    <h2>JavaScript Arrow Function</h2>

    <p>Here’s an Arrow Function with a parameter.</p>

    <p id="demo"></p>

    <script>

      var hello;

      hello = (val) => "Good Morning " + val;

      document.getElementById("demo").innerHTML = hello("Tosin!");

    </script>

  </body>
</html>

Function Invocation

Function invocation executes the function code. “call a function” is an alternative to “invoke a function”. The code expressed in a function runs when you invoke the function. So, how do you invoke the function? There are multiple ways to do this:

Method Form
theObject.doSomething(arguments)
theObject["doSomething"] (arguments)
Function Form
doSomething(arguments)

Apply Form
doSomething.apply(theObject, [arguments])
doSomething.call(theObject, arguments)
Constructor Form
new Constructor(arguments)

You can invoke Functions with fewer arguments than declared above. Meanwhile, disregard the extra arguments, and the missing parameters will then be undefined.  Except for the arrow functions, there are two pseudo-parameters: arguments and this.

Functional Patterns

As far as JavaScript is concerned, there are first-class functions and closure, and it’s a concept that sheds more light and paves the way for Functional Programming. Thus, high-order functions are made possible.

  • “reduce( )”
  • “filter( )”
  • “map( )”

These are all the essential tools for working with arrays in a functional style. Let’s highlight these tools better:

reduce( )

The reduce method reduces the list of values to just one. Then, it executes a reducer function for the array element. Addionally, it returns a single value, the function’s accumulated result.

Example: Subtracting all numbers in an array:

const numbers = [205, 80, 65];

document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num;
}
filter( )

The filter method picks values from a list based on a predicate function. This function decides what the developer can store.

map( )

The map method, on the other hand, converts a list of values to another one using a mapping function.

Example: Multiply the values in an array with 20

const numbers = [250, 93, 73];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 20;
}

Primitives Vs. Objects

Except for null and undefined, the other primitives are treated as objects with the nuance that they have different methods though they aren’t objects

Booleans, numbers, and strings have object equivalent wrappers. These are known as the Boolean, Number, and String functions.

For developers to gain access to properties on primitives, JavaScript produces a wrapper object and then ultimately destroys it. Also, JavaScript optimizes generating and destroying wrapper objects by its engine.

Conclusion

JavaScript is famous for its simplicity. Learning the fundamentals will make you a better programmer. Change is constant; you’ll recognize that if you are in the programming space as technology in this world evolves all the time.

Hopefully, you found this article helpful and helped you become a better developer. But more importantly, that is understanding the JavaScript fundamentals can impact your career as a developer. 

To improve, first, you need to get conversant with these JavaScript fundamentals. It transforms you from a developer that only designs static websites to a web developer that designs interactive websites. To read similar articles such as this one, explore our website. There you have it.

Recommended Articles