MEAN Stack Technologies Unit-2
MEAN Stack Technologies Unit-2
UNIT II: JavaScript: The Basic of JavaScript: Objects, Primitives Operations and Expressions,
Control Statements, Arrays, Functions, Constructors, Pattern Matching using Regular
Expressions. Angular Java Script Angular JS Expressions: ARRAY, Objects, $eval, Strings,
Angular JS Form Validation & Form Submission, Single Page Application development using
Angular JS
JavaScript Objects
You have already learned that JavaScript variables are containers for data
values.
This code assigns a simple value (Fiat) to a variable named car:
let car = "Fiat";
Try it Yourself »
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
const car = {type:"Fiat", model:"500", color:"white"};
Try it Yourself »
The values are written as name:value pairs (name and value separated by a
colon).
It is a common practice to declare objects with the const keyword.
Learn more about using const with objects in the chapter: JS Const.
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Try it Yourself »
Spaces and line breaks are not important. An object definition can span multiple
lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Try it Yourself »
Object Properties
The name:values pairs in JavaScript objects are called properties:
Property Property Value
lastName Doe
age 50
eyeColor blue
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object.
I.E. this.firstName means the firstName property of this.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object.
Methods like call(), apply(), and bind() can refer this to any object.
alert( );
JavaScript Operators
The Addition Operator + adds numbers:
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:
Assignment Examples
let x = 10;
Try it Yourself »
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;
Try it Yourself »
JavaScript Addition
The Addition Operator (+) adds numbers:
Adding
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
The two numbers can be literals:
Example
let x = 100 + 50;
Try it Yourself »
or variables:
100 + 50
Adding
The addition operator (+) adds numbers:
Example
let x = 5;
let y = 2;
let z = x + y;
Try it Yourself »
Subtracting
The subtraction operator (-) subtracts numbers.
Example
let x = 5;
let y = 2;
let z = x - y;
Try it Yourself »
Multiplying
The multiplication operator (*) multiplies numbers.
Example
let x = 5;
let y = 2;
let z = x * y;
Try it Yourself »
Dividing
The division operator (/) divides numbers.
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
^= x ^= y x=x^y
|= x |= y x=x|y
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Try it Yourself »
let x = 10 + y;
Try it Yourself »
The += Operator
The Addition Assignment Operator adds a value to a variable.
Try it Yourself »
let text = "Hello"; text += " World";
Try it Yourself »
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.
Try it Yourself »
The *= Operator
The Multiplication Assignment Operator multiplies a variable.
Try it Yourself »
Try it Yourself »
The /= Operator
The Division Assignment Operator divides a variable.
Try it Yourself »
The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.
Try it Yourself »
Try it Yourself »
Try it Yourself »
Try it Yourself »
The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two
operands and assigns the result to the variable.
Try it Yourself »
The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two
operands and assigns the result to the variable.
Try it Yourself »
Try it Yourself »
Try it Yourself »
The ||= operator is an ES2020 feature.
== equal to
!= not equal
? ternary operator
|| logical or
! logical not
Expressions in javascript
As the examples above also illustrate, all complex expressions are joined
by operators, such as = and +. In this section, we will introduce the following
operators:
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
BigInt operators
String operators
Conditional (ternary) operator
Comma operator
Unary operators
Relational operators
The precedence of operators determines the order they are applied when
evaluating an expression. For example:
const x = 1 + 2 * 3;
const y = 2 * 3 + 1;
Copy to Clipboard
JavaScript has both binary and unary operators, and one special ternary
operator, the conditional operator. A binary operator requires two operands,
one before the operator and one after the operator:
operator operand
operand operator
Copy to Clipboard
For example, x++ or ++x. The operator operand form is called a prefix unary
operator, and the operand operator form is called a postfix unary operator. +
+ and -- are the only postfix operators in JavaScript — all other operators,
like !, typeof, etc. are prefix.
Examples
let’s understand these statements along with examples:
if (condition)
{
// code to be executed of condition is true
}
else {
// code to be executed of condition is false
}
As you can see, when the condition is satisfied in IF-ELSE, the first block of code will be
executed and if the condition isn’t satisfied, the second block of code will be executed.
SWITCH
A switch statement is similar to IF and is of use when you need to execute one code out of the
multiple code block execution possibilities, based on the result of the expression passed. Switch
statements carry an expression, which is compared with values of the following cases and once a
match is found, code associated with that case executes.
Syntax:
switch (expression) {
case a:
//code block to be executed
Now, that we have understood the conditional statements, let’s learn about the second type, i.e.
Iterative Statements.
2. Iterative Statement
Looping, for any programming language, is a powerful tool in order to execute a set of
instructions, repeatedly, while the expression passed is satisfied. A very basic example can be, to
print “Hello World” for 10 times. Now, writing the same print statement with “Hello world“ for
10 straight times will be time-consuming and will impact the execution time. And this is where
looping comes handy. There are three Iterative statements: WHILE, DO-WHILE and FOR.
Let’s understand each with syntax.
WHILE
one of the control flow statement, which executes a code block when the condition is satisfied.
But unlike IF, while keeps repeating itself until the condition is satisfied. Difference between IF
and while can be, IF executes code ‘if’ the condition is satisfied while the while keeps repeating
itself until the condition is satisfied.
Syntax:
while (condition)
{
//code block to be executed when condition is satisfied
Syntax:
while
{
//code block to be executed when condition is satisfied
} (condition)
If the condition at the end is satisfied, the loop will repeat.
FOR
a for loop will execute a code block for a number of times. Compared to other loops, FOR is
shorter and easy to debug as it contains initialization, condition and increment or decrement in a
single line.
Syntax:
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Test it Now
Output of the above example
Arun
Varun
John
Methods Description
copywithin() It copies the part of the given array with its own elements
and returns the modified array.
entries() It creates an iterator object and a loop that iterates over each
key/value pair.
flatMap() It maps all array elements via mapping function, then flattens
the result into a new array.
filter() It returns the new array containing the elements that pass
the provided function conditions.
find() It returns the value of the first element in the given array
that satisfies the specified condition.
findIndex() It returns the index value of the first element in the given
array that satisfies the specified condition.
keys() It creates an iterator object that contains only the keys of the
array, then loops through these keys.
map() It calls the specified function for every array element and
returns the new array
slice() It returns a new array containing the copy of the part of the
given array.
values() It creates a new iterator object carrying values for each index
in the array.
What is an Array?
An array is a collection of items of same data type stored at contiguous memory
locations.
This makes it easier to calculate the position of each element by simply adding
an offset to a base value, i.e., the memory location of the first element of the
JavaScript Arrays
In this tutorial, you will learn about JavaScript arrays with the help of
examples.
An array is an object that can store multiple values at once. For example,
Create an Array
You can create an array using two ways:
1. Using an array literal
The easiest way to create an array is by using an array literal [] . For
example,
// empty array
const myList = [ ];
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];
You can also store arrays, functions and other objects inside an array. For
example,
const newData = [
{'task1': 'exercise'},
[1, 2 ,3],
function hello() { console.log('hello')}
];
// first element
console.log(myArray[0]); // "h"
// second element
console.log(myArray[1]); // "e"
Run Code
The unshift() method adds an element at the beginning of the array. For
example,
let dailyActivities = ['eat', 'sleep'];
Suppose, an array has two elements. If you try to add an element at index 3
(fourth element), the third element will be undefined. For example,
let dailyActivities = [ 'eat', 'sleep'];
Basically, if you try to add elements to high indices, the indices in between will
have undefined value.
If you need to remove the first element, you can use the shift() method.
The shift() method removes the first element and also returns the removed
element. For example,
let dailyActivities = ['work', 'eat', 'sleep'];
Array length
You can find the length of an element (the number of elements in an array)
using the length property. For example,
Array Methods
In JavaScript, there are various array methods available that makes it easier
to perform useful calculations.
Some of the commonly used JavaScript array methods are:
Method Description
find() returns the first value of an array element that passes a test
findIndex() returns the first index of an array element that passes a test
push() aads a new element to the end of an array and returns the new length of an array
adds a new element to the beginning of an array and returns the new length of an
unshift()
array
pop() removes the last element of an array and returns the removed element
shift() removes the first element of an array and returns the removed element
slice() selects the part of an array and returns the new array
JavaScript Functions
JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Test it Now
Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.
Method Description
apply() It is used to call a function contains this value and a single array
of arguments.
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Test it Now
Output:
Example 2
Let's see an example to display the power of provided value.
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Test it Now
Output:
Constructor in JavaScript?
A constructor is a special function that creates and initializes an object instance of a class. In
JavaScript, a constructor gets called when an object is created using the new keyword.
The purpose of a constructor is to create a new object and set values for any existing object
properties.
When a constructor gets invoked in JavaScript, the following sequence of operations take place:
When the this keyword is used in a constructor, it refers to the newly created object:
//Constructor
function User() {
this.name = 'Bob';
}
var user = new User();
//Constructor
function User() {
this.name = 'Bob';
}
var user1 = new User();
var user2 = new User();
In the above example, two objects are created using the same constructor.
//Constructor
In the above example, arguments are passed to the constructor during object creation. This
allows each object to have different property values.
An object literal is typically used to create a single object whereas a constructor is useful for
creating multiple objects:
//Object literal
let user = {
name: 'Bob'
}
//Constructor
function User() {
this.name = 'Bob';
}
var user1 = new User();
var user2 = new User();
Each object created using a constructor is unique. Properties can be added or removed from an
object without affecting another one created using the same constructor. However, if an object is
built using an object literal, any changes made to the variable that is assigned the object value
will change the original object.
Object Prototype
//Constructor
function User() {
this.name = 'Bob';
}
let user1 = new User();
let user2 = new User();
//Adding property to constructor using prototype
User.prototype.age = 25;
console.log(user1.age); // 25
console.log(user2.age); // 25
In the above example, two User objects are created using the constructor. A new property age is
later added to the constructor using a prototype, which is shared across all instances of
the User object.
Although these constructors exist, it is recommended to use primitive data types where possible,
such as:
var a = 'Bob';
var b = 25;
var c = true;
Strings, numbers and booleans should not be declared as objects since they hinder performance.
Syntax
/pattern/modifier(s);
Example
let pattern = /w3schools/i;
Try it Yourself »
Example explained:
Modifiers
Modifier Description
g Perform a global match (find all matches rather than stopping after the
first match)
Expression Description
[^0-9] Find any character NOT between the brackets (any non-digit)
Metacharacters
\d Find a digit
constructor Returns the function that created the RegExp object's prototype
AngularJS:
AngularJS is an open-source front-end web development framework for creating web
applications and has great functionality and support. It was released in the year 2010 by the
angular team of Google. It is a constantly developing and expanding framework which
provides improved methods for developing web applications. It mainly works on the model
view controller (MVC) concept for building apps and supports both dependency injection and
data binding features.
History of AngularJS: AngularJS was originally developed in 2008-2009 by Miško Hevery
and Adam abrons at Brat Tech LLC, as software for the online JSON storage service, in order
It works on the concept of dynamic It works on the model view controller (MVC)
typing. concept for building apps.
It does not support dependency While it supports both dependency injection and
injection. data binding.
It is complicated for beginners to learn It is easy to learn AngularJS for beginners who
JavaScript. know JavaScript.
It does not provide support for filters. It provides support for filters.
It is used for dynamic web It is generally suited for building large single-
applications. page applications.