Difference between: function Person(){}, var person = Person(), and var person = new Person()?
There are three different syntax we can use fordeclaring functionsin java script
i) Function Declaration
function Person(){
console.log(“Hello”);
}
A Function Declaration defines a named function variable without requiring variable assignment. Theyare declared as constructs which are standalone and cannot be nested within non-function blocks.
ii) Function expressions:
var Person = function(){
console.log(“Hello”);
};
A function expression looks similar to function declarations, except that the function is assigned to a variable name. The function name can be optional. If the name isn’t given, then we can term it as an anonymous.
iii) Function constructor:
varmyPerson = new Person();
Such a syntax declaration is used when creating an instance of a Class(Constructor). Here, we pass in an unlimited number of arguments in the front and use the keyword “new”.
Over the past few years there have been drastic changes in web development, lot of JavaScript frameworks have popped up. Some stayed and some have gone into the dark. Oftentimes, developers either choose the wrong framework or use the right framework incorrectly. Choosing the wrong JS framework is something that occurs often but you can avoid by simply educating yourself on the various principles, methods, and practices that you can use to make sure your framework has the functionality you need without bloated code to slow you down.
Downsides of choosing the wrong framework:
With demanding additional functionality, developers are finding quite comprehensive to handle the architectural challenges and implement their ideas with frameworks which are limited. Though they opted for wrong framework to get their things done, it is not fully secure and 80% aren’t delivering what should have been. One of the most frustrating thing is they get in trouble building applications which is far more time-consuming. By choosing the wrong one, they are finding the projects weighed down by restrictive assumptions and masses of code that they don’t understand. There is often a large percentage of code that will never be executed, or find dependency on obsolete or legacy code.
Generally there are various integrated set of tools to enable developers to develop for different types of web applications. This include usage of various javascript frameworks like AngularJS, Backbone.JS, EmberJS, and Nodejs to develop more flexible and less error-prone applications in a more effective way. Also developers given too many choices have a tendency to either not choose anything at all, or to be deeply dissatisfied with their choice. This particularly applies to choosing frameworks, because there are just so many choices, and the cost of switching is painfully high. But do we have a choice? What are the precautions one should follow ahead of choosing a framework that is not the scope of this article. The point is how to handle the wrong framework, a.k.a, OMG! moment. Let’s see what’s the opinion of developers we came across in conferences/casual encounters.
The OMG! Moment
Most of the cases, a developer will know that you chose a wrong framework only after 30%-40% of the application implementation or exposure. He/She would be stuck at a point where either the performance degraded or end up with too much of stale code or helplessly stuck with adding one more custom-helper function to the big list of “ many custom-helpers()”. That’s the OMG! moment where one would bang the desk cursing the framework (Argg!). That’s it, that’s the point where you should immediately re-think. Lot of us move ahead trying to find a work-around “fix”. Don’t! It’s going be a lot of struggle later on.
What choice do we have?
Two approaches brand new framework or write a custom library that would enhance the current framework
Yeah, true we may not have too much choice at that moment, but if and (only if) you have enough resources/time at hand. Have certain % of the time to explore other JS frameworks Let’s come to “a framework evaluation” topic in a moment. Once we narrow down on a JS framework, do couple of POCs (Proof-Of-Concept) that addresses the current concerns or a “fix” is readily provided/available in the new JS framework. It’s going to seem like an herculean task, but lot of developers have secretly agreed that it’s one of the best approach. Identify the components that are already developed and that are in the pipeline. Take a sample complex component and implement it in the new framework. Perform a quality control test or a load test with a (dummy) high volume POC.
Next, have a proper transition plan in place. Check whether such framework has enough support, documentation and resource talent available. Spend more and more time research the forums about problems developers are facing with the framework.
These frameworks add the value based features in different websites and web application development process. Most of them will have unique features specific to that particular framework in terms of platform compatibility, portability, database compatibility, general performance, security, web services, language support etc. and are suitable for key development functions. So before diving in, it’s necessary to have an idea of the most commonly used frameworks that can significantly result in more secure applications. When choosing the correct framework it important that the developer is knowledgeable about the different frameworks in terms of ease of use, rapid application prototyping, scalability, code maintenance and look and feel.
Considerations When Choosing a framework.
• Choose a framework that can be tailored and extended.
• Stick to framework ground rules: follow the documentation and don’t overwrite framework code.
• Build a framework by means of a prototype: a static internal website that includes all the page types and elements you need.
• Focus on quality assurance during the development process, and quality control to find and fix framework issues.
• Diligently maintain and update your framework, whether it’s for internal or external use.
• Anchor your documentation right where development happens.
However, each project is examined from several different perspectives including maturity, size, dependencies, interoperability, and features. If a developer does find him/her self using the wrong framework, the best solution would be to figure out which one you absolutely need, that way the mistake won’t be made again. Developers that are knowledgeable about the various frameworks and how they operate have no problem choosing the correct one and avoiding the wrong one, depending on what type of project they are working on. So take the time to educate yourself, that way you won’t find yourself backtracking and or redoing application from scratch.
Technically, ECMAScript (ES) is the language attempted to standardize the scripting languages such as JavaScript. Over the years, different versions of ES evolved. ECMAScript 6, code named “ES.next”, has gained significant traction that has got many enhancements and features that makes JavaScript code easier and maintainable. ES6 specs are still under experimental stage and a stabilized version is not officially out. In the ECMAScript 5 version of JavaScript, there are several new capabilities to the language without many changes in syntax. For instance, ES5 lacks sub-classing an array. Later ES6 was upgraded to tackle some fundamental language issues that require syntax changes that were needed to be fix, along with some new features to address shortcomings in ES5. Let’s investigate the differences between ECMAScript 5 and 6.
ES5 IMAGE
ECMAScript 5 focus seemed to be on defining the so-called “magical” parts of JavaScript such as read-only properties and non-enumerable properties while setting the path forward to remove “the bad parts” with strict mode.
First let’s understand what are the few interesting features of ES5 include:
• newer object model, using which, newer objects can be created easily and their extensibility can be controlled.
• native JSON support, which includes methods like JSON.parse( ) and JSON.stringify( ) which remove dependency on external libraries for working with JSON.
• Strict Mode- Which makes the programs simpler and less error-prone.
Much of developer’s annoyance usually has come from lack of tooling to scale JavaScript applications, but that is being rapidly addressed with frameworks like AngularJS and JS-based language like TypeScript. ECMAScript 6 is ready to alter the way we gaze at client applications. Web development is continuing to evolve as we see more adoption of new gears that enable JavaScript-based development for both web and mobile devices. ES6 will tackle many of the core language shortcomings addressed in many frameworks and ES5.
OK So What’s New?
ES6 has got new features which includes Classes (‘Class’ is a keyword in ES6), Arrow Functions, Modules, Block Scoping, and Promises. Developers are particularly excited at the features available in ES6 to reduce many aspects of coding. In ES6, built-ins like Array, Date and DOM Elements can be subclassed.
As such, several workarounds in ES6 have emerged which gave developers some great new options. Several existing JavaScript module systems and frameworks (AngularJS,Node.js and Require.JS ) support ECMAScript 6 via transpilers ( Typescript, Traceur, and 6to5).
Let’s dig into each of the above mentioned features in ES6:
Arrow functions – Arrow functions is a short cut to create an anonymous functions and make development more productive. When it comes to defining the functions Arrow functions are used for callbacks. Below example shows a regular way vs arrow functions.
Block scope(const, let, and functions)- let and const behave similarly in the sense that both are block scoped. Const values are read only and cannot be redeclared later on.
for (var i = 0; i < 5; i++) { var j = i + i;
}
console.log(j); // 8
for (var i = 0; i < 5; i++) { let j = i+ i;
}
console.log(j); // Reference Error
Classes (Class Keyword)-Classes are syntactic sugar that overlay the current constructor and prototype based approach to types.
Example of using:
class Language {
constructor (name, founder, year) {
this.name = name;
this.founder = founder;
this.year = year;
}
summary( ) {
return this.name + “was created by ” + this.founder + ” in ” +this.year;
}
}
Modules-Helps remove us from real global variables that pollute the namespace (a really good thing btw) and does a better job at managing asynchronousity. It has two new keywords: export and import.
Example of using:
export const PI = Math.PI;
export function square(x){
return x*x;
}
// app.js
import {PI,square} from ‘math'; //Alternativelycould be:import * as math from ‘math’
console.log(square(PI));//will be PI^2
Promises-Promises are a representation of an object. They are used in asynchronous JavaScript programming and are available today in many third party libraries, including JQuery, Angular, etc.
Example of using:
var promise = new Promise(
function (resolve, reject) { // (A)
…
if (…) {
resolve(value); // success
} else {
reject(reason); // failure
}
});
There are a lot more other interesting features, including rest parameters, generators, default parameters and more.
The features vary widely from completely new objects and patterns to syntax changes to new methods on existing objects. The exciting thing about ECMAScript 6 is that all of these changes are geared towards problems that developers are actually facing. There are several ECMAScript 6 features that replace ECMAScript 5 features, but you can still use ES5 as a foundation by using “transpilers” to bridge the ES5-ES6 gap.
ES6 is the most promising version of JavaScript that will certainly aid writing more modular and less quirky code. By taking advantage of the right tools and functionality of the future version ES6, one can address critical issues of earlier versions that help use these new features effectively. Now, the entire ES6 feature-set is beyond the scope of this post, for that you can check out its new features by trying them out.
Firstly, in JavaScript’s event model, you will come across a concept called as event bubbling (which makes an event to propagate from child element to a parent element). In order to avoid such kind of bubbling effect, many developers use an event method called “stopPropagation( )”. Alternatively, developers have started to use “return false” statement to stop such propagation.
Now, there is another terminology called “preventDefault( )”. As the name indicates, this method prevents any default behavior of an element to trigger. Best use case is to prevent an anchor tag to open a link.
You may come across a scenario where you would like to prevent the anchor tag from opening a link (default behavior) as well as stop the event from going up to the parent.
In such situation, instead of writing two lines of code, you can get it done in single line i.e; “return false”.
How do you organize your code? (module pattern, classical inheritance?)
Modular pattern imitates the classes in conventional software engineering and it mainly focuses on the public and private access to methods & variables. The module pattern goals are to reduce the use of globally scoped variables, so as to decreasing the chances of conflicting with other code throughout an application.
This is also regarded as the most commonly used design pattern and it is also widely accepted in a number of large projects such as jQuery, Dojo, ExtJS and YUI.
Advantages
• Organized and clean approach for developers
• We can encapsulate data.
• More clean code in the global namespace(avoiding conflicts).
Disadvantages • We cannot access private methods
• We can extend Private methods and functions.
Classical Inheritance
The classical inheritance in a way is similar to the inheritancein Java or C. Those who have backgrounds in those programming languages must be familiar. So by using classical inheritance, we are recreating the basic programming language’s behavior i.e. using classes and objects, which are instances of those classes.
So a classical pattern is used together with the“prototype”keyword added to the constructor and the newoperator.
1. Call a constructor function.
2. Have a child’s prototype point to the parent’s prototype.