Modern JavaScript! 👩🏻‍💻

Irushinie Muthunayake
Geek Culture
Published in
11 min readJun 1, 2021

New features in ES6 every developer must know 📝

Special features of modern JavaScript

📍 JavaScript can be defined as a very powerful programming language and it is actually based on ECMA script. (ECMA is the foundation and javascript is on top of that)

📍 JavaScript ES6 is also called ECMAScript 6 or ECMAScript 2015 And this was introduced in 2015 as a new version of JavaScript.

In this article, I'm going to discuss the below topics:

1. Scope

2. Constants

3. Arrow Function

4. Function and Arrow Function

5. Handling Objects

6. Freeze method

7. Template

8. Classes

9. Destructuring

10. JavaScript Callback Function and Promises

11. Async function / await

Let’s get to the coding 😎

① Scope

This is the accessibility of variables in javascript So the scope controls the visibility of variables of your code. There are two types of scope:

Global variables — These are declared outside of a block. Variables that are declared inside the Global scope can be accessed anywhere in our code.

Local variables These are declared inside of a block. Variables that are declared inside the Local scope can be accessed only within that particular block.

✸ The “let” keyword

✬ The keyword let” was introduced by ES6 for declaring variables. So we use the “let” keyword to define a variable, which means that a particular variable isn't visible outside of its scope.

Consider the below example to understand this concept:

☛ Code snippet with “var” keyword. (without the “let” keyword)

Output:

☛ Code snippet with the “let” keyword.

Output:

✬ So here we got this output as we defined the k inside the for loop so that it can’t be accessed outside the “for loop”.

✬ The “let” keyword is very much useful when you code very lengthy scripts, multiple functions.. etc. So in case if you use the same variable in another place, you may face errors and sometimes you will get unexpected results at runtime. So, the “let” keyword will help you to avoid those issues as you can use the keyword “let” to define variables and that will guarantee that variable is not visible outside of that block.

The main difference between var and let:

(Hoisting is a process in JS which means that the functions and variable declarations are gone to the top of their scope before the execution of code.)

② Constants

The “const” keyword

✬ This was introduced to create constants as a feature of ES6.

✬ Consider the below example.

Output:

Colombo

Now consider the below example again.

Output:

We got this error as the “city” is a const variable. So it was not allowed to change its value, Accordingly, once a constant is initialized, we do not have the ability to change its value.

But the most important thing is:

Constant is protecting only a “variable” that is not an object or an array. So if it is an object or an array, you can change the value though it is a constant.

Look at the below code and its output to understand this.

Example:

Output:

③ Arrow Function ( ) =>

✬ Arrow function is also another interesting feature introduced by the ES6(ECMAScript 6) version of JavaScript.

✬ “Arrow” functions give the ability to make function expressions much cleaner than the traditional functions.

Example 1:

//traditional function expression
let w= function(w, x) {
return w* x;
}

//with arrow functions
let w= (w, x) => w*x;

Example 2:

Output:

120
120
120
25

For your memory 🤓➜

🥢 You can omit the parentheses if there is only one argument in the function.

④ Function and Arrow Function

✮ Function and Arrow function don't behave in the same way. Because when considering a normal function, it prints the entire function side that and the keyword “this” represents the caller of the function. But if you write an arrow function, the “this” keyword doesn't represent the caller.

Let’s understand that using the below coding example:

Output:

So accordingly this happens as the “this” keyword in the arrow function doesn’t represent the caller.

⑤ Handling Objects

✬ Objects in JavaScript give you the ability to store multiple collections of data and the data inside these objects be of any type.

Below is an example of an Object in JavaScript

// object
const Employee= {
firstName: 'Joey',
Eid:12
};

✬ Let’s see the below example to understand more about this:

Example :

Figure 1

Output:

According to the above figure 1, Why there is no key-value pair in “SQRT2” in the code (line no 13) 🧐

The reason is, in let SQRT2=Math.SQRT2; -it has taken a variable from another module. so you can specify the same thing inside the object (vehicle). Therefore no need to have a value inside the SQRT2and this is the same asSQRT2:SQRT2.

Example :

  1. Let’s see what will be the output if you add [status]: “ready” dynamic property.

Output: It will give you the following error

ReferenceError: status is not defined

2. Now create a variable called status at the beginning as follows

Figure 2

Output:

So accordingly, The dynamic property means, you can have a placeholder as a key if you do not know what the key would be at the execution time.

For example, if you need to define an object to send it to the user through a service, you have no idea what the key. At that time, you can have a placeholder like the above example(Figure 2).

⑥ Freeze method

✬ The objects in JavaScript are mutable. This means we have the ability to change the value of an object anytime we need it.

So what if we need to make the javascript object immutable? 🙄

We can accomplish this is by using the method freeze()😍 So if we use this “freeze” method, that means it freezes the object. So no one can change the value of the frozen object.

If you call "Object.freeze(obj)", then it will not change the value.

Example: Without using the freeze method

Output:

{ country: 'Sri Lanka' } 
{ country: 'Australia' }

Example: With using the freeze method

Output:

{ country: 'Sri Lanka' }
{ country: 'Sri Lanka' }

✨ So from the above example, we can understand that if you call, Object.freeze()then it will not change its value.

✨ There is an object that passes from service to service and you can use this freezing method if you need to make sure that the object doesn't change from function to function.

💥 Important :

Consider the below code and its output:

Output:

According to the output, though the name did not change, the value of t1 has changed.

WHY 🙄

The reason is, if you call the “Object. freeze” method, it will freeze only the first level values and It will not freeze the inner level or the second-level objects.

⑦ Template

✬ JavaScript template strings give the ability to utilize embedded expressions or strings in the formation of a string. Let’s understand javascript template strings using the below example.

Output:

Happy Work Anniversary Joey Boomer.Good luck for completing 2 years!

So using the ${} you can take properties from the objects.

⑧ Classes

✬ This feature is also one of the features which were introduced by the ES6 version of JS. One way of a class declaration in JavaScript can be shown as below.

class Person{
constructor(name, age){
this.name= name;
this.age= age; }}

📍 Though we have constructors from the class name in Java, Here we have it using the “constructor” keyword.

Below is an example to show the overriding happen in JavaScript

Output:

Jeo is an Employee
Chriss is an Employee an manager of QA
this function is overriden

📍 So accordingly we can override the function with anything when calling through the object.

📍 You may have functions in your class but runtime. But in calling time, you can override the function if you want.

⑨ Destructuring

JavaScript Destructing is also introduced by ES6 and it helps to assign properties of objects and array values into distinct variables.

For Example: Before ES6

Output:

Joey
2
male

For Example: With ES6

Output:

Joey
2
male

📝 Note:

☛ In Object destructuring, the order of the name will never matter at all

☛ When destructuring objects in JavaScript, do not forget to use the similar(same) name for the variable as the key of the corresponding object.

Example : ❶ — Way of Handling Destruct

Example : ❷—Destructuring with functions

Output:

148.83999999999997

Let’s extend the above code as below

Output:

148.83999999999997
148.840
148.84000

const area2=({base}, {round=3}={}) Here you have base, round and you can assign a default value if round value is not passed.

✹ Another way of using destruct with a function

Below is the traditional way without “destruct”.

Below is the way with “destruct”.

Example : ❸ — Destructuring with Arrays

You can perform this restructuring with arrays as below examples

Example Ⅰ:

Example Ⅱ:

Output:
10
50

In Example Ⅱ, you could see that I have assigned values to Jan, Feb, Mar, and May. And there are 4 properties and 5 values as one month are kept empty (const [jan, feb, mar, , may])So now when we print “Jan” it gave 10 as the output. The “empty property” next to “mar” automatically skipped the value “40” and assigned 50 into may (as in the output).

Example Ⅲ: With rest operator

Output:

In here, [month1, …otherMonths] there are three-dot operators in front of “otherMonths”. Accordingly, the value “10” has been assigned to “month1” and the rest of the values has been assigned to “otherMonths” as a new array. By using the rest operator, you can copy one array into another array.

⑩ JavaScript Callback Function and Promises

Callback Function

(Ref:https://www.w3schools.com/js/js_callback.asp)

Assume you go to a juice bar and order some juice, gave your name to the wait staff person. Then you sit back till your order is ready. And then the wait staff person will serve the next person and so on. At the time your juice order is ready, they will call by your name so that you can go and collect your order. So the callback function is also working in the same way as this scenario.

✹ A callback function can be defined as a function that accepts another function as an argument and will automatically invoke that function when it finishes. The advantage of using this is that we can wait for the previous function’s (previous function call) result and then perform another function call

For Example:

Output:
Hi Joey
I am callback function

Promise

(Ref:https://www.w3schools.com/js/js_promise.asp)
Promise

✹ A promise depicts an operation that hasn’t been completed yet. A promise in JavaScript is an object that generates a single value in the future. So It can be resolved, or not resolved.

✹ Fulfilled, rejected, or pending are the three possible states of a JavaScript promise.

Example:

Output:
196783
finished

✬ Accordingly, it will take some time to give the output as it needs to go and collect the data.

function fetchWebpage(URL) ➜ The function “fetchWebpage” takes the URL

return new Promise((resolve,reject)➜ Returning of a new promise, resolve and reject.

So why did we wrap the below with new promise 🙄

return new Promise((resolve,reject)=>{
http.get(url,response=>{
let responseData;
response.on('data',data=> responseData=responseData+data);
response.on('end',()=> resolve(responseData));
response.on('error', reject);
});
})

Because “http.get” is something where it takes time to go to the server and take the response back. So here it needs to wrap this with a promise and when the response is ready it will trigger that the promise is completed.

Now look at the example below:

Output: 2 undefined

📚 Note: The output is 2 undefined because it calls console.log(“2”, resp.length before the result comes.

⑪ Async function / await

✬ We use the “async” function to return a promise. The keyword “async” is used with a function. After using the “async” keyword with a function, then that particular function is asynchronous.

📍 The “await” is only valid inside the async function. So we always use this inside the async function.

Syntax (async):

The below is an extended version of the example we discussed under the callback function:

Output:
2 undefined
3 197176

📗resp= await fetchWebpage(‘http://irushiniedilmika.medium.com/')

As we used “await” inside the async function, it says to call the “fetchWebpage” that will return a promise object and wait until the promise resolves. So once the promise is resolved, continue to the next line.

Advantages of JavaScript

📍 JavaScript is simple to learn, understand and implement.

📍 Interoperability is another advantage of JavaScript, it means that the javascript can be used in vast categories of applications.

📍 · Rich interfaces can be created using JS.

📍 Extended functionalities.

📍 It has a large number of libraries.

Disadvantages of JavaScript

📍 Client-Side Security. (As the code executes on the users’ pc, sometimes malicious activities can occur.

📍 Browser Support (Sometimes js are implemented differently with different kinds of browsers).

--

--