# What Is React-js State?

10K

You must have already learned about the basic building block of any React application which is a Component

A component represents a feature that may be made up of several smaller components. Components can be broadly classified into functional or class components.

Components may take in some values as properties (prop) to render a page. These props decide how to render a page.

function Welcome(props) {
return < h1 >Hello, {props.name}</h1>;
}

In addition to props, a component can also have a state that holds a value that can keep a track of all the information within a component.

In this article, we will focus mainly on what is State, how we can define and utilize State and how components can use it in data management.

## Defining React State

So what exactly is state? What is it used for?

State represents a component’s underlying data model and is rendered by the component. But more importantly, whenever data in the state changes, it causes the component to re-render to reflect the change. This facilitates declarative programming where you can simply manipulate state; while React takes care of implementing updates to ensure your component reflects the data in the State accurately.

In Class component we can use State as follows:

class Welcome extends React.Component {
constructor() {
super();
// Space To define the state
this.state = {
isDisabled: false,
totalCost: 0,
products: []
}
}
// To Define render method
} 

We can also use state in Functional components using the useState Hook. Hooks are a new addition in React 16.8 which let us use State and other React features in functional components.

## When should I use a Hook?

If you are writing a functional component and realize that you need to add State to it, the only option previously was to convert it to a class. Now you can use a Hook inside the existing function component.

For this, you can directly read the React documentation of Hooks here.

In this article, we will mainly focus on “what is a State” and how is it different from Props.

## Difference of Props and State

Most of the developers who are new to React often think about when to use State and when to use a Prop. Let’s understand this dilemma with an example.

A React component is akin to a JavaScript function.  A State can only be utilized in class components natively and is quite similar to a Prop, with the only exception that it is fully private, which means it can only be fully controlled and accessed by a component. In functional components, you have to opt-in to the useState hook to include stateful features.

Props, on the other hand, allow you to reuse the component by giving it an ability to receive data as input from the parent component.

A fictional example of Using a State:

class MyComponent extends React.Component {
state = {
name: 'Tom'  //defining the name property inside component state
}
render() {
return <div>Hello {this.state.name}</div>;
}
}  

Here, we can use the state ‘name’ anywhere in the component named “MyComponent” with the value ‘Tom’, or we can assign a new state also in the same component.

And, Using Prop:

Prop is a short name for properties. React is nothing without a Prop. Earlier we saw an example where we used the same data over and over again, but what if we have a scenario where we need the same component but not the same data? For example, I might want the theme component, but instead of a dark theme, I would like to use a light theme!

What I mean here is that basically, I want to re-use “MyComponent” again, but not the data defined in it. This is where Props will come in useful; in cases when we want to change the content inside the reusable component.

class ThemeProvider extends React.Component {
render() {
return <div>Current theme is {this.props.theme}</div>;
}

}
// when re-using the component with differnt data
<ThemeProvider name="Light" />
<ThemeProvider name="Dark" />         

It’s absolutely fine if you are not familiar with this code snippet. The idea is to understand when to use state or prop, and not the code as of now!

For now, just know that Prop is just a state, which is passed from parent to child. And because props can’t change their value in the child component, they take the help of an event listener or callback function in the parent component.

Now let’s quickly jump into the basics of a State.

## Creating the State Object

React component has a built-in state object.

Before you think that state is a very simple concept, let me stop you right there!

It’s not!

You should not forget the data flow in React! In React there is a uni-direction flow of data, which is from parent to child. This can be a bit confusing, in that different components will never know what is changing in their component and when. Besides, they might be unaware of whether a component is stateless or stateful.

This is why the state is usually said to be encapsulated or having a local scope.

This is why the state is usually said to be encapsulated or having a local scope.

And therefore, you initialize the state in the class component by simply using a constructor.

Inside the Constructor

To declare a local state in the component, we can use a constructor as follows:

class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson',
currentTimer: 0,
hasPicked: false,
themeRed: false,
todoList: []
}
}
render() {
return <p>My name is {this.state.name}</p>;
}
}    

And the output or the result of the above < p> tag will be rendered as:

Hello, my name is Michael Jackson

However, this was the older convention of declaring a state. We can also declare a state without the ‘constructor’ and ‘super’ keywords with the help of Property Initializer which came in 2017.

Wait, what is Property Initializer?

If you have a lot of code, it becomes harder to understand what is what. And if there are any arguments in the constructor, then it becomes an extra overhead to keep track of all of them.

Therefore, the idea behind using an Initializer is to use a cleaner ES6 component, by assigning an arrow function to a property that will act like a normal method. In other words, it can also be termed as class field syntax.

Without the Constructor

Take a look at the representation below:

class Welcome extends React.Component {
state = {
name: 'Michael Jackson'
}
}
render() {
…
}
}  

In the following example, we have added a state to the “Welcome” component.

Let’s see how we can consume the data from the object  not outside the component, but within it!

## Rendering data from state

A state is either initialized in the constructor or by using the class fields syntax to directly initialize it in a class component. Now let’s see how we can consume the state from the component in the render.

A point to note here while using state is we use “this.state” to get the value of the name property and it can be accessed in the render() method as follows:

~~~Wrong Approach~~~
class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson'
}
}
render() {
const { name } = this.state
return < h1 >My name is {name}</h1>;
}
} 

or an alternative to the above is:

~~~Right Approach~~~
class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson'
}
}
render() {
return < h1 >My name is { this.state.name }</h1>;
}
} 

The only difference in both is that in the first snippet I used State as:

const { name } = this.state

But we have already initialized the state in the constructor, why should we do it again?

We should not reassign it, and hence we should never update the component state directly.

A state should always be accessed using this.state.propertyName.

## Updating the State

So far, we have seen how to create state and use state in the component.

Now let’s understand why and how to update state and what happens after updating a state.

A state can’t be changed directly and the only permissible way of updating it is by using setState as follows:

this.state.site = "Welcome"; // wrong implementation

this.setState({ // correct implementation
site: "Welcome"
});

// Or
this.setState((prevState, props) => ({ site: "Welcome" })))  

The setState( ) method makes the component re-render; and hence when a state changes the component re-renders and updates the changes.

Each time setState is called, it sends a request to React to update and re-render and give it back a newly updated state.

Let’s understand this with an example:

Let’s suppose we have a component and want to change the name in the component with a method called handleNameChange(). It should look as follows:

handleNameChange(name) {
this.setState({ name })
}  

The above method receives an argument and it uses that argument to update the state.

Component Demo to update a state should look as follows:

class App extends React.Component {
constructor() {
super()
this.state = { name: 'Michael Jackson' }
}
handleNameChange(name) {
this.setState({ name })
}
render() {
const { name } = this.state
return (
<div>
< div>
< input
type="text"
value={this.state.name}
onChange={event => this.handleNameChange(event.target.value)}
/>
</ div>
<p>My name is, {name}</p>
</ div>
)
}
}  

## When is setState asynchronous?

React doesn’t have just one job to do, or only one component to observe for. It is possible that different components will be asking for different updates and DOM manipulations at the same time, hence the state updates are merged!

When setState() is called, React merges the object provided into the current state object.

For example, if we have different variables in our state like this:

constructor(props) {
super(props);
this.state = {
likes: [],
names: []
};
}  

And both states can be independently updated by using setState() calls as follow:

componentDidMount() {
fetchLikes().then(response => {
this.setState({
likes: response.likes
});
});

fetchNames().then(response => {
this.setState({
names: response.names
});
});
}  

Here we are calling multiple setState during one update cycle, so this.setState({names}) will leave this.state.likes unmarked but will completely replace this.state.names.

Hence you will not get the recently updated data in {names} and previous changes will be lost.

A quick fix to the above problem is as follows: Instead of giving a new state directly we can provide a function that can automatically provide the current state into a new state. There are two approaches to this:

// Method #1
this.setState({ foo: this.state.counter + 1 }, this.anyCallback);  

Or

// Method #2
this.setState((prevState) => { return { counter: prevState.counterfoo + 1 } }, this.anyCallback);  

The main difference is that in example #1, the counter gets incremented by 1 based on the state at the time when you have called the setState() method, whereas

In the example-2, the counter will be incremented by 1 only depending on the value that the previous state had while the arrow function was called.

So if we have multiple setState() which happen at the same time before the actual state update, it is possible that they may conflict or have outdated state data, but if we go with approach #2 they are guaranteed to have the most recent updated state because they update synchronously!

## Bonus Section:

### Changing Title on Click Example Using State

So far you have understood how to use State in React and what are the basic principles that define when to use State and when to use Prop. Here is a simple Demo for using State in a component and using Props to reuse the component.

Try this code to understand the power of State and reusable components.

let imgLogo = 'https://apod.nasa.gov/apod/image/2009/CrabNebula_Hubble_960.jpg';

class BonusExample extends React.Component {
constructor() {
super();
this.state = {
newTitle: false
};
this.changeTitle = this.changeTitle.bind(this);
}
changeTitle() {
this.setState({
newTitle: !this.state.newTitle
});
}
render() {
let title = this.state.newTitle ? 'Here is my New Title - Google Page' : 'Here is my Old Title - Facebook Page';
if (this.state.newTitle) {
} else {
}
return (
< div>
<Main title={title}>
<div className=" wrapper">
< button style={{ margin: '20px' }} type="button" className="btn btn-primary" onClick={this.changeTitle}>Change Name</button>
</div>
</Main>
<Footer>< HelperComponent /></Footer>
</div>
);
}
}

render() {
return (
<div style={{margin:'20px'}} className="wrapper">
</div>
);
}
}

render() {
return (
<div style={{ margin: '20px' }} className="wrapper">
</div>
);
}
}

render() {
return (
{this.props.children}
);
}
}

class Main extends React.Component {
render() {
return (
<div>
<h 1>{this.props.title}</h1>
{this.props.children}
</div>
);
}
}

class Footer extends React.Component {
render() {
return (
<footer>
{this.props.children}
</footer>
);
}
}

class LogoComponent extends React.Component {
render() {
return (
<img width="150px" src={imgLogo} />
);
}
}

class HelperComponent extends React.Component {
render() {
return (
<p>Changing the title from one to Another</p>
);
}
}

ReactDOM.render(<BonusExample />, document.getElementById('example'));  

## Conclusion

I hope you have understood the concept of State and its usage. We have learned the basic difference between State and Props and when each should be used. We have also understood the data flow in a React component and how to consume and update a State object in React.

Now that you have understood all the fundamentals of State, there are some high-level pointers that you should always keep in mind while using a State.

• State is private to a component
• State Updates have shallow merging
• You should never modify a State Directly
• Updates in a State may Be asynchronous
• State is only used when you want to change component data

### 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

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

## What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (Model View Whatever) framework backed by Google and is widely popular for creating dynamic apps. It offers a suite of tools that can be used for building the framework most suited to your single page application development. However, it can also be fully utilized to work for other categories of web pages. It works well with other web-based libraries and is fully extensible. All its features can be modified and even can be replaced to suit your unique development workflow and web feature needs.    As AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Dependency Injection in the following section. IntroductionDependency Injection − AngularJS has a built-in dependency injection (DI) subsystem library whose work is to help the development team by making the application easier to develop, test, and understand. We will learn about each part of DI in detail. The topics we will go through in this article are: Dependency injection in AngularJS Value Injecting a Value Factory Injecting Values into a Factory Service Injecting Values into a Service Providers Configuring a Provider Constants Dependencies Between Modules Dependency injection in AngularJs Today’s software is totally designed in accordance with various design patterns. One such pattern is Dependency Injection. The DI design pattern specifies the pattern in which components are provided with their dependencies, instead of hard coding them within the component. AngularJS comes with a built-in dependency injection mechanism that enables you to divide your application into various types of components which can be injected into each other as their respective dependencies. Modularization of your application makes it easier to use, reuse, configure and even test the different components in your application. According to DI the core types of objects and components include the following: Value Factory Service Provider Constant These are the objects and components which can be injected into each other using AngularJS Dependency Injection. ValueFor AngularJS, the “Value” is a simple object. It can be a number, a string or a POJO (Plain old JavaScript object). This object is used to pass values in AngularJS factories, AngularJS services or AngularJS controllers during the run and config phase. The following example shows the steps involved in using a value. Step 1:  Define a module   var myMod = angular.module("myModule", []); Here, myModule is created using the AngularJS function angular.module(). You can add value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a value object and pass data to it.    myMod.value("numberValue", 10);    myMod.value("stringValue", "aaa");    myMod.value("objectValue", { field1 : 123, field2 : "abc"} );  Here, values are defined using the value () function on the module as created in step 1. The first parameter specifies the name of the value, and the second parameter is the value itself passed to other parts of the application. Factories, services and controllers can now reference these values by their value name. Step 3: Injecting a value in Controller function To inject a value into AngularJS controller function, we need to add a parameter with the same value name as that with which the value was defined. Note that the controller function is registered in angular via the angular.module(...).controller(...) function call. The $scope parameter passed to the controller function is the model for the controller. Thus, here myMod is the module registering the controller as myController, and$scope is the model for myController.  var myMod = angular.module("myModule", []);    myMod.value("numberValue", 10);    myMod.controller("myController", function($scope, numberValue) { console.log(numberValue); });Example: Using Value in AngularJS: Consider that you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJs CDN for the same provided by Google. Value in AngularJS Value Example The numberValue is: {{nValue}} var myMod = angular.module('myModule', []); myMod.value("numberValue", 5); myMod.controller('myController', function($scope, numberValue)   {  $scope.nValue =numberValue; }); Output: Factory In AngularJS, a factory is a function that is used to return a value. This function creates the value on demand whenever a service or controller needs any value injected from the factory. AngularJS applications normally use a factory function to calculate and return a value. The following example shows the steps involved in using a Factory. Step 1: Define a module var myMod = angular.module("myModule", []); Here, myModule is created using the AngularJS function angular.module(). You can add factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a factory object and return data from it. myMod.factory("myFactory", function() { return "a value"; }); Here, we have used the factory function to create a Factory named myFactory. This Factory is returning “a value” from it. Step 3: Injecting values into factory Create a controller which gets the factory created value injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a factory value into AngularJS controller function, we need to add a parameter with the same value name as that with which the factory was defined. var myMod = angular.module("myModule", []); myMod.factory("myFactory", function() { return "a value"; }); myMod.controller("MyController", function($scope, myFactory) {    console.log(myFactory);    }); Note: It is not the factory function that is injected, but the value produced by the factory function that gets injected. Example: Using Factory in AngularJS:         Factory                Factory Example    The numberFactory is: {{nFactory}}        var myMod = angular.module('myModule', []);  myMod.factory("myFactory", function() {    return "a value";    });        myMod.controller('myController', function($scope, myFactory) {$scope. nFactory =myFactory;  });       Output: Service Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injecting it into controllers. The following example shows the steps involved in using a Service. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service for defining the MathService for calculating basic math functions like add, subtract, multiply and divide. And then create another service, myService for defining a cube method to return the cube of a given number: myMod.service('MathService', function() {      this.add = function(a, b) { return a + b };      this.subtract = function(a, b) { return a - b };      this.multiply = function(a, b) { return a * b };      this.divide = function(a, b) { return a / b };  });  myMod.service('myService', function(MathService){       this.cube = function(a) {          return MathService.multiply(a,MathService.multiply(a,a));        }    }); The above code snippet uses MathService to call multiply function that takes two parameters and calculates the product.  Step 3: Inject the service "myService" into the controller   Create a controller which gets the Service injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a Service function into AngularJS controller function, we need to add a parameter with the same value name as that with which the Service was defined.  myMod.controller('myController', function($scope, myService) {$scope.doCube = function() {          $scope.result = myService.cube($scope.number);       }    }); Here we can even make it event based by adding an event in the main HTML content as:   Enter a number:            Cube      Result of Service: {{result}}      Example: Using Service in AngularJS:         Service Example           Service Example        Result of Service: {{result}}          var myMod = angular.module("myModule", []);  myMod.service('myService', function(){  this.sum = function(a,b) {  return a + b;  }      });  myMod.controller('myController', function($scope, myService) {$scope.result = myService.sum (5, 6);  });       Output: Provider In AngularJS, a provider is used to internally create other values or services or factory during config phase (the phase during which AngularJS bootstraps itself). Provider can be considered to be the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value or service or factory. The following example shows the steps involved in using a Provider. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service using provider which defines a method square to return the square of a number.  We use provider method to create a Provider.   myMod.config(function($provide) {$provide.provider('myServiceProvider', function() {          this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); Step 3: Inject the Provider "myServiceProvider" into the controller Create a controller which gets the Provider injected (To understand how to create a Controller, go to the Value part of the article and navigate to its Step 3). To inject a Provider function into AngularJS controller function, we need to add a parameter with the same value name as that with which the provider was defined. myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {        $scope.number = defaultInput;$scope.result = myServiceProvider.multiply($scope.number,$scope.number);        $scope.square = function() {$scope.result = myServiceProvider.multiply($scope.number,$scope.number);         }       });   Example: Using Provider in AngularJS:             Provider               Provider Example                        Enter a number:      X 2              Result: {{result}}                                  var myMod  = angular.module("myModule", []);              myMod.config(function($provide) {$provide.provider('myServiceProvider', function() {    this.$get = function() { var factory = {}; factory.multiply = function(a) { return a * a; } return factory; }; }); }); myMod.value("defaultInput", 10); myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {                $scope.number = defaultInput;$scope.result = myServiceProvider.multiply($scope.number);$scope.square = function() {    $scope.result = myServiceProvider.multiply($scope.number);     }        });               Output: Constants Config Phase of AngularJS has some restrictions for injected values, as you cannot inject values into the module.config() function. Instead constants are used to pass values at config phase. To define a constant value we use the constant() function of the defined module. Then for the constant parameter we provide a constant value. The following example shows the steps involved in using a Constant in AngularJS. Step 1: Define a module   var myMod = angular.module("myModule", []);  Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a constant using the constant function and pass constant data to it.      myMod.constant("configParam", "constant value");    Example: Using Constant in AngularJS:              Constant            Constant Example      The numberConstant is:  {{nConstant}}            var myMod = angular.module('myModule', []);      myMod.constant("nConst", 5);      myMod.controller('myController', function($scope,nConst) {$scope.nConstant =nConst;  });        Output: Difference between Constant and Value Values and Constants seem to be applied in the same way; however, Value differs from Constant in that value cannot be injected into configurations, but it can be intercepted by decorators. Also, a Constant can be used during the apps config phase, whereas a Value is only available during the run phase. The main difference between value and constant is that a value specified using Constant is available during the configuration phase while value specified using Value is available during the run phase. Example showing the difference between a Constant and a Value:          Constant                  Constant Example    {{ID}}          var myMod = angular.module('myModule', []);  myMod.value("myValue", "First Assignment");  myMod.value("myValue", "Second  Assignment");  myMod.constant("myConstant", "First Assignment");  myMod.constant("myConstant", "Second Assignment");  myMod.controller("myController", function($scope, myValue, myConstant) { console.log("myValue: " + myValue); console.log("myConstant: " + myConstant);$scope.ID = " myValue: " + myValue + "&nbsp   myConstant: " + myConstant;  });       Output: Constant Example myValue: Second Assignment myConstant: First Assignment  Complete Example: AngularJS Dependency Injection Let's take an example to deploy all the above mentioned directives.                AngularJS Dependency Injection                 AngularJS Application Showing Dependency Injection         Enter a number:         X  2                Result: {{result}}                          var myMod = angular.module("myMod", []);    myMod.config(function($provide) {$provide.provider('MathService', function() {    this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); myMod.value("defaultInput", 10); myMod.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }); myMod.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); myMod.controller('myController', function($scope, CalcService, defaultInput) {    $scope.number = defaultInput;$scope.result = CalcService.square($scope.number);$scope.square = function() {    $scope.result = CalcService.square($scope.number);      }        });               Output: ConclusionIn the above article we learned about the Dependency Injection in AngularJS. Dependency Injection is a software design pattern that specifies how components get hold of their dependencies. In this pattern, components are given their dependencies instead of coding them directly within the component. We learned about core types of objects and components like Value, Factory, Service, Provider, and Constant. We learned how to create and register an injectable service and configure an injector with a service provider. We learned how to work with Injecting services to a controller. In the end we summarized with a complete example how Providers, Services, Factory and Value can be used.  Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
6559
What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (M... Read More

## Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. Introduction  Expressions In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. We will learn about each type of Expression in detail. The topics we will go through in this article are: Introduction to Expressions AngularJS Examples AngularJS using Numbers AngularJS using Strings AngularJS using Objects AngularJS using Arrays AngularJS Expression Capabilities and Limitations. Expressions in AngularJS Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: Can be written inside double braces: {{ expression }}. Can also be written inside a directive: ng-bind="expression". AngularJS will resolve the expression, and return the result exactly where the expression is written. Much like JavaScript expressions, they can contain literals, operators, and variables. Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} * Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. AngularJS Expressions and JavaScript expressions Let us compare Expressions in AngularJS and JavaScript. Similarity between AngularJS Expressions and JavaScript expressions: AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. Differences between AngularJS Expressions and JavaScript expressions: Context: JavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. Instead use services like $window and$location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. It is possible to access the context object using the identifier this and the locals object using the identifier $locals. AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's$parse service processes these expressions. Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. Filters: You can use filters within expressions to format data before displaying it. No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. No Bitwise, Comma, And Void Operators: You cannot use Bitwise, or void operators in an AngularJS expression. Citation: https://docs.angularjs.org/guide/expression (Docs from AngularJS) Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. AngularJS expressions support filters, while JavaScript expressions do not. AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. AngularJS expression cannot declare functions. AngularJS expression cannot contain comma or void. AngularJS expression cannot contain return keyword. There are several categories in which Expressions operate. Some of the Expression Types are: Expressions Using numbers. Example: Expense on Books : {{cost * quantity}} Rs Expressions Using strings. Example: Hello {{student.firstname + " " + student.lastname}}! Expressions Using object. Example: Roll No: {{student.rollno}} Expressions Using array. Example: Marks(Math): {{marks[3]}} Let us go through each category in detail. Expression using Numbers Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   Say if we use the expression as:               My first expression: {{ 5 + 5 }} Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in:              My first expression: 10 We will understand more about the use of number expression in AngularJS with examples. Example: Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js Example Using Curly Braces {{ }} for expressions:       Number Expression of AngularJs      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.expr1 = 10;  $scope.expr2 = 20 }); Number Expression The Result of Addition is : {{expr1 + expr2}} Now run the number expressions as an HTML file and check the output, which will look like this:Example Using ng-init and ng-bind for number expressions: Number Expression of AngularJs The Result of Addition is : Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: Expression using String Expression using String in AngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function. * Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false. For example: var obj1 = 123; var obj2 = "A String value";$scope.isString1 = angular.isString(obj1);   $scope.isString2 = angular.isString(obj2); isString1 returns false while isString2 returns true. We will see how to use string expressions in detail in AngularJS with the following example: Example: String Expressions of AngularJS var app = angular.module('myApp', []) app.controller("myController", function ($scope) {  $scope.expr1 = "Hello ";$scope.expr2 = "World";  $scope.expr3 = 100; var nexpr =$scope.expr3;  var sexpr = $scope.expr1;$scope.isString1 = angular.isString(sexpr);  $scope.isString2 = angular.isString(nexpr); }); String Expression The Result of Concatenation of {{expr1}} and {{expr2}} is : {{expr1 + expr2}} The Result of angular.isString() for parameter {{expr1}} is : {{isString1}} The Result of angular.isString() for parameter {{expr3}} is : {{isString2}} Now run the String expressions as an HTML file and check the output, which will look like this: Expression using Object The object expressions in AngularJS hold object properties in them. AngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section: Objects in AngularJS Before moving forth we need to understand objects in AngularJS. AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. For Example: Considering an object as AngularTraining with fields as Trainer, noOfStd, noOfHours, it can be defined as:$scope.AngularTraining = {  Trainer: ‘Monica’,  noOfStd: 10,  noOfHours: 24  };  To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. Note that $scope in AngularJS is a built-in object which basically binds the “controller” and the “view”. One can define member variables in the$scope within the controller which can later be accessed by the view. We will see how to use object expressions in detail in AngularJS with the following example: Example:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.AngularTraining = {  Trainer: 'Monica',  noOfStd: 10,  noOfHours: 24  };   });                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this:Objects with ng-init definition: We can define the objects at ng-init as shown in the following example:       String Expressions of AngularJS                Pure JSON object contains key value pairs as Object Expression        The AngularTraining Object is:    AngularTraining.Trainer: {{ AngularTraining.Trainer}}     AngularTraining.noOfStd: {{ AngularTraining. noOfStd}}     AngularTraining. noOfHours: {{ AngularTraining. noOfHours}}             Now run the Object expressions as an HTML file and check the output, which will look like this: Expression using Array Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. Arrays in AngularJS An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. For example: marks = [95, 52, 65, 98, 55, 35]; We will see how to use array expressions in AngularJS with the following example: Example:       String Expressions of AngularJS      var app = angular.module('myApp', [])  app.controller("myController", function ($scope) {$scope.name = "Monica";  $scope.leave = [1, 2, 0]; }); Array Expression The Leave Report for the first quarter for Employee: {{name}} is: January: {{ leave[0] }} February: {{ leave[1] }} March: {{ leave[2] }} Total Leave for the first Quarter is: {{ leave[0] + leave[1] + leave[2] }} Now run the Array expressions as an HTML file and check the output, which will look like this:Defining Arrays with ng-init definition: We can define the arrays at ng-init as shown in the following example: String Expressions of AngularJS Array Expression The Leave Report for the first quarter for Employee: {{name}} is: January: {{ leave[0] }} February: {{ leave[1] }} March: {{ leave[2] }} Total Leave for the first Quarter is: {{ leave[0] + leave[1] + leave[2] }} Now run the Array expressions as an HTML file and check the output, which will look like this: Complete Example Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS A complete example of AngularJS expression is: AngularJS Expressions Expression Hello {{student.firstname + " " + student.lastname}}! Expense on Books : {{cost * quantity}} Rs Roll No: {{student.rollno}} Marks(Math): {{marks[3]}} Now run the Expressions as an HTML file and check the output, which will look like this: AngularJS Expression capabilities and Limitations AngularJS Expression capabilities Angular expressions have the same power and flexibility as JavaScript expressions. In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. In AngularJS expressions you can use filters within expressions to format data before displaying it. Angular JS Expression limitations Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression You cannot declare functions in an AngularJS expression, not even inside ng-init directive. You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \$ etc. Such expressions cannot be used within AngularJS expressions. Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. Conclusion (Summary) AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as {{ textBinding }}. Some valid expressions are: 1+2, a+b, user.name, items[index] . Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
9157
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-ba... Read More

## Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript framework that can be used to build applications across platforms, achieve maximum speed with accelerated performance and ensure quick builds? Just AngularJS, isn’t it?  Powered by Google, Angular was developed as a framework to give you a toolset for powering your single page application development, work well with other web-based libraries and be fully extensible. All its features can be modified and even replaced to give you complete freedom in developing your own unique workflow.  As a pure JavaScript framework, Angular can be added to an HTML page with a normal tag with src attribute pointing to the source framework library. AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions.  AngularJS can be downloaded from https://angularjs.org/.  If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS.  It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, Logging and Internationalization. We will deal with Logging in the following section. IntroductionAngularJS includes a logging service called $log, which logs the messages to the client browser's console. The$log service includes different methods to handle the log for error, information, warning or debug information. It can be useful in debugging and auditing. This article will help you learn about each type of log. The topics we will go through in this article are: Introduction to logging Testing AngularJS Logging Application What Is Application Logging? Angular Logging: The Improved Approach Logging with AngularJS - extending the built-in logger $log in AngularJS Turn off logging in AngularJS Introduction to logging AngularJS has an impressive and robust logging mechanism in-built through the$logService and $log injection. The$log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.  The main purpose of all AngularJS logging services is to simplify debugging and troubleshooting. To reveal the location of the calls to $log in the JavaScript console; you can "blackbox" the AngularJS source in your favorite browser. To blackbox in the browser, go to the page, right click it, “Inspect” it in developer mode, and then read the console. Note: All browsers do not support blackboxing. AngularJS logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database.$log in AngularJS AngularJS programmers frequently use console.log to record errors or other informational messages in their applications. Although this is fine while debugging your application, yet it is not a best practice for production environment. As AngularJS is all about services, it is a better idea to create a logging service that you can call from other services and components due to some event which needs to be logged. In this logging service, you can still call console.log, but you can also modify the service later to record messages to store them in local storage or a database table via the Web API. Some methods that we will use for logging in AngularJS $log are: log(); to write a log message info(); to write an information message warn(); to write a warning message error(); to write an error message debug(); to write a debug message The above methods are used for different categorizations of$log. Testing AngularJS Logging Application An Example of logging in AngularJS is: Considering you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js  Logging Example in AngularJS var app = angular.module('myApp', []) app.controller("myController", function ($log) {$log.log('This is log.');             $log.error('This is error.');$log.info('This is info.');             $log.warn('This is warning.');$log.debug('This is debugging.');         }); Go to Inspect, through browser blackbox to see the Console for the different loggers.   Now run the logging example as an HTML file and check the output, which will look like this: Go to Inspect, through browser blackbox to see the Console for the different loggers. In the Inspect Window, go to Console, and see the result as: This is log. This is error. (In red font displayed with error icon) This is info. This is warning. (In brown font with warning icon) Here is a more complex example, which logs according to events generated as follows:       Logging Example in AngularJS      var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope,$log) {  $scope.$log = $log;$scope.message = 'Hello World!';  }]);            Reload this page with open console, enter text and hit the log button...  Message:         log  warn  info  error         Now run the above logging example as an HTML file and check the output, which will look like this: Reload this page with open console, enter text and hit the log button... Message:Clicking the buttons accordingly will give the console information as: Hello World! log Hello World! warn (in brown font with warning icon) Hello World! info Hello World! error (in red font with error icon) The output snapshot: What Is Application Logging? For a long time, logs have been an essential part of troubleshooting application and infrastructure performance. They help in providing visibility of how our applications are running on each of the various infrastructure components. Log data contains information such as out of memory exception or hard disk errors or even simple divide by zero error. Within software development, application logging plays a vital role; as much as we’d like our software to be perfect, issues will always arise within a production environment. When they do, a good logging strategy becomes very crucial. An application log usually contains errors, warning, events and non-critical information when compared to an error log that usually contains only errors and critical warnings. The application log should contain all the information necessary for audit. Put in simple words, an application log is a file that contains information about events that have occurred or errors and warnings that may occur due to some malfunctioning within a software application. These events are logged out by the application and written into a file, console or Web API. Once logged, the events can be handled accordingly as they include errors and warnings as well as informational events. The types of information and format of messages found in an application log file will vary between applications. These variables aren’t determined by external guidelines or by the operating system we are working on, rather they are determined by  the developers of the software application who control what goes into the log file. They’re the ones making decisions about what events and information would be useful to log and how logging should be done. Many events will be specific to the source application and many others would require a timestamp. Thus, it is common for logged events to contain information such as timestamp, source, etc. to make them more useful. Here is some common information that you will generally get in application log messages: Context information: Context information is the background information that provides an insight into the state of the application at the time of the message. Timestamp: A timestamp is a specific piece of contextual information for tracking and correlating issues that relate to the time aspect. Log levels: Log labels help you calculate the level of importance for the information entries in your log file. Some of the frequently used levels include INFO, WARN, ERROR, MESSAGE, and LOG. Once you are familiar with logged messages you will find it easier to use them when you’re trying to analyze bugs and unexpected events. When developers use the word “logging,” they usually refer to application logging. However, there are other types of logging as well. To further clarify what application logging is, let us briefly look at other types of logs to understand the differences. System Logs: System logs are written by the operating system. They contain information about System Processes and Drivers. On a Windows machine, System log is stored in the event log while in a Linux machine this is the syslog service. Server Logs: Server logs provide information on the state of a web application, web API, web Server or application server. The web server or application server is responsible for creating and maintaining server log files. GC Logs: Garbage collector logs assist with memory management of Java Programming Language by tracking objects within a JVM (Java Virtual Machine) and removing those that are unused. They are deactivated by default, however with simple switches, they can be switched on. Thus, application logging involves recording information about your application’s runtime behavior to a more persistent medium like a file or a database or even simple console. By reading the log entries wherever they are stored, you go back in time to analyze the application’s behavior, understanding the sequence of events that happened to it. You could even repeat the actions taken by a user, in order to recreate and fix whatever problem you are struggling with.  We need to log so that we can retroactively debug and analyze our application as if we are running it in the current moment. AngularJS Logging: The Improved Approach It is very easy to log all of the client-side messages to the server using AngularJS logging services. The biggest benefit is that it makes it easier to find application errors once in production phase and accelerate bug finding at deployment stage. Client-side logging can also help you identify the frequency of errors so that hotfixes can be prioritized in the order of importance as they can be labeled, helping you further to improve your AngularJS application for your clients. In AngularJS we have the different categories of logging as : $log.log(),$log.warn(), $log.info(),$log.error() and $log.debug(). These help the programmer and debugger to understand and classify different information as simple log, warning, information, error or debug information. Logging with AngularJS - extending the built-in logger Showing the correct line numbers You can tell AngularJS to show the correct line numbers by binding the$log.* functions to the console.* functions. For Example:     $log.debug = console.debug.bind(console); You will have to do that for each one of the 5$log methods separately. For Example:       Logging Example in AngularJS        var app = angular.module('myApp', [])  app.controller("myController", ['$scope', '$log', function($scope,$log) {  $log.debug = console.debug.bind(console);$log.info = console.info.bind(console);  $log.log = console.log.bind(console);$log.warn = console.warn.bind(console);  $log.error = console.error.bind(console); console.debug("Calling console.debug"); console.info("Calling console.info"); console.log("Calling console.log"); console.warn("Calling console.warn"); console.error("Calling console.error");$scope.$log =$log;  $scope.message = 'Hello World!'; }]); Reload this page with open console, enter text and hit the log button... Message: log warn info error debug Output is: All the console messages are shown in line numbers. Showing the$exceptionHandler as Factory  As per https://cmatskas.com/logging-with-angularjs-extending-the-built-in-logger/  site:  AngularJs has an impressive and robust logging mechanism through the $logService and$log injection. However, Angular logs everything to the console, which is neither a robust or scalable solution. Sometimes, you need to be able to intercept the exceptions and do something extra. This could be as simple as adding extra information or sending all logs to the server/database. The example below is simple and allows you to hook into the $exceptionHandler and pass a logger in the form of an AngularJS factory. The factory contains only one method => log(). This method first calls the base$log.error() method and after that point we have all the data we need to do as we want. The only limitation is that this custom logger deals only with errors and exceptions. Example: var mod = angular.module("LogDemo2", [] ); mod.provider('$exceptionHandler', {$get: function( errorLogService ) {          return( errorLogService );      }  });  mod.factory('errorLogService', ['$log', '$window', function($log,$window) {        function log( exception ) {            $log.error.apply($log, arguments );            try {              var args = [];              if (typeof arguments === 'object') {                  for(var i = 0; i       Reload this page with open console, enter text and hit the log button...  Message:           log  warn  info  error  debug          Case 1:  With :   app.config(function($logProvider){$logProvider.debugEnabled(false);  }); Output: We can see that if we open the “See Console Sidebar”, we get 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is missing as it is turned off by our application. If we hide the Console Sidebar, we can still see all the messages displayed in the Console as:Case 2: With :  app.config(function($logProvider){$logProvider.debugEnabled(true);  }); Or we can skip the entire code for app.config(){….}); as by default debug is turned on. Output: We can see that if we open the “See Console Sidebar”, we get 1 debug, 1 error, 1 warning and 2 info(1 for log function, other one for info function). Here Debug() is seen as it is turned on by our application or by default. If we hide the Console Sidebar, we can see all the messages displayed in the Console except the debug message since it can be seen only in the verbose of the console, as:Conclusion: logging in AngularJS In this post, we started with logging in AngularJS. AngularJS comes with a service called $log for logging.$log is a simple wrapper around the console.log facilities. We understood the difference between $log.info,$log.warn, $log.error,$log.log and $log.debug. We learned how to extend$log through AngularJS application and even work with extended features of the same. We also saw how to switch off debugging in AngularJS logging. Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.
10474
Logging in AngularJS Applications Made Simple

What comes to mind, when you think of a JavaScript... Read More