# What Are React.Js Prop

10K

Understanding data manipulation in React is never an easy job. React has a unidirectional data flow due to which the technique of data manipulation in React is slightly different than in other frameworks.

To understand the concepts like Props or State, I’d recommend you brush up or go through the data flow concepts in React first.

In this article, we’re going to focus only on the Props feature and how to use it in React.

We already know that components are reusable, and we can use our component multiple times in our application. To understand props, you should have a solid understanding of the components and how data flows inside the components.

If you don’t know much about React components, I recommend you stop here and read about React components first before continuing!

Let’s now learn what are “props” and how to use them?

## What is Props in React?

We all know that React Components allow you to split the application interfaces into reusable, independent segments.

“Props” stands for properties. It is a special keyword in React which is used for passing data from one component to another.

Logically, components are just like JavaScript functions. They accept random inputs (called “props”) and return React elements which tell what should be displayed on the screen.

Props can be used to pass any kind of data such as:

• String
• Array
• Integer
• Boolean
• Objects or,
• Functions

## Understanding ReactJS Props

We are all quite familiar with parent and child components.

If you aren’t, then before delving deep into ReactJS props, it’s important to revisit concepts on parent and child components.

class ParentComponent extends Component {
render() {
return (
< h1 >
I'm the big parent component.
<ChildComponent />
</ h1 >
);
}
}

And here is the child component:

const ChildComponent = () => {
return <p>I'm a small child!</p>
};

And did you realize that when we called the child component inside the parent component, we end up rendering the same data again and again?

The problem we want to solve here is, we want to render the dynamic data and not static data!

Let’s understand this with a simple example. Here we have two components:

One is the parent component which is a class component:

//this is Parent component

import React, { Component } from 'react';
import MyComponent from './MyComponent.jsx';
class App extends Component {
render() {
return (
<div>
<MyComponent />
<MyComponent />
< /div>
);
}
}
export default App;

And we are rendering the child component ( MyComponent ) which is a functional component inside the parent as follows:

import React from 'react';
const MyComponent = () => {
return < h1 > Hello Michael </h1>
}
export default MyComponent;

The result will be like this:

Hello Michael
Hello Michael

This is coming twice, because we have used <MyComponent> twice in our parent component. We can re-use this component any ‘n’ number of times as we want.

Now, what if a certain scenario demands that we don’t require this static data in the child component, and we want some dynamic data when the component renders? What I meant is that I want to reuse the child component not with the data it has, but with some other data like:

Hello Michael
Hello Professor

Here we can make use of Props or properties. We can add props in the component in the same way that we add attributes in our HTML.

Let’s add Props in our older component and see the results:

import React, { Component } from 'react';
import MyComponent from './MyComponent.jsx';
class App extends Component {
render() {
return (
<div>
<MyComponent name = "Michael" />
<MyComponent name = "Professor" />
</div>
);
}
}
export default App;  

In the above file, we have used a name attribute with the desired dynamic value we want after rendering the data. Now, the most important point here is to pass props to the child component.

Passing Props >>>>>

import React from 'react';
const MyComponent = (props) => {
return < h1 > {props.name} </ h1>
}
export default MyComponent;  

If you try to console the value of Props, you will see nothing but a plain JavaScript object with key-value pairs. We can access the value as key of “name” using (.) dot notation like this >>> “props.name“,

In the final step, we have used interpolation to use the props and we enclose it in curly brackets because it is a JSX expression.

Now after calling the child component inside the parent component, here comes the desired output which is

Hello Michael
Hello Professor 

Now that we’ve successfully rendered the data of the child component from the parent component, let’s dig deeper!

### Props in the Constructor:

In the above example, we have used a functional component.

What if we have a class component and we want to use props in that component?

Normally, a constructor() method is invoked when a class in a component is created without using the newer public class fields syntax. Most of the times when a constructor() is invoked, the super() method is invoked inside of it. Otherwise, the parent’s constructor will not be executed.

See the snippet below for the class component:

class MyComponent extends React.Component {
constructor(props) {
super(props);
console.log(this.props); // props will be logged here.
}
render() {
return < h1 >Hello {this.props.name}</h1>;    }
}  

To access the props we use this.props.

To summarize the above: If we want to use this.props inside the constructor, we need to pass it in super, or else we can use it in render() without using super()

## Using Props in React & Passing Data using Props

Props are mainly used for passing data from the parent component to child component. It motivates us to reuse the components and reduce redundancy as well. But as a growing app, you might see a lot of bugs with typechecking.

In React there is a special inbuilt feature that is used to check the basic validations during typechecking using PropTypes.

See the depth and power of propTypes here:

import PropTypes from 'prop-types'
export default class Mycomponent extends React.Component {
render() {
// .... Your code goes here
}
}
content: PropTypes.string.isRequired,
message: PropTypes.array.isRequired,
onClick: PropTypes.func.isRequired,
length: PropTypes.number.isRequired,
styles: PropTypes.object.isRequired,
} 

PropTypes, a built-in-type checker, ensures that the right type of props is passed to a component. We can define components without propTypes as well, but why risk our application with any wrong data type that might lead to a crash?

NOTE: propTypes can only be checked in development mode (for performance reasons)

PROPTYPES exports a huge range of validators which can be used to make sure that the data you receive is checked and valid, completely bug free!

To use typechecking on the props for a component, let’s use and assign the special propTypes property as follows:

import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
return (
< h1 >Hello, {this.props.name}</h1>
);
}
}

MyComponent.propTypes = {
name: PropTypes.string
};  

In this example, we have used “PropTypes.string”. When an invalid value is provided for a prop, for-ex, other than a string, a warning will be thrown in the JavaScript console. To learn more about prop types, head over here

### Default Props

There could be certain scenarios in which we need some default props so that props are set even if a parent component doesn’t pass the props down.

In this case, we can also define default values for the props directly to the constructor by assigning to the special property known as defaultProps provided by React.

class MyComponent extends React.Component {
render() {
return (
< h1 >Here comes the, {this.props.name}</h1>
);
}
}

// Specifies the default values for props:
MyComponent.defaultProps = {
name: 'new value'
};

// Renders "Here comes, new value":
ReactDOM.render(
<MyComponent />,
document.getElementById('dummy')
);


Default props work great in the situation when the same default value can be utilized again and again for every instance of the component. Again reduce the LOC (line of code).

## Why are Props useful?

Props provide a medium so that components can talk to each other.  In fact, we can reduce thousands of lines of code just by using Props!

Whenever we declare any component it can be either a class component or a functional component. One thing to notice here is, no matter what kind of component is, it should never change its props value.

Hence the components should act like pure functions (which can’t change their own input) to their props.

But, if you really want to change or introduce some dynamic UIs that should change within the component, you should learn about “State”.

State allows React components to change their values over time without any violations. A state is usually called as an encapsulated one or having a local scope of the component.

It is not accessible to any component other than the one that owns it and sets it.

You can learn about the state in this article.

## Can we use Props and State Together?

Absolutely  ! Let’s understand with the following example how we can combine both state and props in our component.

import React from 'react';

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
content: "Some Content from props..."   //Line-8
}
}
render() {        //Line-11
return (
<div>
<Content contentProp={this.state.content} />
</div>
);
}
}
render() {
return (
<div>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
< h2 >{this.props.contentProp}</h2>
</div>
);
}
}
export default App;          

An explanation for the above snippet:

Here we have initialized and used the state in our parent component (line number 7-8) and we have used that state by passing it down the component tree using props.

Inside the render() (line number 11), we are setting the props data as headerProp and contentProp used in child components which are <Header> component and <Content> component.

Now, if you change the state in the parent component, all the child components get updated, because the single source pf data is State here!

## What are the differences between props and state?

Let’s  take a look at some high-level differences between state and props. Although they do similar things, they are used differently.

While both are used for data manipulation, one is of private and the other is of dynamic context.

• Props are used to pass data from parent to child whereas the state is used for data manipulation inside the component.
•  We can get the value of props from the parent component, where we get the value of state object from the initial data defined in the constructor() method.
•  While this.props is set up by React itself, with this.state we are free to add additional fields to the component manually to store something or in a scenario that doesn’t participate in the data flow.
•  Props are immutable, i.e We can't change props passed to a component whereas we can change the Statei.e React uses the setState() method to update the object of a state (but within the component itself)

## Conclusion :

Props is a very crucial concept while learning React.

In this article, you have learned about the lifeline of React, which is Props, and how we can use props in React. You have got clarity on why a component updates or re-renders when data in the props changes.

We also saw that whenever data changes in props, the component will re-render.

Last but not the least, let’s just recall the pointers of all of the above:

• Props are like parameters to a function
• Props cannot be changed, they are immutable
• A prop is a special keyword in React, that stands for properties
• Props can only be passed in a uni-direction i.e (parent to child)
• Props can be used to pass dynamic data to a component
• A component re-renders when data in the props change

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