Top JavaScript Features You Must Know

Features of JavaScript

Introduction

JavaScript is one of the most popular languages and has a host of handy features for web development. On GitHub, it’s among the highest volumes of code is written in repositories across all users. In fact, according to Stack Overflow, nearly 70% of professional developers who responded to the 2020 survey coded in JavaScript. JavaScript has been the most-used technology since Stack Overflow started doing the annual poll. The reason for this overwhelming popularity of JavaScript is three-part. 

First is its ability to be used in all aspects of web development, as in front-end and back-end. This versatility makes it possible to make a web application using only javascript.

Second, its nature as a scripting language makes its syntax easy to understand; also, there is no particular setup required to run it, as it runs on the browser readily. This ease in running JavaScript makes it popular for doing small odd tasks using scripts.

Third, because of the first two points, it has strong community support. A vast community makes it so that there are a lot of open-source libraries available for free use. As the number of open-source, public libraries increases, so does the number of users, increasing community support.

The only prerequisite to learning JavaScript is basic computer literacy and a basic understanding of HTML and CSS.

What is Javascript?

At a high level, JavaScript is a scripting or programming language that allows you to implement complex features on web pages. The HTML you write only creates a static page on the web, so every time a web page does more than just display static information for you to look at; it is using javascript to enhance the page’s functionality! To display content updates promptly, interactive interfaces for maps, animated 2D/3D graphics, scrolling video jukeboxes, etc., we can use JavaScript. It is the third layer in the cake of standard web technologies, the other two of which are HTML and CSS

Top Features of JavaScript

Below are a few features of JavaScript based on general features, language use, and experimental features.

General language features

Scripting Language

JavaScript is a lightweight scripting language made for client-side execution on the browser. Since it is not designed as a general-purpose language and is specially engineered for web applications, the set of libraries is also geared primarily towards web applications.

Interpreter Based

JavaScript is an interpreted language instead of a compiled one. In that sense, it is closer to languages like Ruby and Python. The browser interprets JavaScript’s source code, line by line and runs it. In contrast, a compiled language needs to be compiled into a byte-code code executable. Java and C++ are examples of compiled languages.

Event Handling

An event is an action or an occurrence in a system that communicates about said occurrence so that you can respond to it somehow. For example, a user clicks on a button, and the system tells you to respond to the button click event with an action, say an information box.

JavaScript enables you to handle events and even generate custom events.

Light Weight

JavaScript isn’t a compiled language, so it doesn’t get converted to byte-code beforehand. However, it does follow a paradigm called Just-In-Time (JIT) Compilation. Meaning it gets converted to bytecode just as it’s about to run. This enables JS to be lightweight. Even less powerful devices are capable of running JavaScript.

Case Sensitive

JavaScript is highly case sensitive. All keywords, variables, functions names and other identifiers can and must only follow a consistent capitalisation of letters. E.g.:

var hitCounter = 5
var hitcounter = 5

Here variables hitCounter and hitcounter are both different variables because of the difference in the case. Also, all keywords such as “var” are case sensitive.

Control Statements

JavaScript is equipped with control statements like if-else-if, switch-case, and loops like for, while, and do-while loops. These control statements make it a powerful programming language, enabling its user to write complex logic.

Objects as first-class citizens

All non-primitive data types in JavaScript are actually objects, i.e. data types like Arrays, Functions, Symbols etc. inherit all the properties of the Object prototype.

The term first-class citizen means “being able to do what everyone else can do”. In JavaScript Objects prototype is the base prototype of all. They can be passed as reference, returned in a function, and assigned to variables for manipulation. This concept is also extended to functions as Object is also the prototype of functions.

Functions as First-class citizens(supports functional programming)

What do we mean by functions as first-class objects/citizens? Functions that return a function are called Higher Order Functions, which JavaScript supports. Functions as first-class citizens simply mean functions enjoy similar behaviour from the JavaScript interpreter as that of objects or any other variable. Meaning, we can pass them into arguments (pass by reference), return them by another function, and assign them to a variable as a value.

Dynamic Typing

JavaScript is a dynamically typed language. It means that the JS interpreter does not require explicit declaration of the variables before they are used. E.g.:

var dynamicType = “a string”
dynamicType = 5

Here we can see the same variable dynamicType can contain either a string or an integer with the same variable declaration. That is, the variable type does not need to be declared during creation or assignment.

Language Use Features

Client-side validations

JavaScript is heavily used for easing the interactions between users and web applications. Towards this, validation plays a significant role. Validations can guide users to fill forms correctly with valid data and prevent spam submissions. 

Platform Independent

JavaScript is platform-independent; it can run on any computer irrespective of the operating systems used. JavaScript is built into Netscape 2.0 and greater. Since the JavaScript interpreter is part of Netscape, it runs on platforms that support Netscape, which means that a piece of Javascript code will give the same output with the same setup on all platforms.

Async Processing

JavaScript supports asynchronous behaviour through the use of Promises and Async functions. In Promises, we can make a request and attach a .then() clause to it, which only executes on the completion of the promise. The other alternative is to use the async-await syntax functions; async functions don’t execute sequentially but parallelly, which positively affects pages’ processing time and responsiveness.

Prototype-based

JavaScript is a prototype-based scripting language, which means it uses the prototypal inheritance model instead of the commonly known class inheritance. This means instead of creating classes and deriving objects from them, we define the Objects prototype and use this object prototype to create more Objects of the same type. This behaviour is similar to the Object factory method, and thus such a design pattern is commonly seen in JavaScript code.

Experimental & Newer features

Here are a few more unique features of javascript; these features are handy for professional developers and assist in writing idiomatic code. Some of these features do not come out of the box. In those cases, you need a transpiler like Babel to run them.

Nullish coalescing operator (??)

According to MDN: “The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand”. This handy feature allows for distinction between 0 and null/undefined values, which is necessary during calculations! For example –

function addTax(price, taxes, description) {
  // 10% or 0.1 is default tax  
  taxes = taxes || 0.1
  // What if taxes are 0%, that could be a problem.
  const total = price * (1 + taxes)
  console.log(
    `%c${description} with tax, totals to: ${total}`,
    "font-weight: bold; color: blue"
  )
}

addTax(100, 0.3, "An item")
addTax(100, undefined, "Default tax")
addTax(100, 0, "Zero tax")

In the example above, in the third case of no tax, we can see that the answer is wrong! The total should be 100 as the intention is to have no tax on this item. But as we can see, JavaScript treats the 0 value as false, thus assigning taxes a value of 0.1 instead of 0.

We can simply fix this by using the Nullish coalescing operator, like so:

function addTax(price, taxes, description) {
  // 10% or 0.1 is default tax  
  taxes = taxes ?? 0.1
  const total = price * (1 + taxes)
  console.log(
    `%c${description} with tax, totals to: ${total}`,
    "font-weight: bold; color: blue"
  )
}

addTax(100, 0.3, "An item")
addTax(100, undefined, "Default tax")
addTax(100, 0, "Zero tax")

The ?? operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined; therefore, we get the correct value for taxes.

Logical nullish assignment (??=)

The Logical nullish assignment is simply the shorthand for the line of code:

taxes = taxes ?? 0.1

Styling Console Log

It is possible to style your console logs in javascript; that is, you can apply styling to your boring and static console logs! The syntax is simple, add a %c to what you want to style and pass the styles you want to apply as the second parameter:

console.log(
    `%c${description} with tax, totals to: ${total}`,
    "font-weight: bold; color: blue"
  )

To add more styles, just add another %c and another parameter like so:

  console.log(
    `%c${description} with tax, totals to: %c${total}`,
    "font-weight: bold; color: blue",
    "font-weight: bold; color: green"
  )

Object Shorthand

According to ES6/ES2015 syntax, if you want to define an object whose keys have the same name as the variables passed in as properties, you can use the shorthand and simply pass the key name. The object shorthand allows you to save time and space by allowing you to use this shorthand, making the code more idiomatic and concise:

Optional chaining (?.)

Optional Chaining, also commonly known as null safe traversal, is a feature similar to nullish coalescing but exponentially more helpful as it solves a prevalent issue. Suppose there is an object with nested properties, as is often common in JS. E.g.:

const peter = {
  name: 'Peter',
  address: {
    street: 'church street',
    apt: 'Parker'
  }
}

function printStreet(person) {
  console.log(person && person.address && person.address.street)
}
printStreet(peter)

The old way of checking whether an object exists.

If you want to print the street, you will have to check the property at each level in the object for undefined cause if any of the properties are not defined. JS will throw an error saying that “cannot read property X of undefined”, to avoid this, we need to do a null safe traversal of the object.

Defer/Async Loading

The script tag attributes async and defer are features that tackle page load time issues for heavy scripts; both will download the file during HTML parsing, allowing faster load times. Both do not interrupt the parser.

  • The script with the async attribute will be executed once downloaded, irrespective of the order in which they are written. Therefore, the order of execution isn’t guaranteed. 
  • On the other hand, the script with defer attribute will be executed after completing the DOM parsing, respecting the order in which script tags are mentioned. Therefore scripts loaded with defer attributes maintain the order in which they appear on the DOM.

Use <script async> when the script is independent(has no dependency). When the script depends, use <script defer>.

The best solution regarding dependency would be to add the <script> at the bottom of the body. There will be no issue with blocking or rendering.

Typically, we put out script tags at the bottom of the body(left image). This allows the HTML to parse before scripts are loaded, which is vital because your JS has to plug into the existing HTML. If you put your scripts in the head, they will load faster, but the script won’t attach itself to the HTML since the HTML parsing was interrupted to load the script.

Conclusion

Many of the Features of Javascript are unique and quirky as they were results from partial defects/bugs written into the core of the language. Others are the result of trying to mimic the features of languages like Java and its Object-Oriented programming concepts (Oops). Yet more features are a result of it intended as a scripting language. The governing body for Javascript is ECMA was established in 2009. Earlier than 2009, in the starting years of JavaScript, it was not developed according to a road map but as per its adopted use cases.

FAQ’s

Q. Why is JavaScript the best?
A. There are a few reasons why learning JavaScript is best:

  1. It is better for website development
  2. Experienced developers are more likely to know or require JavaScript
  3. It is easy to learn
  4. Its the most popular programming language

Why wait? Do check out this Free JavaScript course from Scaler Topics and learn JavaScript from scratch.

Q. Where is JavaScript used?
A. Its most commonly used to create web pages. It helps to add dynamic behaviour to the web pages, such as validations, special effects and other complex interactions between users and web pages.

Q. What are the limitations of JavaScript?
A. JavaScript can be used on the Frontend and Backend (using Node.js), however, there are certain scenarios where JavaScript is not suited for development.

  • If you want to do some compute-intensive tasks or calculations, JavaScript will cause latency and delay. This is also called the blocking-nature of JavaScript.
  • If you need multiple threads or multiprocessor capabilities, JavaScript is not suited to you. JavaScript is single-threaded and is best suited for async tasks.
  • Client-side JavaScript cannot read or write files by default.

Q. What is unique about JavaScript?
A. JavaScript is a flexible and powerful programming language implemented consistently by various browsers, making it very portable. It’s the most used and most easily accessible language. To run a piece of Js code, you just need a browser. Apart from that, it makes responsive design easier for web apps.

Q. How does JavaScript work?
A. The basic flow is that you add script tags in your HTML, typically at the end of the body; this loads the js when your HTML is done parsing. The interpreter picks the downloaded code and runs it in the order the script tags are written.

Additional Resources

Previous Post

Top 10+ New HTML5 Features

Next Post

Top Java 9 Features You Must Know