These are the features in ES6 that you should know

ES6 brings more features to the JavaScript language. Some new syntax allows you to write code in a more expressive way, some features complete the functional programming toolbox, and some features are questionable.

ES6 brings more features to the JavaScript language. Some new syntax allows you to write code in a more expressive way, some features complete the functional programming toolbox, and some features are questionable.

let and const

There are two ways for declaring a variable (let and const) plus one that has become obsolete (var).


let

let declares and optionally initializes a variable in the current scope. The current scope can be either a module, a function or a block. The value of a variable that is not initialized is undefined .


Scope defines the lifetime and visibility of a variable. Variables are not visible outside the scope in which they are declared.

Consider the next code that emphasizes let block scope:

let x = 1;
{ 
  let x = 2;
}
console.log(x); //1

In contrast, the var declaration had no block scope:

var x = 1;
{ 
  var x = 2;
}
console.log(x); //2

The for loop statement, with the let declaration, creates a new variable local to the block scope, for each iteration. The next loop creates five closures over five different i variables.

(function run(){
  for(let i=0; i<5; i++){
    setTimeout(function log(){
      console.log(i); //0 1 2 3 4
    }, 100);
  }
})();

Writing the same code with var will create five closures, over the same variable, so all closures will display the last value of i.

The log() function is a closure. For more on closures, take a look at Discover the power of closures in JavaScript.

const

const declares a variable that cannot be reassigned. It becomes a constant only when the assigned value is immutable.


An immutable value is a value that, once created, cannot be changed. Primitive values are immutable, objects are mutable.

const freezes the variable, Object.freeze() freezes the object.

The initialization of the const variable is mandatory.

Modules

Before modules, a variable declared outside any function was a global variable.


With modules, a variable declared outside any function is hidden and not available to other modules unless it is explicitly exported.

Exporting makes a function or object available to other modules. In the next example, I export functions from different modules:

//module "./TodoStore.js"
export default function TodoStore(){}
//module "./UserStore.js"
export default function UserStore(){}


Importing makes a function or object, from other modules, available to the current module.

import TodoStore from "./TodoStore";
import UserStore from "./UserStore";
const todoStore = TodoStore();
const userStore = UserStore();


Spread/Rest

The … operator can be the spread operator or the rest parameter, depending on where it is used. Consider the next example:


const numbers = [1, 2, 3];
const arr = ['a', 'b', 'c', ...numbers];
console.log(arr);
["a", "b", "c", 1, 2, 3]


This is the spread operator. Now look at the next example:

function process(x,y, ...arr){
  console.log(arr)
}
process(1,2,3,4,5);
//[3, 4, 5]
function processArray(...arr){
  console.log(arr)
}
processArray(1,2,3,4,5);
//[1, 2, 3, 4, 5]

This is the rest parameter.

arguments

With the rest parameter we can replace the arguments pseudo-parameter. The rest parameter is an array, arguments is not.


function addNumber(total, value){
  return total + value;
}
function sum(...args){
  return args.reduce(addNumber, 0);
}
sum(1,2,3); //6


Cloning

The spread operator makes the cloning of objects and arrays simpler and more expressive.


The object spread properties operator will be available as part of ES2018.

const book = { title: "JavaScript: The Good Parts" };
//clone with Object.assign()
const clone = Object.assign({}, book);
//clone with spread operator
const clone = { ...book };
const arr = [1, 2 ,3];
//clone with slice
const cloneArr = arr.slice();
//clone with spread operator
const cloneArr = [ ...arr ];


Concatenation

In the next example, the spread operator is used to concatenate arrays:


const part1 = [1, 2, 3];
const part2 = [4, 5, 6];
const arr = part1.concat(part2);
const arr = [...part1, ...part2];


Multiple inheritance

The spread operator, like Object.assign(), can be used to copy properties from one or more objects to an empty object and do multiple inheritance.


const authorGateway = { 
  getAuthors : function() {},
  editAuthor: function() {}
};
const bookGateway = { 
  getBooks : function() {},
  editBook: function() {}
};
//copy with Object.assign()
const gateway = Object.assign({},
      authorGateway, 
      bookGateway);

//copy with spread operator
const gateway = {
...authorGateway,
...bookGateway
};

Property short-hands

Consider the next code:


function BookGateway(){
function getBooks() {}
function editBook() {}

return {
getBooks: getBooks,
editBook: editBook
}
}

With property short-hands, when the property name and the name of the variable used as the value are the same, we can just write the key once.

function BookGateway(){
function getBooks() {}
function editBook() {}

return {
getBooks,
editBook
}
}

Here is another example:

const todoStore = TodoStore();
const userStore = UserStore();

const stores = {
todoStore,
userStore
};

Destructuring assignment

Consider the next code:


function TodoStore(args){
const helper = args.helper;
const dataAccess = args.dataAccess;
const userStore = args.userStore;
}

With destructuring assignment syntax, it can be written like this:

function TodoStore(args){
const {
helper,
dataAccess,
userStore } = args;
}

or even better, with the destructuring syntax in the parameter list:

function TodoStore({ helper, dataAccess, userStore }){}

Below is the function call:

TodoStore({
helper: {},
dataAccess: {},
userStore: {}
});

Default parameters

Functions can have default parameters. Look at the next example:


function log(message, mode = "Info"){
console.log(mode + ": " + message);
}
log("An info");
//Info: An info
log("An error", "Error");
//Error: An error


Template string literals

Template strings are defined with the &nbsp;charter. With template strings, the previous logging message can be written like this:</p><p><br></p><pre class="ql-syntax" spellcheck="false">function log(message, mode= "Info"){ console.log(${mode}: ${message}); } </pre><p>Template strings can be defined on multiple lines. However, a better option is to keep the long text messages as resources, in a database for example.</p><p>See below a function that generates an HTML that spans multiple lines:</p><pre class="ql-syntax" spellcheck="false">function createTodoItemHtml(todo){ return <li>
<div>${todo.title}</div>
<div>${todo.userName}</div>
</li>`;
}

Proper tail-calls

A recursive function is tail recursive when the recursive call is the last thing the function does.

The tail recursive functions perform better than non tail recursive functions. The optimized tail recursive call does not create a new stack frame for each function call, but rather uses a single stack frame.

ES6 brings the tail-call optimization in strict mode.

The following function should benefit from the tail-call optimization.

function print(from, to)
{
const n = from;
if (n > to) return;

console.log(n);
//the last statement is the recursive call
print(n + 1, to);
}
print(1, 10);


Note: the tail-call optimization is not yet supported by major browsers.

Promises

A promise is a reference to an asynchronous call. It may resolve or fail somewhere in the future.

Promises are easier to combine. As you see in the next example, it is easy to call a function when all promises are resolved, or when the first promise is resolved.

function getTodos() { return fetch("/todos"); }
function getUsers() { return fetch("/users"); }
function getAlbums(){ return fetch("/albums"); }
const getPromises = [
getTodos(),
getUsers(),
getAlbums()
];
Promise.all(getPromises).then(doSomethingWhenAll);
Promise.race(getPromises).then(doSomethingWhenOne);
function doSomethingWhenAll(){}
function doSomethingWhenOne(){}


The fetch() function, part of the Fetch API, returns a promise.

Promise.all() returns a promise that resolves when all input promises have resolved. Promise.race() returns a promise that resolves or rejects when one of the input promises resolves or rejects.

A promise can be in one of the three states: pending, resolved or rejected. The promise will in pending until is either resolved or rejected.

Promises support a chaining system that allows you to pass data through a set of functions. In the next example, the result of getTodos() is passes as input to toJson(), then its result is passed as input to getTopPriority(), and then its result is passed as input to renderTodos() function. When an error is thrown or a promise is rejected the handleError is called.

getTodos()
.then(toJson)
.then(getTopPriority)
.then(renderTodos)
.catch(handleError);
function toJson(response){}
function getTopPriority(todos){}
function renderTodos(todos){}
function handleError(error){}

In the previous example, .then() handles the success scenario and .catch()handles the error scenario. If there is an error at any step, the chain control jumps to the closest rejection handler down the chain.

Promise.resolve() returns a resolved promise. Promise.reject() returns a rejected promise.

Class

Class is sugar syntax for creating objects with a custom prototype. It has a better syntax than the previous one, the function constructor. Check out the next exemple:


class Service {
doSomething(){ console.log("doSomething"); }
}
let service = new Service();
console.log(service.proto === Service.prototype);


All methods defined in the Service class will be added to theService.prototype object. Instances of the Service class will have the same prototype (Service.prototype) object. All instances will delegate method calls to the Service.prototype object. Methods are defined once onService.prototype and then inherited by all instances.

Inheritance

“Classes can inherit from other classes”. Below is an example of inheritancewhere the SpecialService class “inherits” from the Service class:


class Service {
doSomething(){ console.log("doSomething"); }
}
class SpecialService extends Service {
doSomethingElse(){ console.log("doSomethingElse"); }
}
let specialService = new SpecialService();
specialService.doSomething();
specialService.doSomethingElse();

All methods defined in the SpecialService class will be added to the SpecialService.prototype object. All instances will delegate method calls to the SpecialService.prototype object. If the method is not found in SpecialService.prototype, it will be searched in the Service.prototypeobject. If it is still not found, it will be searched in Object.prototype.

Class can become a bad feature

Even if they seem encapsulated, all members of a class are public. You still need to manage problems with this losing context. The public API is mutable.


class can become a bad feature if you neglect the functional side of JavaScript. class may give the impression of a class-based language when JavaScript is both a functional programming language and a prototype-based language.

Encapsulated objects can be created with factory functions. Consider the next example:

function Service() {
function doSomething(){ console.log("doSomething"); }

return Object.freeze({
doSomething
});
}

This time all members are private by default. The public API is immutable. There is no need to manage issues with this losing context.

class may be used as an exception if required by the components framework. This was the case with React, but is not the case anymore with React Hooks.

For more on why to favor factory functions, take a look at Class vs Factory function: exploring the way forward.

Arrow functions

Arrow functions can create anonymous functions on the fly. They can be used to create small callbacks, with a shorter syntax.


Let’s take a collection of to-dos. A to-do has an id , a title , and a completed boolean property. Now, consider the next code that selects only the title from the collection:

const titles = todos.map(todo => todo.title);

or the next example selecting only the todos that are not completed:

const filteredTodos = todos.filter(todo => !todo.completed);

this

Arrow functions don’t have their own this and arguments. As a result, you may see the arrow function used to fix problems with this losing context. I think that the best way to avoid this problem is to not use this at all.


Arrow functions can become a bad feature

Arrow functions can become a bad feature when used to the detriment of named functions. This will create readability and maintainability problems. Look at the next code written only with anonymous arrow functions:


const newTodos = todos.filter(todo =>
!todo.completed && todo.type === "RE")
.map(todo => ({
title : todo.title,
userName : users[todo.userId].name
}))
.sort((todo1, todo2) =>
todo1.userName.localeCompare(todo2.userName));

Now, check out the same logic refactored to pure functions with intention revealing names and decide which of them is easier to understand:

const newTodos = todos.filter(isTopPriority)
.map(partial(toTodoView, users))
.sort(ascByUserName);
function isTopPriority(todo){
return !todo.completed && todo.type === "RE";
}

function toTodoView(users, todo){
return {
title : todo.title,
userName : users[todo.userId].name
}
}
function ascByUserName(todo1, todo2){
return todo1.userName.localeCompare(todo2.userName);
}

Even more, anonymous arrow functions will appear as (anonymous) in the Call Stack.

For more on why to favor named functions, take a look at How to make your code better with intention-revealing function names.

Less code doesn’t necessary mean more readable. Look at the next exampleand see which version is easier for you to understand:

//with arrow function
const prop = key => obj => obj[key];
//with function keyword
function prop(key){
return function(obj){
return obj[key];
}
}

Pay attention when returning an object. In the next example, the getSampleTodo() returns undefined.

const getSampleTodo = () => { title : "A sample todo" };
getSampleTodo();
//undefined


Generators

I think the ES6 generator is an unnecessary feature that makes code more complicated.


The ES6 generator creates an object that has the next() method. The next()method creates an object that has the value property. ES6 generators promote the use of loops. Take a look at code below:

function* sequence(){
let count = 0;
while(true) {
count += 1;
yield count;
}
}
const generator = sequence();
generator.next().value;//1
generator.next().value;//2
generator.next().value;//3

The same generator can be simply implemented with a closure.

function sequence(){
let count = 0;
return function(){
count += 1;
return count;
}
}
const generator = sequence();
generator();//1
generator();//2
generator();//3

For more examples with functional generators take a look at Let’s experiment with functional generators and the pipeline operator in JavaScript

Conclusion

let and const declare and initialize variables.


Modules encapsulate functionality and expose only a small part.

The spread operator, rest parameter, and property shorthand make things easier to express.

Promises and tail recursion complete the functional programming toolbox.

For more on JavaScript take a look at:

Discover Functional Programming in JavaScript with this thorough introduction


Learn these JavaScript fundamentals and become a better developer

Let’s explore objects in JavaScript

How point-free composition will make you a better functional programmer

How to make your code better with intention-revealing function names

Make your code easier to read with Functional Programming


By : Cristi Salcescu


What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!

Learn JavaScript in 60 Minutes | JavaScript Crash Course | JavaScript Tutorial |

This video on "JavaScript" will help you learn JavaScript basics and fundamental concepts in 60 minutes. This will provide you in-depth knowledge about the JavaScript fundamentals that will help you write your own code in JavaScript and build a website. This JavaScript tutorial covers following topics..

==================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Svelte.js - The Complete Guide

The Complete JavaScript Course 2019: Build Real Projects!

Advanced CSS and Sass: Flexbox, Grid, Animations and More!

CSS - The Complete Guide (incl. Flexbox, Grid & Sass)

CSS Bootcamp - Master CSS (Including CSS Grid / Flexbox)

Build Responsive Real World Websites with HTML5 and CSS3

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

JavaScript - Step By Step Guide For Beginners

JavaScript | How to use classes in JavaScript

JavaScript | How to use classes in JavaScript

Classes in JavaScript are a special syntax for its prototypical inheritance model that resembles class based inheritance in other object oriented languages. Classes are just special functions that can be declared to resembles classes in other languages. In JavaScript, we can have class declarations and class expressions, because they are just functions. So like all other functions, there are function declarations and function expressions. Classes serve a templates to create new objects.

Defining Classes

To declare a class, or make a class declaration, we use the class keyword to do so. For example, to declare a simple class, we can write:

class Person{
  constructor(firstName, lastName) {
    this.firstName= firstName;
    this.lastName = lastName;
  }
}

Class declarations aren’t hoisted so they can used before they are defined in the code, as the JavaScript interpreter will not automatically pull them up to the top. So the class above won’t work before it’s defined in the code like the following:

const person = new Person('John', 'Smith');
class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

We will get a ReferenceError if we run the code above.

We can also define a class by a class expression, which is an alternative syntax for defining a class. They can be named or unnamed. We can also assign a class to a variable like we do with functions. If we do that, we can reference the class by its name. For example, we can define:

let Person = class {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

To get the name of the unnamed classes above, we can get the name with the name property, like so:

console.log(Person.name);


We can also undefined a named class like the following:


let Person = class Person2{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

Then to get the name of the class, we can use the name property again. So we if we write:

console.log(Person.name)


we get Person2 logged.

The class body is defined with curly brackets. We define the class members inside the brackets. The body of the class is executed in strict mode, so everything defined in strict mode applies to the definition of a class, so we can’t define variables with out some keyword before it like var , let or const , and many other rules apply when you define a class. Classes in JavaScript also have a constructor method that lets us set fields when the object is instantiated with a class . Each class can only have one constructor method in it. If there’s more than one, then SyntaxError will be thrown. A constructor have to also call the super method to call the constructor of the super class inside if it the class extends a parent class.

Methods that aren’t declared static constitutes of the prototypical methods of the class. They are called after an object has been created by using the new keyword. For example, the following class have only prototypical methods:


class Person{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName(){
    return `${this.firstName} ${this.lastName}`  
  }
  sayHi(){
    return `Hi, ${this.firstName} ${this.lastName}`
  }
}

In the Person class above, fullName and sayHi are prototypical methods. They are called like this:

const person = new Person('Jane', 'Smith');
person.fullName() // 'Jane Smith'

Static methods are methods that can be called without creating an object from the class using the new keyword. For instance, we can have something like the following:


class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  static personCount() {
    return 3;
  }
}

We can call the personCount function without using the new keyword to create an instance of the class. So if we write:

Person.personCount

We get 3 returned.

The this value inside prototypical methods will be the value of the object. For static methods the value of this has the class that the static method is in as the value.

Getters and Setters

JavaScript classes can have getters and setter functions. Getters, as the name suggests, is a method that lets us get some data from a class. Setters are methods that gives us the ability to set some fields of the class. We denote getter functions with the get keyword and setters with the set keyword. For example, we can write a class that has getters and setters like the following:

class Person {
  constructor(firstName, lastName) {
    this._firstName = firstName;
    this._lastName = lastName;
  }
  get fullName() {
    return `${this.firstName} ${this.lastName}`
  }
  get firstName() {
    return this._firstName
  }
  get lastName() {
    return this._lastName
  }
  sayHi() {
    return `Hi, ${this.firstName} ${this.lastName}`
  }
  set firstName(firstName) {
    this._firstName = firstName;
  }
  set lastName(lastName) {
    this._lastName = lastName;
  }
}

Then when we use the new keyword to construct a Person object, we can use them in the following way:


const person = new Person('Jane', 'Smith');
person.firstName = 'John';
person.lastName = 'Doe';
console.log(person.firstName, person.lastName)

Since we have the getter and setter functions, we can use them to set the data directly to set the data for firstName and lastName of the Person class. In the setter functions, which start with the keyword set , what we assign to them get passed into the parameters and set in the member of the class. In the getter functions, which are denote by get we return the member values so that we can use them.

JavaScript Inheritance

In JavaScript, we can create classes where the properties can be included in the properties of a child class.

So, we can have a high-level class that contains the properties that are common to all the child classes, and the child class can have its own special properties that are not in any other classes.

For example, if we have an Animal class with the common properties and methods, like name and the eat method, then the Bird class can just inherit the common properties in the Animal class. They don’t have to be defined in the Bird class again.

We can write the following to do inheritance in JavaScript:

class Animal {
  constructor(name) {
    this.name = name;
  }
  eat() {
    console.log('eat');
  }
}
class Bird extends Animal {
  constructor(name, numWings) {
    super(name);
    this.numWings = numWings;
  }
}
const bird = new Bird('Joe', 2);
console.log(bird.name)
bird.eat();

In the example above, we have the parent class, Animal, that has the eat method, which all classes that extends from Animal will have, so they don’t have to define eat again.

We have the Bird class which extends the Animal class. Note that in the constructor of the Bird class, we have the super() function call to call the parent’s class constructor to populate the properties of the parent class in addition to the properties of the child class.

Classes cannot extend regular objects, which cannot be constructed with the new keyword. If we want to inherit from a regular object, we have to use the Object.setPrototypeOf function to set a class to inherit from a regular object. For example:

const Animal = {
  eat() {
    console.log(`${this.name} eats`);
  }
};
class Cat{
  constructor(name) {
    this.name = name;
  }
}
class Chicken{
  constructor(name) {
    this.name = name;
  }
}
Object.setPrototypeOf(Cat.prototype, Animal);
Object.setPrototypeOf(Chicken.prototype, Animal);
let cat = new Cat('Bob');
let chicken = new Chicken('Joe');
cat.eat();
chicken.eat();

If we run the example code above, we have see Bob eats and Joe eats logged because we have inherited the eat function from the Animal object.

this Keyword

The this keyword allows us to access the current object’s properties inside an object, unless you’re using arrow functions.

As we can see from the above example, we can get the properties of the instance of the child and the parent class in the object.

Mixins

We can use mixins to do multiple inheritance in JavaScript. Mixins are templates for creating classes. We need mixins to do multiple inheritance because JavaScript classes can only inherit from one super class, so multiple inheritance isn’t possible.

For example, if we have a base class, we can define mixins to incorporate the members from multiple classes into one by composing the mixins by calling one and then pass the returned result into the next one as the argument, an so on, like so:

class Base {
  baseFn() {
    console.log('baseFn called');
  }
}
let classAMixin = Base => class extends Base {
  a() {
    console.log('classAMixin called');
  }
};
let classBMixin = Base => class extends Base {
  b() {
    console.log('classBMixin called');
  }
};
class Bar extends classAMixin(classBMixin(Base)) {}
const bar = new Bar();
bar.baseFn()
bar.a()
bar.b()

In the code above, we have the Base class which we pass into the classBMixin to get the b function into the Base class, then we call the classAMixin by passing in the result of classBMixin(Base) into the argument of the classAMixin to return the a function from classAMixin into the Base class and then return the whole class with all the functions from all the classes incorporated into one.

If we call all the functions above like we did by creating an instance of the Bar object and then call the baseFn , a and b functions, then we get:

baseFn called
classAMixin called
classBMixin called

This means that we have all the functions from the mixins incorporated into the new Bar class.

In JavaScript, classes are just syntactic sugar to make the prototypical inheritance of JavaScript clearer by letting us structure the code in a way that’s more like typical inheritance class based object oriented inheritance pattern. This means that we write classes to and use the new keyword to create objects from the classes, but underneath the syntactic sugar, we are still using prototypical inheritance to extend objects. We can extend classes from objects and we can also use mixins to do multiple inheritance in of JavaScript classes.