Search

Functions in JavaScript

In this blog we will learn more about the JavaScript functions. A function can be defined as a piece or block of code which is executed to perform a specific task. In other words, it is a group of reusable code which can be called anywhere in the program which makes the life of developers easy by eliminating the need of writing the same piece of code again and again. Functions help developers to divide larger programs into smaller chunks and also make them easily manageable. Functions allow us to define a block of code, give it a name and then execute it as many times as we want. We can define a JavaScript function using the keyword function.  Let’s explore JavaScript functions in detail. JavaScript Function Overview:- As in any other scripting and programming language, functions are one of the fundamental building blocks in JavaScript. A function is nothing but a series of statements that can be used to perform a task. In simple terms a function takes inputs and returns an output. In order to use a function, first we need to define it and then call the same. JavaScript provides us with many built in functions, for example  alert (“Welcome to Knowledge Hut”);  document.write(“Welcome to knowledge hut blogs”);  Math.sqr(3); Generally, functions always return a value. For example, a mathematical function performs calculations on the input data and returns an output. Other functions return true/false, or text. Some functions return no value but perform a side-effect; “write” is one such function whose side-effect is to send text to the HTML document.  JavaScript Function Syntax:- We use the keyword function to define a JavaScript function followed by the name of the function, and a list of parameters(can be empty also) enclosed in  parentheses (). function functionName (parameters) {  //your code    }  Ex: function helloMessage(){  alert(“welcome to Knowledge hut”); }   helloMessage(); function with parameters:- function printEmpDetails(empFirstName, empMiddleName, empLastName){  alert(“EmployeeDetails”+ empFirstName+””+ empMiddleName+””+ empLastName);  }  printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi.  printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates. functions with argument objects:- In JavaScript we can pass argument objects as default; argument object is just like an array object. function printEmpDetails(empFirstName, empMiddleName, empLastName){  alert(“EmployeeDetails”+ arguments[0]+””+ arguments[1]+””+ arguments[2]);  }  printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi.  printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates.  We can also iterate arguments as   function printEmpDetails () {      for(var i = 0; i < arguments.length; i++){   alert(arguments[i]);      }}    printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”); Function with return value:- By using a return statement in a function it will always return zero or 1 value. function addition(var1, var2) {      return var1 + var2;  };  var output = addition(5,15); à Output returns as 20, and assigns it to the variable output  function square(var1, var2) {      console.log( var1 * var2);  };  output = square(2,5); // Output does not return any value, since the variable has not been assigned to print the output. Function Expression:-In JavaScript we can also assign a function to the variable and then use that variable as the function. var sum = function addition(var1, var2) {      return var1 + var2;  };  var output = sum(5,15); à Valid way of calling function using variable   var output1 = addition (5,15); à Invalid way of calling function using variable    Anonymous Function:-  In JavaScript we can define a function without any name, this function without any name is known as an anonymous function.  var printMsg = function (){  alert("Welcome to Knowledge Hut!");  };  printMsg(); àoutput will be Welcome to Knowledge Hut.  Nested Functions:-  In JavaScript we can write more than one function. Nested functions will be in the scope of outer functions. Inner function will be able to access parameters and variables of the outer functions.  function printMsg(name){  function something() {  alert("Welcome " + name);  }return something();  }printMsg("Gandhi"); àOutput àWelcome Gandhi. JavaScript Function Invocation:- Whenever we want to execute the code that is written inside the function, we need to invoke that function. In JavaScript we can invoke functions in 4 different ways. As a function itself. As a method, using call() and apply() Using constructor. As a function itself:- This is the basic way of calling a function. function print(){  alert(“welcome to knowledge hut”);  }   print(); As a method:-  JavaScript provides us with predefined call() and apply() methods which can be used to invoke other functions. The major difference is apply() which takes arguments as an array, whereas call() takes arguments as one by one separately. The methods call() and apply() allow you to invoke the function, giving you a lot of control over how the function executes. var msg = function (str) {      alert("Student First Name " + this.var1 + ", Last Name" + str.var1);  };  var str1 = { var1: "APJ" };  var str2 = { var1: "Kalam" };  msg.call(str1, str2);  // => Student First Name APJ, Last Name Kalam  msg.call(str2, str1);  // => Student First Name Kalam, Last Name APJ  msg.apply(str1, [str2]); // => Student First Name APJ, Last Name Kalam  msg.apply(str2, [str1]); // => Student First Name Kalam, Last Name APJ The ‘this’ keyword In JavaScript, this is a special keyword which is used within methods to refer the object on which a method is being called. The value of ‘this’ can be determined using the following series of steps: If using call or apply to invoke the function, this will be set to the first argument passed to call/apply. If the first argument passed to call/apply is null or undefined, this will refer to the global object. If using bind to invoke the function, the this will be the first argument that was passed to bind at the time the function was created. If function is being invoked as a method of an object then this will refer to that object. If the function is invoked as a standalone function and not attached to any object, this will refer to the global object. Using constructor:- JavaScript allows us to create the function dynamically using the Function() constructor along with a new operator. Syntax:- new Function([arg1 [, arg2 [, ...argN]] ,] functionBody)  var sampleFunction = new Function('x', 'y', 'return x * y');   console.log(sampleFunction(5,5)); àOutput = 25    Adding a Method to a Constructor  function vName(firstName, lastName, age) {    this.visitorFirstName = firstName;    this.visitorlastName = lastName;    this.visitor = function() {return this.visitorFirstName + " " + this.visitorlastName;};  }  var visitorName = new vName("APJ","Kalam");  console.log("Welcome to Knowledge Hut” +visitorName.visitor());  outputà > Welcome to Knowledge Hut APJ Kalam Built In Constructors:- var a = new Date(); //new date object  var b = new String(); //new String object  var c = new Function(); //new function object JavaScript Function Parameters: -  When we invoke a function we can pass some parameters to the function. These parameters are used inside the function and we can pass as many parameters as required, separated by commas. function functionName(parameter1, parameter2,…, parameterN) {    // your code to be executed  } General rules for JavaScript parameters. We do not specify any datatype to the parameters. There is no type checking on the parameters passed. No restrictions on number of parameters passed. JavaScript also has argument object which is known as built-in object. Whenever a function is invoked the argument object which is an array of arguments can be used. var a = add(10,20,23,40);  function add() {    var x;    var add = 0;    for (x = 0; x < arguments.length; x++) {      add += arguments[x];    }    return add;  } How to close Functions:- JavaScript function closures are very important as they will control what is there and what is not there in the scope of the function. Closures are very important and frequently used in JavaScript for data privacy. Mainly it is used while handling events and call back functions. With the help of closures, inner functions have access to the enclosing/outer functions variables. function out() {     var y = 10;     function inn() {            var x = 20;            console.log(x+y);      }     return inn;  }   In the above example, we have defined two functions ‘in’ and ‘out’. An out function has been defined with a variable y and it returns the in (inner) function. Whereas ‘in’ function has its own variable x and accesses the ‘out’ variable y in the function body. Here the scope of the out variable is limited to out function; similarly the in function is limited to inner function. Now you may wonder, how does the in function access the y variable defined in the scope of the out function? This is where the ‘closure’ comes into picture in JavaScript. With closure, the inner function always gains access to the variables and parameters defined in the outer function, even after the outer function has returned. Closure is a function that always remembers the variables from the place where it is defined, regardless of where it is executed later. Conclusion:-  In this blog we have discussed about JavaScript functions which are blocks of code and are executed repeatedly. Function helps us to avoid repeating the same code all over the place. You can use a function to wrap that code and reuse it. Functions can take zero or more than one argument. Since JavaScript is a loosely coupled language, we can pass any value to any of the data types and it is always optional to specify the parameter value while invoking the functions. Functions are the foundation of a good JavaScript programmer. Using them makes your programs better organized, clearer, more readable, and easier to understand when you wrap your code up in well-named functions for reuse. 

Functions in JavaScript

8K
Functions in JavaScript

In this blog we will learn more about the JavaScript functions. A function can be defined as a piece or block of code which is executed to perform a specific task. In other words, it is a group of reusable code which can be called anywhere in the program which makes the life of developers easy by eliminating the need of writing the same piece of code again and again. Functions help developers to divide larger programs into smaller chunks and also make them easily manageable. Functions allow us to define a block of code, give it a name and then execute it as many times as we want. We can define JavaScript function using the keyword function.  

Let’s explore JavaScript functions in detail. 

JavaScript Function Overview:- 

As in any other scripting and programming language, functions are one of the fundamental building blocks in JavaScript. A function is nothing but a series of statements that can be used to perform a task. In simple terms a function takes inputs and returns an output. In order to use a function, first we need to define it and then call the same. JavaScript provides us with many built in functions, for example  

alert (“Welcome to Knowledge Hut”); 
document.write(“Welcome to knowledge hut blogs”); 
Math.sqr(3); 

Generally, functions always return a value. For example, a mathematical function performs calculations on the input data and returns an output. Other functions return true/false, or text. Some functions return no value but perform a side-effect; write is one such function whose side-effect is to send text to the HTML document.  

JavaScript Function Syntax:- We use the keyword function to define a JavaScript function followed by the name of the function, and list of parameters(can be empty also) enclosed in  parentheses (). 

function functionName (parameters) { 
//your code    } 
Ex: function helloMessage(){ 
alert(“welcome to Knowledge hut”); } 
 helloMessage(); 

function with parameters:- 

function printEmpDetails(empFirstName, empMiddleName, empLastName){ 
alert(EmployeeDetails+ empFirstName+””+ empMiddleName+””+ empLastName); 
} 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi. 
printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates. 

functions with argument objects:- 

In JavaScript we can pass argument objects as default; argument object is just like an array object. 

function printEmpDetails(empFirstName, empMiddleName, empLastName){ 
alert(“EmployeeDetails”+ arguments[0]+””+ arguments[1]+””+ arguments[2]); 
} 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi. 
printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates. 
We can also iterate arguments as  
function printEmpDetails () { 
    for(var i = 0; i < arguments.lengthi++){ 
 alert(arguments[i]); 
    }} 
 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”); 

Function with return value:- 

By using a return statement in function it will always return zero or 1 value. 

function addition(var1, var2) { 
    return var1 + var2; 
};  var output = addition(5,15); à Output returns as 20, and assigns it to the variable output 
function square(var1, var2) { 
    console.log( var1 * var2); 
}; 
output = square(2,5); // Output does not return any value, since the variable has not been assigned to print the output. 

Function Expression:-

In JavaScript we can also assign a function to the variable and then use that variable as the function. 

var sum = function addition(var1, var2) { 
    return var1 + var2; 
}; 
var output = sum(5,15); à Valid way of calling function using variable  
var output1 = addition (5,15); à Invalid way of calling function using variable  
 Anonymous Function:-  In JavaScript we can define function without any name, this function without any name is known as an anonymous function. 
var printMsg = function (){ 
alert("Welcome to Knowledge Hut!"); 
}; 
printMsg(); àoutput will be Welcome to Knowledge Hut.  

Nested Functions:- 

 In JavaScript we can write more than one function. Nested functions will be in the scope of outer functions. Inner function will be able to access parameters and variables of the outer functions.  

function printMsg(name){ 
function something() { 
alert("Welcome " + name); 
}return something(); 
}printMsg("Gandhi"); àOutput àWelcome Gandhi. 

JavaScript Function Invocation:- 

Whenever we want to execute the code that is written inside the function, we need to invoke that function. In JavaScript we can invoke functions in 4 different ways. 

  • As a function itself. 
  • As a method, using call() and apply() 
  • Using constructor. 

As a function itself:-

 This is the basic way of calling a function. 

function print(){ 
alert(“welcome to knowledge hut”); 
 
print(); 

As a method:- 

 JavaScript provides us with predefined call() and apply() methods which can be used to invoke other functions. The major difference is apply(which takes arguments as an array, whereas call() takes arguments as one by one separately. The methods call() and apply() allow you to invoke the function, giving you a lot of control over how the function executes. 

var msg = function (str) { 
    alert("Student First Name " + this.var1 + ", Last Name" + str.var1); 
}; 
var str1 = { var1: "APJ" }; 
var str2 = { var1: "Kalam" }; 
msg.call(str1, str2);  // => Student First Name APJ, Last Name Kalam 
msg.call(str2, str1);  // => Student First Name Kalam, Last Name APJ 
msg.apply(str1, [str2]); // => Student First Name APJ, Last Name Kalam 
msg.apply(str2, [str1]); // => Student First Name Kalam, Last Name APJ 

The this keyword 

In JavaScript, this is a special keyword which is used within methods to refer the object on which a method is being called. The value of this can be determined using the following series of steps: 

  1. If using call or apply to invoke the function, this will be set to the first argument passed to call/apply. If the first argument passed to call/apply is null or undefined, this will refer to the global object. 
  2. If using bind to invoke the function, the this will be the first argument that was passed to bind at the time the function was created. 
  3. If function is being invoked as a method of an object then this will refer to that object. 
  4. If the function is invoked as a standalone function and not attached to any object, this will refer to the global object. 

Using constructor:- 

JavaScript allows us to create the function dynamically using the Function() constructor along with new operator. 

Syntax:- new Function([arg1 [, arg2 [, ...argN]] ,] functionBody) 
var sampleFunction = new Function('x', 'y', 'return x * y'); 
 console.log(sampleFunction(5,5)); àOutput = 25 
 
Adding a Method to a Constructor 
function vName(firstName, lastName, age) { 
  this.visitorFirstName = firstName; 
  this.visitorlastName = lastName; 
  this.visitor = function() {return this.visitorFirstName + " " + this.visitorlastName;}; 
} 
var visitorName = new vName("APJ","Kalam"); 
console.log("Welcome to Knowledge Hut” +visitorName.visitor()); 
outputà Welcome to Knowledge Hut APJ Kalam 

Built In Constructors:- 

var a = new Date(); //new date object 
var b = new String(); //new String object 
var c = new Function(); //new function object 

JavaScript Function Parameters: -  When we invoke a function we can pass some parameters to the function. These parameters are used inside the function and we can pass as many parameters as required, separated by commas. 

function functionName(parameter1, parameter2,…, parameterN) { 
  // your code to be executed 
} 

General rules for JavaScript parameters. 

  • We do not specify any datatype to the parameters. 
  • There is no type checking on the parameters passed. 
  • No restrictions on number of parameters passed. 

JavaScript also has argument object which is known as built-in object. Whenever a function is invoked the argument object which is an array of arguments can be used. 

var a = add(10,20,23,40); 
function add() { 
  var x; 
  var add = 0; 
  for (x = 0; x < arguments.length; x++) { 
    add += arguments[x]; 
  } 
  return add; 
} 

How to close Functions:- 

JavaScript function closures are very important as they will control what is there and what is not there in the scope of the function. Closures are very important and frequently used in JavaScript for data privacy. Mainly it is used while handling events and call back functions. With the help of closures, inner functions have access to the enclosing/outer functions variables. 

function out() { 
   var y = 10; 
   function inn() { 
          var x = 20;  
         console.log(x+y); 
    } 
   return inn; 
}   

In the above example, we have defined two functions in and out. An out function has been defined with a variable y and it returns the in (inner) function. Whereas in function has its own variable x and accesses the out variable y in the function body. Here the scope of the out variable is limited to out function; similarly the in function is limited to inner function. Now you may wonder, how does the in function access the y variable defined in the scope of the out function? This is where the closure comes into picture in JavaScript. With closure, the inner function always gains access to the variables and parameters defined in the outer function, even after the outer function has returned. Closure is a function that always remembers the variables from the place where it is defined, regardless of where it is executed later. 

Conclusion:-  

In this blog we have discussed about JavaScript functions which are blocks of code and are executed repeatedly. Function helps us to avoid repeating the same code all over the place. You can use a function to wrap that code and reuse it. Functions can take zero or more than one argument. Since JavaScript is a loosely coupled language, we can pass any value to any of the data types and it is always optional to specify the parameter value while invoking the functions. Functions are the foundation of a good JavaScript programmer. Using them makes your programs better organized, clearer, more readable, and easier to understand when you wrap your code up in well-named functions for reuse. 

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

7 Things to Keep in Mind Before Your Next Web Development Interview

Websites are an integral component of any business. According to research by techjury, there are approximately 4.3 billion internet users in the world, which makes the internet the single largest source for an audience. Organizations have identified this factor, and every business today has a website that represents them online. In fact, many companies, like ecommerce stores and food and beverage companies, for example, make their largest profits directly from their website.The requirement for website development, revamping and maintenance makes web developers sought-after candidates for every company. As a web developer, your options are many, and by regularly upskilling yourself, you can ensure a lucrative career. Before you attend your next interview, make sure to go through interview questions and answers online to be prepared. In this article, we cover seven tips for web developers to crack their next interview.1. Learn how to design In most companies, design and development are handled by different teams, and rightly so since they are two different disciplines that require a different skillset. The former is in the creative field, and the latter is technical. However, a candidate who can handle both is always going to be preferred. As a developer, you need to know the basics of design, the rules of UI and UX, and understand brand guidelines. These basic design skills will help you be more involved in the project and be a plus point to crack your next interview.  2. Be proficient in basic languages Every web developer needs to have a strong grasp on the ground level languages: HTML, CSS, PHP and JavaScript. Whether you develop on WordPress or code in Angular, your knowledge on these four languages will be tested. Prepare by going through knowledgebase articles for each of these and looking for interview questions online, especially JavaScript interview questions because a lot of companies look for animations that are triggered through JavaScript. 3. Learn multiple platforms Technology is ever-evolving. Make it a point to stay updated and learn new languages on a regular basis. Many websites and web apps today are built on different platforms: AngularJS, Python, React, Django, etc. Knowing more than just the basic languages will give you an edge over other candidates and pave the way for faster career growth. 4. Learn the basics of editing tools We have already discussed how important it is to add design as a skill to your portfolio. One way to do this would be to learn how to use editing tools such as Photoshop and Illustrator. This will also reduce your dependency on the design team whenever you need basic design edits like resizing or recolouring of images or layouts. Not only will you be able to complete projects faster, but you will also add bonus skills to your resume that interviewers pick up on.  5. Create an online portfolioThe best resume for a web developer is a website! If you can create a visually stunning website that is also agile, you can impress interviewers just by showcasing it. An online portfolio is a great way to show in real-time what you’re capable of, and also to showcase all your previous projects. It also helps potential employers find you online.  6. Be prepared to create a mock website Companies nowadays place a premium on seeing you walk the talk. Rather than asking you a bunch of questions, they give you a single page design and ask you to develop it at the interview. There usually aren’t any restrictions and interviewers let you choose the language and platform (unless the interview is for a specific language). Go into the interview prepared for this scenario by deciding beforehand what your strengths are and what platform you can complete this task on within the fastest time possible.  7. Relax, there are plenty of opportunities We began this article by giving you an idea of how much in demand web developers are. With many start-ups springing up and companies constantly revamping their websites, there are going to be numerous opportunities for you to land a well-paying web developer job. You can also look for freelance projects online on websites like Fiverr. Ace your next web development interview These are some core areas that every web developer needs to be proficient at. With the stiff competition today, mastering just one skill is never enough. Fortunately, there are a plethora of online courses and articles that will help you prepare and bag a career-defining web development job.
6650
7 Things to Keep in Mind Before Your Next Web Deve...

Websites are an integral component of any business... Read More

Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript used pretty much everywhere. For the seventh year in a row, we see it ranking as the most popular and widely used programming language, a good 67.8% of developers having used it in 2019. JavaScript is used to build 95.2% (1.52 billion) websites today, including Facebook and YouTube and some of the most popular and useful apps such as Google Maps and eBay. Let’s take a closer look at what JavaScript is, how and why it was created, and how it seems to be taking over front-end development. It all began in the late 90s when Netscape Navigator, a popular browser was launched by Netscape Communication. In the initial days of Netscape, it was just a software which was able to render static HTMLs, but people wanted it to do more. Netscape envisioned that web pages should be more dynamic in nature. If users are not able to engage with HTMLs, browsers will end up becoming boring pieces of software, they figured.That’s when Brendan Eich came into the picture. He was contracted in 1995 by Netscape Communications to develop a language which would have a low learning curve, so that anyone would be able to write functionalities with it. He developed the language in just 10 days and named it Mocha. A working prototype of Mocha was integrated in the Netscape Browser in May 1995, renaming the language to LiveScript and later in December 1995, it was renamed again, this time as JavaScript. The marketing team at Netscape chose to call it "JavaScript" as Java was extremely popular at that time. With the popularity of Netscape Navigator, Microsoft wished to capture the browser market and developed Internet Explorer with a scripting language named JScript. For a long time, there was no common standard formed for JavaScript, resulting in huge cross browser compatibility issues. Finally, in 1997, Netscape invited ECMA (European Computer Manufacturing Association) to take the responsibility of forming a specification for JavaScript.Since then, the ECMA has released updated specifications for JavaScript regularly and browsers try to follow these specifications in their implementation of JavaScript engine.Fact Check: Today, Brendan Eich is the CEO of Brave Software which builds a privacy oriented, chromium-based browser named Brave.Fact Check: Netscape Navigator later became the foundation stone for Mozilla Firefox. They retained the same name for their JavaScript engine "Spider Monkey" which was part of the Netscape navigator.Need of Framework With the ECMAScript specifications in place, developers began to use JavaScript  to make the HTML page much more dynamic using JavaScript. However, there were still a few developers who preferred to write big client-side functionality with JavaScript, owing to low performance of browser and JavaScript engines. Perhaps, the industry had a more a server-side performance focus in that era. Then, as computers became more powerful, browser performance improved and JavaScript engines evolved, developers started moving client-side logic to browser using JavaScript.Once developers started writing more and more JavaScript, the community felt the need to write logic in a more structured and scalable manner, so as to be more understandable, readable, manageable and less error prone. The need for a framework in JavaScript was clearly felt.Many frameworks like Dojo, Backbone, Ember and AngularJS eventually emerged within their own communities, which tried to solve problems in their unique way. Collectively, this has helped the whole JS community to move forward towards a more scalable and maintainable web application. ReactJS In 2011, Codebase for Facebook Ads was getting bigger. Developers began to face maintenance issues with it and it was getting harder to add new features in an efficient way. That's when Facebook engineer, Jordan Walke, built a prototype for an efficient application UI. This marked the birth of ReactJS, initially called FaxJS. Later, when Instagram was acquired by Facebook, the folks at Instagram wanted to adopt this framework. Pete Hunt and Jordan Walke then improved, decoupled the library and made it open source as ReactJS in 2013. Since then ReactJS has gone through many changes. The latest version of ReactJS in 2020 is currently 16.13. ReactJS follows component-based architecture and encourages developers to think in terms of small, composable components. Interestingly, this methodology is aligned with an efficient approach for solving any problem in life: the first step to solve a big problem is to break it down into multiple smaller sub problems. Once you have a solution for each sub-problem, you can then add it up to get the overall solution. This can be applied to all problems, big or small. ReactJS asks developer to adopt a problem-solving approach like this to build any UI. It must be noted that ReactJS does not aim to solve each and every problem of building a web application. Rather, it has a narrow focus and a limited scope to solve the one core problem of web development around how to efficiently updating the UI/views.When ReactJS was open sourced in the JSConf 2013, the ideas and changes that ReactJS was proposing were not very well received. For instance, although two-way binding was very popular, ReactJS went ahead with one way data flow. In another example, writing HTML inside JS was considered a bad practice, but ReactJS still wanted to use JSX. All these ideas initially attracted a lot of criticism from the web developer community. In time, however, developers started using it and found it easy to build components efficiently. So, ReactJS now solved the one problem around updating views. But what about all the problems in web development? An ecosystem began to emerge to address the other problems along with ReactJS. Libraries like Redux and React-Router came to life, making ReactJS a complete web framework, although this meant that there would be a dependency on multiple libraries. The ease of using ReactJS trumped all the negative points of the framework and this is what continues to make it a very popular library in web development. In 2020, ReactJS has 50K plus stars on Github and is downloaded 6 million times per week. The ReactJS ecosystem continues to grow steadily; React Native recently bought ReactJS to build cross mobile platform apps. Libraries like Gatsby and NextJS encourage developers to use ReactJS on server and provide benefits of server-side rendering without much hassle. ReactJS has also stood out in multiple developer surveys such as the State of JavaScript. Main design concepts in ReactJS Main design concepts in ReactJSDeclarative, composable, reusable componentsReactJS motivates developers to write small components and reuse the same component at multiple places. Re-usability of components greatly speeds up the overall development and results in less amount of code. Less code is always better because it is less prone to errors. ReactJS encourages developers to write composable components which can be wrapped around any other React component to provide special functionality, thus discouraging the writing of components that do too many things. ReactJS always encourages developers to break their problem into smaller problems, solve the smaller problems first and then combine them to present the overall solution. Less functionality in components always leads to less error prone components. ReactJS encourages developers to write clean, readable, and maintainable code. This is why it emphasizes writing declarative components, which make a codebase easier to read and understand by fellow developers.Declarative, composable components looks a lot like HTML in JS. Instead of standard HTML tags, we have React components as tags. This similarity to standard web semantics is what makes JS somewhat familiar to developers starting out. Reactive Updates Writing static HTML is no fun and it can be said that JavaScript was born to bring interactivity to web pages. ReactJS helps developer to add functionalities in components with which the user can interact and see the results. ReactJS allows developers to attach a state to component and whenever the state of components changes, the component efficiently re-renders itself to produce an updated view. Now, the state of the component can be changed by clicking a button, entering text into the input box or any other part of the component triggering an event. The React component listens to these events and acts accordingly. Updating the whole component UI seems like a terrible idea, but ReactJS has implemented this terrible idea wonderfully by doing it efficiently. In-memory DOM representation ReactJS is able to efficiently update views by keeping a DOM representation in memory known as virtual DOM. Upcoming updates always compare the new DOM with an older copy of the DOM and based on the difference, it figures out the actual DOM elements which need to be updated on the UI. Reducing the number of DOM manipulations makes ReactJS faster. What this means is that writing smaller React components will take up less memory to store DOM representations (Virtual DOM) and ultimately, this results in better performance. Features of ReactJS Main features of ReactJSJSX and Why is it needed When ReactJS was released, it was mentioned in documentation that it is recommended to use JSX along with ReactJS. Now, what is JSX? and do i really need another library to use the ReactJS library? So, let us see how a simple ReactJS component looks without JSX: import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); There is no way the above code looks like a declarative component. The truth is JavaScript does not understand HTML or XML like tags. That is why we need someone to do that conversion for us. Here enters JSX, also known as a syntax extension for JavaScript. With JSX, the above Greeting React component will look something like this: import React from "react";  function Greeting({ name }) {    return {`Hello ${name}`};  }  ReactDOM.render(, document.getElementById("root")); JSX actually makes ReactJS code more readable and understandable. You can assume this as a templating library which converts HTML looking syntax into ReactJS element JS code by calling createElement(). Virtual DOM ReactJS has made the term, 'VDOM' or virtual DOM very popular in the JavaScript community. Web browsers have provided APIs to interact with DOM to make our web page dynamic. One can dynamically add or remove nodes in the web page by using these APIs. But interacting with these APIs was very slow, as changing node triggers re-layout and re-paint event for sub-tree. Although the entire subtree is re-rendered (diffing stops when an element type has been modified and subtree is freshly rendered), even in case of virtual DOM reconciliation, the advantage that React offers is that the developer is freed from figuring out which part of DOM really requires updates - the diffing and reconciliation algorithm takes care of it.  React has thus provided a way to reduce the number to change in DOM using virtual DOM. The VDOM is a JavaScript object which contains information of DOM sub tree. We can also call this an object representation of DOM. React uses this object to compare subsequent modification and figure out the minimum number of modifications needed to make in browser DOM to get the desired result. ReactJS claims that the wonderful performance of their library is because of the algorithm they use to compare the virtual DOM. React Native React native is another popular library which is used to build cross platform mobile applications using JavaScript. Before ReactJS, Cordova and ionic were some frameworks which were very popular to build mobile applications using JavaScript. However, these applications did not perform very well. React native uses popular component-based concepts of ReactJS and provides a way to build an efficient mobile application. React native converts JS code into native platform code to run in mobile devices. This approach has improved the performance of mobile applications by a great deal in comparison to other frameworks like ionic. With React Native, ReactJS has now become a very popular library to build UI on any platform. ReactJS: Here to stay Over the past decade, the JavaScript community has seen tremendous changes in language within the developer community. It has seen a lot of new ideas and terms surface in the form of libraries. Developers are building and sharing their work with rest of the world quite frequently and every other day, implementations are open sourced on Github. These new ideas and the problem solving approach continues to help the JavaScript ecosystem to evolve and become better. Prior to ReactJS, JQuery was very popular and was the default library for any web project involving DOM manipulation. With AngularJS and other MVC libraries, we were encouraged to think about a problem in terms of Modal, View and Controller. People have always sought to figure out an approach that can solve the problem. And structuring a solution in a scalable manner is not a new challenge either. We have already implemented scalable solutions at server-side, and they are performing quite well. ReactJS now brings the same pattern to the front-end, where the final output is a UI. To implement this, we break the problem into smaller sub-problems and write solutions for them. This is the basic mental model to solve all UI problems and ReactJS focuses on the same. New ideas in the JavaScript community help the community move forward and eventually, the best solutions become part of the standard JS (ECMAScript). ES modules, promises and some lodash utilities are examples of this. When a library moves in the same general direction as the web, it is bound to be used by a large community. Developers will use these solutions until new specifications are finalized and browsers adopting new specifications. Interim, people will use the feature in the form of third party library.So, is ReactJS moving in the right direction? I would say yes. ReactJS is evolving right along the evolving standards of JavaScript. The front-end community is leaning more towards concepts of functional programming rather than object-oriented methodology. In a similar direction, ReactJS continues to move towards a functional programming pattern. ReactJS has introduced hooks in version 16.8, which encourages developer to build more and more functional components instead of class-based components. Hook does not even work with class-based component. Understanding well that it sometimes becomes a hectic task to figure out which library one should choose to handle state management, ContextAPI and useReducer hooks have been introduced, which help in managing state in small applications much better. Today, with the help of ContextAPI and useReducer hooks, you can build an application without using any other library like Redux. This, however, does not mean that you should stop using Redux as it has its own benefits.Component based architecture is also aligned with the standard web components support in browsers, which allow developers to write non-standard HTML tags in code. In short, ReactJS has made the community become familiar with some of the upcoming web standards. For this reason, I feel that conceptually, ReactJS is going to stay with the community for long. Many big companies like Facebook, Microsoft and AirBnB are supporting the direction and concepts of ReactJS, thus adding credibility to the library. With many big brains backing the library, the ReactJS community looks poised for growth. With no perfect solution to all the problems in web development in sight, the best option is to move forward with whatever is available at the moment. In the JavaScript community too, there is an effort to figure out an alternate to ReactJS such as VueJS and Svelte. Perhaps, ReactJS will get replaced by some other library in the future. However, the basic idea of creating smaller, reusable components is here to stay.Whatever framework we learn, it is most important to grasp the basic idea behind the library. It is this idea or design pattern that is going to remain for good. It may appear in front of you in a different form and shape, but the idea will remain forever. 
9961
Why ReactJS is taking over Frontend Development

History of JavaScript Today, we see JavaScript u... Read More

Exploring the Various Decorators in Angular

There are several important concepts in Angular, and Decorators are an important concept to learn when you are working with version 2 and above of Angular. Through this post we will learn about decorators, its types and how it is being used in real time applications.  Decorators are an important concept in TypeScript and since Angular uses Typescript widely, decorators become an important part of Angular as well.  What are Decorators? Decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method or property. They allow a service, directive or filter to be changed before being used. Basically, a decorator provides configuration metadata that determines how the component, class or a function should be processed, instantiated and used at runtime. Angular defines a number of decorators that attach specific kinds of metadata to classes, so that the system knows what those classes mean and how they should work. There are various types of in-built decorators. Let’s look at each type of decorator in detail. Types of Decorators: There are four types of decorators and each type further has its own subset of decorators.  Class Decorators  This is the first type of decorator which tells us about a particular class’s intent and helps answer questions like whether the class is a component or a module. There are various Class decorators in Angular, and among them @Component and @NgModule are widely used. Let’s see the structure of class decorators via a code snippet. Explanation: The below code snippet uses @Component, which is a type of class decorator provided by Angular.Property Decorators Property decorators are used to decorate specific properties inside a class. Using a property decorator, we can easily identify why we use any particular property of a class Like @Input (), @Output, @ReadOnly (), @Override () The above code uses @Override decorator before the property name which will invoke the decorator. This is nothing but a function and will override the string property name from “pat” to “test”. Method Decorator  Method decorators, as the name indicates, are used to decorate the method defined inside our class with functionality. A common example of method decorator is @HostListener In the above screen shot @HostListener decorator is used before onHostClick () method. Parameter Decorators Parameter decorators allow us to decorate parameters in our class constructors.  @Inject () is a common and widely used parameter decorator. Using this decorator, we can inject services in Angular classes. Structure of Decorators  In all the code snippets that we have seen so far on decorators, you must have noticed that each of the decorators follows a similar pattern or structure when used in code. Each decorator starts with @ symbol and is added before the class, method, property or passed as a parameter. All are functions having open and close brackets. This helps us understand that it is the function which is used as an in-built decorator. Just like a function can be customized, decorators can also be customized. Based on the requirement in our project, we can create custom decorators and use them accordingly. Custom Decorator  In this section we are going to learn the steps involved in creating custom decorators. As the term custom itself suggests, it is something which we create based on our project need which is not already fulfilled by the in-built Angular decorator. So, whenever we want to add some more features to our class, property of class, or method of class we use custom decorators. Here we are going to create a custom class decorator. Step 1. In an Angular project solution structure, create a classes folder inside the app folder.  Inside the classes folder create a class named sample Demo . Step 2. Once the class is created, you can go ahead and create a folder inside the app folder called decorator and add a file name as class.decorator.ts  Step 3. As we know decorators are functions, so we will create a function named Logging, as follows: ‘target’ is the class on which this decorator is going to be used and as we are going to use this decorator on class sample Demo, we have added export keyword before this function. Step 4. As we are going to use this decorator in the sample demo, let us add the sample demo class with decorator.  If we add this class in our main component and invoke, we will see the output on console as custom decorator SampleDemo How to pass data to a decorator The example explained above is a simple custom decorator where we are logging some messages on the console along with the class name where it is used. But if we want to send messages through the class where we are adding the decorator, then we have to change the implementation of the Function Logging.  Function Logging will accept some arguments and return the message as passed by the decorator on class. When we use the decorators in Angular, we pass in some form of configuration, specific to the decorator. For example, when we use @Component we pass through an object, and with @HostListener we pass through a string as the first argument (the event name, such as 'click') and optionally an array of strings for further variables (such as $event) to be passed through to the decorated method. Uses of Decorators in Real Time Applications Almost all Angular applications use decorator concepts; as decorators are functions that allow a service, directive or filter to be modified prior to its usage. @override, @deprecate, @autobind, @mixin are decorators which are widely used in real time applications. Angular framework has several of these kinds of examples which help to achieve complex features in applications. We know now what Angular decorators are and how they work on class, property, methods and parameters to provide information about metadata. All decorators work on a similar principle. We can apply some changes to the behaviour of the default functionality or we can add some custom tweaks to the code before the decorator can be applied to a class, property or method.  There are different ways to call decorators as these decorators can control start from the class implementation to the property and method implementation within the class. Decorators are great when code needs to be customized to suit the needs of the clients and when in-built functions do not help us with what we need.  Summary  When it comes to Angular decorators, we have several options to inject our codes and logic on different levels of class; as everything in programming revolves around class and its objects. Angular, being a rich framework gives us wide options to handle things in our own way. TypeScript has introduced this concept of decorators and those wishing to implement decorators into their code will benefit from going through TypeScript documents to understand more about actual implementation of decorators and its advanced concepts.