The ECMAScript 2015 aka ES6, is the 6th edition of the ECMAScript language specification standards. What ES6 did to Javascript was what Java8 did to Java. ES6 came with many new features to enhance the existing language and many new concepts to write clean and concise code.
Here are some additions in ES6
1. let & const (Block Scope without Hoisting )
If you’ve coded in Javascript before 2016, you know how vulnerable the var keyword made the applications. Using it outside a function was a suicide but even within a function, it created problems due to hoisting. Now, what was hoisting?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
So no matter where you declare var, it will always be moved to the top of its enclosing function. So any block within the function will still see the same variable. This doesn’t leave any space to have scopes.
To tackle this problem, ES6 introduced let. Any variable defined with let will be scoped to the most recent block it's defined in. Therefore, will not be seen outside.
For better understanding, copy this code in an empty file and open file in browser
<html><body>Check console logs</body> <script> window.onload = () => {let letVariable = 10; var varVariable = 10;console.log(`initial value letVariable = ${letVariable}`) console.log(`initial value varVariable = ${varVariable}`){ let letVariable = 20; var varVariable = 20;console.log(` intermediate value letVariable = ${letVariable}`); console.log(` intermediate value varVariable = ${varVariable}`); }
letVariable = letVariable + 30; varVariable = varVariable + 30;console.log(`final value letVariable =${letVariable}`) console.log(`final value varVariable = ${varVariable}`)} </script></html>
What do you expect to see? Think of an answer before looking at console logs.
Sometimes we want to make sure that no further code can change an already assigned value of a variable. var or let can not restrict that. ES6 added the const keyword forthat purpose
Add the below line of code in the above file before the last line. and open in browser
const constVariable = 10; console.log(`initial value for constVariable = ${constVariable}`);constVariable = constVariable + 1; console.log(`final value for constVariable = ${constVariable}`);
2. Arrow functions (Expression Bodies)
Arrow functions aka Fat Arrow function, one of the most used features of ES6, are the victim of maybe the laziest naming, done in the history of JS. If you know java, JS Arrow functions ()=>{}are the same as Java lambdas()->{}but with an extra slash, thus called fat. (I guess).
Before 2016 in JS the reusable expressions used to be created as
var sum = function (a,b){ return a+b;};
But with ES6 Arrow functions you can write the same code as
let sum = (a,b)=> a+b;
NOTE: Arrow functions are not a direct replacement for function but only for a function expression. named function gets hoisted but function expression & arrow functions do not. So above two are not the same as the below code, because the below code can be used before it's declared
function sum(a,b) { return a+b;}
3. Default parameter
By design, all functions in javascript are variable args functions. what that means is that you can invoke a javascript function declared with n number of parameters by providing from 0to n number of arguments. The absent parameters variables get turned into zombies (undefined).
ES6, allows you to keep those zombies (undefined) out of scene, by assigning a default parameter value during function declarations. The default value is used only if the parameter is not passed.
// This is not the best method to sum a variable number of arguments // but it shows the power what defaults dofunction withDefaults(a=0, b=0,c=0){ return a+b+c;} function withoutDefaults(a,b,c){return a+b+c;}console.log('withDefaults ' + withDefaults(1,1)); console.log('withoutDefaults ' + withoutDefaults(1,1));
4. Template Literals — Interpolation
The ES6 does Intuitive expression interpolation for strings “if requested”.
And how do we request? By surrounding a string with a backtick. In that case,theJS engine uses the values of the variables inside the string, not the variables themself.
And how does it know what is a variable within a string? Anything mentioned within ${} is a variable. for example value of xxx will be used when mentioned as ${xxx}
const person = { name: 'MPS', age: ‘10’ } console.log(`${name} is ${age} year old`);
5. Enhanced Object Properties
Now you can create javascript Object without providing property names. See below.
const name = 'MPS', age = 10;const person = {name, age} console.log(`${person.name} is ${person.age} years old`)//This is same as ES5 below. const person2 = { "name": name, "age": age };
6. Destructuring Assignments
It's an expression that provides an Intuitive and flexible destructuring of Arrays or Objects into individual variables during the assignment.
It has the capability to match the variable names. Here is a simple example to create new constants from given object properties. As below.
const person = { name: 'MPS', age: ‘10' } const {name, age} = person; console.log(`name is ${name} and age is ${age}`); //Prints name is MPS and age is 10
You can also provide default values. When the given object doesn't have a property with same names the default values will be assigned. See below
const person = { name: 'MPS' } const {name, age='100'} = person; console.log(`name is ${name} and age is ${age}`); //Prints name is MPS and age is 100
The names do not have to be the same. you can destructure the a given object properties into constants with different name. In below example I’m creating a userName and userAge variable taking value from person object
const person = { name: 'MPS', age: ‘10' } const {name :userName,age :userAge} = person; console.log(`userName is ${userName} and userAge is ${userAge}`);
7. Promises
Promises deserve their own post. I’ll cover them in a separate article. For now, just for a quick overview, Java developers can treat ES6 Promises similar (not same) as the javaFuture.
As an oversimplification, consider it as a wrapper on top of an actual value which may be or may not be returned in a close or distant time in the future.
For example, if you invoke a function getItems() that uses an API to fetch the data from a server. Instead of waiting until the server returns a response, getItems()can right away return a Promise object. That promise will be fulfilled in the future and may or may not have the server response.
NOTE: I used words similar and oversimplifications above. Because unlike a true wrapper Promise does not hold the return value, instead it contains the execution logic that needs to be applied to the return value. We will discuss Promises in detail in a separate post.
8. keywords for clean Object-Oriented Programming
If you tried working on Object-oriented Javascript code before 2016, you might know the pain of overhandling the Prototypal Chain and the complexity of this. ES6 introduced class, extend, super, static, scoped let & const, and constructor()which help write clean & concise object-oriented UI code.
Below is some self-explanatory code to demostrate the use of keywords
<html><body>Check console logs</body> <script> window.onload = () => {class Vehicle {constructor(make) { this.make = make } start() { console.log(`${this.make} started`); } }class Car extends Vehicle {constructor(make, maxSpeed) { super(make); this.maxSpeed = maxSpeed; } go(){ super.start(); console.log(`We will drive at ${this.maxSpeed} speed`); } } new Car('toyota', 120).go(); } </script></html>
9. Modules
ES6 onwards, by default each “.js” file, is considered a Module.
The export/importkeywords can be used for exporting/importing values from/to modules without global namespace pollution & name collision. default keyword was also introduced to have one default export from a module & we can also import by wildcard ‘ *’ for a mass-mixin of values.
Lets have a file DoThings.js with following content
In the above case, when we import module Something it will represent the expression. You can import it and name it anything.
/** App.js ****/ import anyName from ’Something'
Conclusion
ES6 came with a lot of more features like Symbols, Map/Set, new built-in Methods for Array/String/Numbers, extended Regex support, and much more. But “in my opinion” the above 9 concepts are the prerequisite for every UI developer to start working on modern-day JS code.
More to come in this series in the next posts. Stay tuned.
Since the beginning of personal computers, few keyboard shortcuts are common among all operating systems and software. The ubiquitous cmd+c (copy), cmd+v(paste) , cmd+z (undo) and cmd+y (redo) I am not sure why, both of my favorite IDEs, Visual Studio Code & Intellij decided to not use cmd+Y for redo.Below are the quick steps to configure cmd+Y for a redo in VS-Code & Intellij Visual Studio Code Open VS Code & Go to keyboard shortcuts There will be a search bar at the top Type “ redo “ in the search bar. You can see on my system its still mapped to shift+cmd+z Double click on ⇧ ⌘ z and the below box will appear. Do not click anywhere or type anything on the keyboard except the key you want to assign, in our case it was cmd+y, so type cmd+y Press Enter and you are done. Now you can use cmd+z for undo and cmd+y to redo like always Intellij It is also as simple as VS-Code...
If you want to avoid overpriced pre-builts like the M1 Mac Mini, Mac Pro, or Dell XPS Desktop without compromising on performance, a self-built desktop is a preferred option. It's also a great choice if you enjoy building things. custom built with ASUS-PRIME-P If you choose to build a custom PC, be prepared to invest time in researching and assembling compatible components. In this post, I'll share my experience building this colorful powerhouse. I'll cover: Why did I do it. Key questions to ask when selecting components Thought process behind component choices Components used in my build Benchmark comparisons . ** My second custom-build **. *** Disclaimer: Not an Apple product. Just a free apple sticker is used *** Why did I do it I decided to get a desktop during the pre-MacM1 era (yes, that’s a thing). After browsing many websites, I found that well-configured prebuilt PCs were overpriced, while cheaper ones had subpar components. Unable to choose betwee...
It's a common use case to have an enterprise application, perform specific work, at a specific time or in response to a specific action. In other words, “There is an ask to execute a Job upon a predefined Trigger ”. This brings us to the need for a Scheduling System. A system, where Jobs & Trigger can be registered and the system will manage the remaining complexity. Thankfully for the Java systems, Quartz is for rescue. It‘s an open-source library that has been extensively used in enterprise applications for more than a decade. Components in Quartz Sub System: Following are the all major component in the Quartz subsystem: Scheduler : It’s the control room of Quartz. It maintains everything required for scheduling, such as managing listeners , scheduling jobs , clustering, transactions & job persistence. It maintains a registry of JobDetails , Listeners & Triggers , and exec...
Once, I was working on a few geospatial APIs handling many time zones. While writing tests, I realized I did not know much about timezones. A lame excuse might be, my subpar schooling as a village kid. Nevertheless, I decided to turn the pages on timezones, what I found was more politics than science. Photo by Arpit Rastogi on Unsplash Before diving into anomalies, let’s talk about history then we will go to science followed by politics. History The world without time zones By 300 BCE, the western world agreed that the earth is round. Each developed civilization devised its unique distinct system to measure distances, times & absolute locations, but relative to prime locations within their civilizations. It all worked in ancient times because long-distance travel was not prevalent among common people. Only merchants or armies traveled long distances. And they already developed systems that worked on their predetermined routes, irrespective of the time differences b...
During our java based microservice development, we extensively use build tools like Maven or Gradle. Usually, IDEs do a lot on our behalf or we just run some predefined commands without checking what's happening inside. Here in this series of 6 posts, I tried to explain Maven. Before I start talking about what Maven is, and its different components, let’s discuss the “why”. Why do we even need Maven? For this, I’ve to first explain the nature of a Java-based project and also need to take you back in history. The “Build” Step. Java is a compilable language, Unlike Python or Javascript, which are interpreted. ie, the code we write in java, can not as-is run on a Java virtual machine (JVM). JVM understands only the bytecode. Therefore, in the Java world, there is always a need for an intermediary step. A step that compiles the java code files into bytecode. That's why after writing the java code, we “somehow” create some deployable (jar, war, ear) to run on ma...
A wise man ( narcissist me ) once said, “Life is all about the question and answers. The trick to a meaningful life is, To ask the right questions to yourself, so you can get on the right path to search for the answer .” The very first question one should always ask oneself is WHY. Let's discuss our WHY in the current case. Why BDD Let's take a step back and start with the well-known software development practice TDD ( Test-Driven Development). In TDD, the very first thing developers do is, set up the technical expectations from the code by writing failing test cases. After the expectation is set, the code is written/modified to finally pass all of the failing tests. It's an Acceptance driven development strategy . TDD works fine to create a robust technically working product. But the whole TDD approach revolves only around technical teams. It barely involves the business analysis or product owners to validate the business aspect of a feature, they get involved o...
Comments