Modern Javascript features

Share

In the modern Javascript world, there are plenty of new, fast and reliable features. When ES6 (ECMAScript – Javascript standardization) came in the middle of 2015, Javascript became one of the strongest programming languages. That version was first one to include classes and modules, and also used strict mode (easier to find an error). In June 2018, the newest ES9 or ES2018 was released. Between those three years (from June 2015 to June 2018), ECMAScript was making many changes to Javascript language, and there are many helpers we can use in our development.

var, const & let

With ES6, we’ve got new keywords const and let, too. In ES6+, it’s not recommended to use var because that’s the weakest signal available in Javascript. Keyword const means that identifier won’t be reassigned. Contrary to that, let means that variable may be reassigned and it’s block-scoped keyword. So a variable declared in a block with the let is only available for use within that block.

let howMany = 4;
   
if(howMany > 3){ 
  let displayApples = "I have more than 3 apples"  console.log(displayApples); // "I have more than 3 apples" 
}  

console.log(displayApples); // displayApples is not defined

The const declarations are also block-scoped and both keywords (const and let) can’t be re-declared. However, when const is an object, the property can be updated as well.

// This is OK - updating apples
let apples = "3 apples";
apples = "4 apples";

// This is NOT OK - re-declare pears 
let pears = "3 pears";
let pears = "4 pears"; // error: Identifier 'pears' has already been declared   

// This is OK - different scopes, same variable name 
let bananas = "3 bananas";
if( true ){
  let bananas = "4 bananas";
  console.log(bananas); // "4 bananas" 
}
  console.log(bananas); // "3 bananas"   

// CONST part   

// This is NOT OK - updating const
const appleConst = "3 apples";
applesConst = "4 apples"; // error: Assignment to constant variable.    

// This is NOT OK - re-declare const 
const pearsConst = "3 pears";
const pearsConst = "4 pears"; // error: Identifier 'pearsConst' has already been declared   

// This is OK - update property of CONST object 
const showMe = {
  what: "apples",
  howMany: 3
};   

showMe.howMany = 4;
console.log(showMe.howMany + ' ' + showMe.what); // "4 apples" - property howMany was updated

forEach Helper

This method calls a provided function once for each element in an array, in order. It doesn’t execute the function for array elements without values.

var colors = ['red', 'yellow', 'purple'];   

colors.forEach(function(color) { 
  console.log(color);
});

every and some Helper

The every method checks if all elements in array pass a test implemented by the provided function.

The some method checks if any of the elements in array pass a test implemented by the provided function, too.

var applesInBaskets = [32, 33, 16, 40];
var pearsInBaskets = [32, 33, 39, 40];
var bananasInBaskets = [6, 10, 12, 17];

function checkBasket(basket) {
    return basket >= 20;
}

// All baskets in array should have more than 20 fruits to return TRUE

console.log(applesInBaskets.every(checkBasket)); // false - one basket with apples has less than 20 apples (16)
console.log(pearsInBaskets.every(checkBasket)); // TRUE - all baskets with pears have more than 20 pears (32, 33, 39 and 40)
console.log(bananasInBaskets.every(checkBasket)); // false - all baskets with bananas have less than 20 bananas

// At least one basket in array should have more than 20 fruits to return TRUE
console.log(applesInBaskets.some(checkBasket)); // TRUE - three baskets with apples have more than 20 apples (32, 33, 40)
console.log(pearsInBaskets.some(checkBasket)); // TRUE - all baskets with pears have more than 20 apples (32, 33, 39, 40)
console.log(bananasInBaskets.some(checkBasket)); // false - all baskets with bananas have less than 20 bananas

map Helper

This Helper has so many similarities with already described forEach Helper. However, while forEach method simple calls a provided function on each element in array, map method actually returns a new Array of the same size – it returns transformed elements.

let arr = [1, 2, 3, 4, 5];

let doubled = arr.map(num => {
    return num * 2;
});

console.log(doubled); // [2, 4, 6, 8, 10]

find and findIndex Helper

The find method returns the value of the first element in an array that passes a given test. The findIndex method is very similar, but instead of value, it returns index of element that passes test implemented by the provided function.

let fruit = ['banana','pear','ananas', 'apple', 'peach'];
let stuffs = ['desk', 'pen', 'wardrobe'];

function findApple(newFruit){
  return newFruit==='apple';
}

console.log(fruit.find(findApple)); // "apple"
console.log(stuffs.find(findApple)); // undefined

console.log(fruit.findIndex(findApple)); // 3
console.log(stuffs.findIndex(findApple)); // -1

filter Helper

The filter method creates a new array with all elements that pass the test implemented by the provided function.

let baskets = [12, 5, 8, 130, 44];

function moreThanTenApples(element) {
   return (element >= 10);
}

let passed = baskets.filter(moreThanTenApples);
console.log("Those baskets have more than 10 apples: " + passed ); // "Those baskets have more than 10 apples: 12, 130, 44"

Template literals

Template literals is a way to create and handle dynamic string or string templates. It’s so much easier to carry strings with those features. It doesn’t matter anymore which to choose: ‘single quote’ or “double quote”. And also, there’s the most important new stuff: `backticks` in JS strings. Inside backticks, you can combine single or double quotes as much as you want to.

let firstString = `He says: "Ok, let's do that".`; // He says: "Ok, let's do that".

// Variable interpolation
let name = "Joe";
let secondString = `Hi, my name is ${name}.`; // Hi, my name is Joe.

// Expression interpolation
let isMarry = true;
let thirdString = `Please say hello to ${isMarry ? "Marry" : "Mike"}!`; // Please say hello to Marry!

// Multi-line
let paragraph = `This is first line,
but this should be on second line.
And this on third line.`;
/*
This is first line,
but this should be on second line.
And this on third line.
*/

// HTML templates
let HTMLstring = `
<div>
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
  </ul>
</div>
`;
// returns HTML with unorder list and three elements

Spread/rest operator

With ES2015, we’ve got also one new useful operator ‘…’ (three dots). If this operator splits array into the list of arguments, we call it – spread operator. However, if this operator groups list of arguments in array, we call it – rest operator.

// Spread operator
function fruits(apples, bananas, pears){
  console.log(apples);
  console.log(bananas);
  console.log(pears);
}
fruitsNo = [7, 9, 14];

fruits(...fruitsNo);
/*
7
9
14
*/

// Rest operator
function getFruitsByBasket(apples, bananas, pears) {
  var fruits = [...arguments];
  var howMany = fruits.map(function (fruit){
       return fruit;
  });
  console.log(`In baskets, there are ${howMany} fruits.`)
}

getFruitsByBasket(6, 7, 8); // In baskets, there are 6,7,8 fruits.

Conclusion

Modern Javascript makes developer’s life much easier. Some of described features are wide accepted by JS community. However, Javascript is the fastest-growing language in developer’s world and possibilities of modern JS are almost infinite.

Share

Sign in to get new blogs and news first:

Leave a Reply

Miloš Ristić

Frontend Developer @ enjoy.ing
mm

Miloš Ristić is front-end developer with over 6+ years of experience with many front-end tools, libraries and frameworks. His skills range goes from full-stack WordPress development to mobile applications development using JS frameworks. He loves everything around JS.

Sign in to get new blogs and news first.

Categories