Four Ways to Create Objects in JavaScript

In JavaScript, there are four methods to use to create an object:

  1. Object literals
  2. New operator or constructor
  3. Object.create method
  4. Class

In this post, we will learn each of these methods.

Object literals

An object literal, also called an object initializer, is a comma-separated set of paired names and values. You can create an object literal as shown below:

You can add properties dynamically in an object, including after you have created the object. Here we add the dynamic property car.type:

The object literal is a simple expression that creates an object each time the statement that it appears in is executed in the code. You can also use Object.defineProperty to create properties in the object literal as shown below:

The main advantage of using Object.defineProperty is that you can set values for object property descriptors or modify existing properties. You can learn more about Object Property Descriptor here.

New Operator or Constructor

The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object. Consider the following code:

Learn full article on the Infragistics blog

What are Template Literals in JavaScript

Read full article on the Infragistics blog

In ES6, two types of literals were introduced:

  1. Template Literals for string concatenation and expression embedding in a string
  2. Tagged Template Literals to tag the Template Literal in a function so the literal can be evaluated in the function

Let’s assume that you need to do the string concatenation with a dynamic expression or with the value of a variable. Take a look at the following code:

Here you see you’ll need to embed the value of variable foo in a string literal. In ES6, you can do this using Template Literals, as shown in the code listing above. Template Literals are mainly used for the following purposes:

  • String concatenation
  • To create multi line strings
  • To embed expressions
  • To use string interpolation

In the code above, we are embedding the expression foo in the string result. To use Template Literals:

  1. Template literals are created inside a back-tick (` `) character.
  2. In Template literals, placeholders are created using the ${expression} symbol. At run time, the expression will be evaluated and replaced in the placeholders.
  3. In template literals, the expression can be embedded using ${expression}. This is also called an expression interpolation.

Using Template literals, let us create some expression interpolation. Consider the following code:

To create expression interpolation here, we are using the Template literal. You’ll also notice the string is broken into multiple lines. If required, you can created a nested template also.

Tagged Template Literals :

ES6 allows you to tag template literals, meaning you can parse that inside a function.  So, if you use Tagged Template Literals, JavaScript will not immediately assign them to a variable, and rather parse them in a function

Read full article on the Infragistics blog

Simplifying function expressions and the function statement

Read full article on the Infragistics blog

In JavaScript, a function can be created in three possible ways:

  1. Function as an expression
  2. Function as a statement
  3. Arrow functions

In this post, we will learn about function expressions and the function statement.

Consider the following code:

When you create a function as shown above, it is called a function declaration or statement. You can rewrite the code above to add a function in different ways, as shown below:

The function created above is called a function expression – in this case, an anonymous function expression. A named function expression can be created as below:

The name of the function expression can only be used inside a function body, which is helpful in recursion. A function expression can either be a:

  1. Named function expression
  2. Anonymous function expression

The third method of creating a function is by using the Arrow function, which was introduced in ECMAScript 6. You can learn more about Arrow functions here.

Some important points about naming functions are as follows:

  1. A function statement cannot be created without a name
  2. A function expression can be created without a name, meaning you’re able to create an anonymous function

Read full article on the Infragistics blog

What are getters and setters in JavaScript

In JavaScript, you may have heard of getters and setters. Let’s take a look at what these things are.

First, a setter is used to set the value of a property. A setter gets called each time the value of the property is changed. In other words, it executes a function for each time a property used inside the setter function is changed. Take a look at the following code:

image

In the object foo, the setter cal will be called each time the property a is changed. As an output, you will get 13 printed. While creating a setter, you need to follow these rules:

  • A setter name could be either string or number.
  • A setter must have exactly one input parameter.
  • There should be only one setter with the same identifier in an object
  • You can remove a setter using the delete operator

For other examples of a setter, let’s take a look at the following code:

image

For the above code snippet as output, Hello Jason will be printed. You can also add the setter to an existing object using Object.defineProperty. Let’s say that you have an object foo:

image

Now to add a setter for the existing object foo , use Object.defineProperty.

image

Read full article on the Infragistics blog

JavaScript Object Property Descriptors

In JavaScript, you can create an object literal as shown in the listing below:

image

At first sight, it looks like the object cat has two properties with a string and number value. However, it’s much more than that to a JavaScript interpreter. In ES5, the concept of a Property Descriptor was introduced. Before we go ahead and discuss property descriptors, let’s try to answer a few questions:

  1. How do I create a read only property?
  2. How do I make an unenumerable property?
  3. How do I make property not configurable?
  4. How do I determine whether a property is read only?

You can answer all these questions when you understand Property Descriptors.

Let’s consider the code below:

image

Here, your output will be as follows:

As you can see here, there are four characteristics of a property:

  1. Value
  2. Writeable
  3. Enumerable
  4. Configurable

The value holds the data of the property, whereas writeable, enumerable, and configurable describe other characteristics of the property. Let’s take a closer look at each of these characteristics in the rest of this post.

Writable

Whether value of the property can be changed or not is decided by the writable characteristic. If writable is set to false, then the value of the property can’t be changed and JavaScript will ignore any changes in the property value. Consider the code below:

image

You can change the value of the writable, configurable, and enumerable characteristics using Object.defineProperty. We’ll talk more about Object.defineProperty later in this post, but as you see in the code snippet above, we have set the writable to false, thereby changing the value of the name property. JavaScript will ignore the reassignment, and the value of the name property would remain foo.

If you run the code in strict mode, for reassignment of the property value where writable is set to false, JavaScript will throw an exception. Consider the code below:

image

Here, JavaScript is running in strict mode, hence when you reassign the value for the name property, JavaScript will throw an exception as shown below:

The error message here says you cannot assign something to a read only property.  Here, aproperty acts as a read only property if the writable characteristic of the property is set to false.

Read full article on the Infragistics blog

Arrow functions in JavaScript

The JavaScript arrow function is a shorter way of writing a function expression that was introduced in ECMAScript 6. Usually in JavaScript, you can create a function in two ways:

  1. Function as statement
  2. Function as expression

A function statement can be created as shown below:

image

The same function can be created as a function expression as shown below:

image

ECMA 2015 (or ECMA Script 6) introduced shorter syntax to write a function expression called the arrow function. Using the arrow function, you can write the function expression above as seen here:

image

As you see, writing a function expression using the arrow function is shorter.

Basic syntax rules for arrow functions

First, parameters should be passed in the small parentheses. You can create an arrow function with two parameters as shown below:

Read full article on the Infragistics blog

Simplifying function hoisting in JavaScript

To understand function hoisting, let us start by considering the code listed below:

image

In any other programming language, the output here would be a reference error. However, in JavaScript you will get undefined as the output. Why? Because JavaScript hoists variables at the top of the execution context. An execution context could be the function in which a variable is declared, or a JavaScript file in which a variable is declared. So, let us rewrite the above code snippet using a function:

image

Here, the variable “foo” is hoisted at the top of function abc execution context; which means you can access foo before it is declared. To put it simply, whenever you declare a variable, the JavaScript interpreter breaks it into two statements:

  1. Declaration of variable
  2. Assignment

The declaration of a variable goes at the top of the execution context, and assignment happens where the variable is created. So the above code snippet is broken into two statements as shown in the image below:

The variable foo is hoisted at the top of the execution context of function abc, hence when you use it before its declaration, you get “undefined” as the output.

Keep in mind that a variable declared using the let statement does not get hoisted to the top of the execution context.

Now that you understand how variables are hoisted in JavaScript, let’s explore function hoisting in JavaScript. In JavaScript a function can be created in two ways:

Read full article on the Infragistics blog

What is the arguments object in a JavaScript function?

A JavaScript function has array-like objects called arguments which correspond to the arguments passed to the function. All arguments passed to a JavaScript function can be referred using the arguments object. 

Now as we get started, let’s consider the code listed here:

image

In the above function, num1 and num2 are two arguments.  You can refer to these arguments using the arguments named num1 and num2. Besides the arguments name, you can also refer to them using a JavaScript array like the object arguments. So, the above function can be rewritten as shown in the listing below:

image

In JavaScript functions, the arguments object is used to access or refer to all arguments passed to the function. The arguments object is a local variable available to the function. The length of the arguments object is equal to the number of arguments passed to the function.  Let us consider the code below, where you’ll get 2 as an output because two arguments have been passed to the function:

Read full article on the Infragistics blog

What is a Default Parameter in a JavaScript function?

A JavaScript function can have default parameters values. Using default function parameters, you can initialize formal parameters with default values. If you do not initialize a parameter with some value, then the default value of the parameter is undefined.

image

While calling function foo, you are not passing any parameter, so the default value of variable num1 is set to undefined. However, sometimes you may want to set a default value other than undefined. In the past, the best strategy was to test for the parameter value undefined and then assign a value. So, let us say that in the above example, you want to set the default value of num1 to 9. You can do that as shown in the code listed below:

image

ECMAScript 6 introduced default parameters for the function. Using the default parameters features of ECAMA 2015, you no longer have to check for an undefined parameter value. Now, you can put 9 as the default value in the parameter itself. You can rewrite the function above to use the default value as shown below:

image

For function foo, if num1 parameter’s value is not passed, then JavaScript will set 9 as the default value of num1.

Read full article on the Infragistics blog

What is the Rest Parameter in a Function?

Learn full article on Infragistics blog

A JavaScript function can take any number of parameters. Unlike other languages like C# and Java, you can pass any number of parameters while calling a JavaScript function. JavaScript functions allows unknown number of function parameters. Before ECMAScript 6, JavaScript had arguments variable to access these unknown or variable number of parameters, which is an array-like object but not an array. Consider this code listing to understand the argumentsvariable:

As you see, that arguments object is used to access unknown or variable function parameters.  Even though arguments uses length property and square brackets, it is not a real JavaScript array. You cannot use other JavaScript array methods like pop, push, slice etc. with the arguments object.  Some of the problems in using arguments are:

  • JavaScript function arguments object is not a real JavaScript array; therefore, you cannot use other array methods like pop, push, slice, etc. with it
  • It is difficult to access arguments object of outer function in an inner function. To use it, you need to assign outer function arguments object in a variable, and then use it in an inner function
  • If you want to use arguments object as an array, then you need to convert it manually using Aarry.prototype.slice

ECMAScript 6 introduces a new feature, Rest Parameters, which represents an unknown number of parameters as an array in a function. It not only represents extra parameters as an array, it also solves many of the problems of the arguments object.  Let us rewrite the above add function using the rest parameters.

Learn full article on Infragistics blog