0% found this document useful (0 votes)
4 views39 pages

MEAN Stack Technologies Unit-2

Unit 2 covers the basics of JavaScript, including objects, primitives, control statements, arrays, functions, and regular expressions. It explains object creation, property access, methods, and the use of the 'this' keyword, along with various operators such as arithmetic, assignment, comparison, and logical operators. Additionally, it discusses best practices for using JavaScript variables and objects, emphasizing the importance of avoiding unnecessary object declarations for primitive types.

Uploaded by

hodeeevikas2012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

MEAN Stack Technologies Unit-2

Unit 2 covers the basics of JavaScript, including objects, primitives, control statements, arrays, functions, and regular expressions. It explains object creation, property access, methods, and the use of the 'this' keyword, along with various operators such as arithmetic, assignment, comparison, and logical operators. Additionally, it discusses best practices for using JavaScript variables and objects, emphasizing the importance of avoiding unnecessary object declarations for primitive types.

Uploaded by

hodeeevikas2012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

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

MEAN Stack Technologies Unit-2 1


firstName John

lastName Doe

age 50

eyeColor blue

Accessing Object Properties


You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Try it Yourself »
Example2
person["lastName"];
Try it Yourself »
JavaScript objects are containers for named values called properties.

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

fullName function() {return this.firstName + " " + this.lastName;}

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.

MEAN Stack Technologies Unit-2 2


I.E. this.firstName means the firstName property of person.

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.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

The this Keyword


In a function definition, this refers to the "owner" of the function.
In the example above, this is the person object that "owns"
the fullName function.
In other words, this.firstName means the firstName property of this object.
Learn more about this in The JavaScript this Tutorial.

Accessing Object Methods


You access an object method with the following syntax:
objectName.methodName()
Example
name = person.fullName();
Try it Yourself »
If you access a method without the () parentheses, it will return the function
definition:
Example
name = person.fullName;
Try it Yourself »
Do Not Declare Strings, Numbers, and
Booleans as Objects!
When a JavaScript variable is declared with the keyword " new", the variable is
created as an object:
x = new String(); // Declares x as a String object
y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow
down execution speed.
You will learn more about objects later in this tutorial.

MEAN Stack Technologies Unit-2 3


Exercise:
Alert "John" by extracting information from the person object.
const person = {
firstName: "John",
lastName: "Doe"
};

alert( );

JavaScript Operators
The Addition Operator + adds numbers:

The Assignment Operator = assigns a value to a variable.

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 »

MEAN Stack Technologies Unit-2 4


JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Types of JavaScript Operators
There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators

JavaScript Arithmetic Operators


Arithmetic operators perform arithmetic on numbers (literals or variables).
Operator Description

+ 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:

MEAN Stack Technologies Unit-2 5


Example
let x = a + b;
Try it Yourself »
or expressions:
Example
let x = (100 + 50) * a;
Try it Yourself »

Operators and Operands


The numbers (in an arithmetic operation) are called operands.
The operation (to be performed between the two operands) is defined by
an operator.
Operand Operator Operand

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.

MEAN Stack Technologies Unit-2 6


Example
let x = 5;
let y = 2;
let z = x / y;
Try it Yourself »
Remainder
The modulus operator (%) returns the division remainder.
Example
let x = 5;
let y = 2;
let z = x % y;
Try it Yourself »
Incrementing
The increment operator (++) increments numbers.
Example
let x = 5;
x++;
let z = x;
Try it Yourself »
Decrementing
The decrement operator (--) decrements numbers.
Example
let x = 5;
x--;
let z = x;
Try it Yourself »
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the
second operand.
Example
let x = 5;
let z = x ** 2;
Try it Yourself »
x ** y produces the same result as Math.pow(x,y):
Example
let x = 5;
let z = Math.pow(x,2);
Try it Yourself »

MEAN Stack Technologies Unit-2 7


Operator Precedence
Operator precedence describes the order in which operations are performed in
an arithmetic expression.
Example
let x = 100 + 50 * 3;
Try it Yourself »
Is the result of example above the same as 150 * 3, or is it the same as 100 +
150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).
And (as in school mathematics) the precedence can be changed by using
parentheses.
When using parentheses, the operations inside the parentheses are computed
first:
Example
let x = (100 + 50) * 3;
Try it Yourself »
When many operations have the same precedence (like addition and subtraction
or multiplication and division), they are computed from left to right:
Examples
let x = 100 + 50 - 3;
Try it Yourself »
let x = 100 / 50 * 3;

JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.

Operator Example Same As

= 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

MEAN Stack Technologies Unit-2 8


Shift Assignment Operators
Operator Example Same As

<<= x <<= y x = x << y

>>= x >>= y x = x >> y

>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators


Operator Example Same As

&= x &= y x=x&y

^= x ^= y x=x^y

|= x |= y x=x|y

Logical Assignment Operators


Operator Example Same As

&&= x &&= y x = 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.

Simple Assignment Examples


let x = 10;

Try it Yourself »
let x = 10 + y;

Try it Yourself »

The += Operator
The Addition Assignment Operator adds a value to a variable.

MEAN Stack Technologies Unit-2 9


Addition Assignment Examples
let x = 10;
x += 5;

Try it Yourself »
let text = "Hello"; text += " World";

Try it Yourself »

The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example


let x = 10;
x -= 5;

Try it Yourself »

The *= Operator
The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example


let x = 10;
x *= 5;

Try it Yourself »

The **= Operator


The Exponentiation Assignment Operator raises a variable to the power of
the operand.

Exponentiation Assignment Example


let x = 10;
x **= 5;

Try it Yourself »

The /= Operator
The Division Assignment Operator divides a variable.

MEAN Stack Technologies Unit-2 10


Division Assignment Example
let x = 10;
x /= 5;

Try it Yourself »

The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example


let x = 10;
x %= 5;

Try it Yourself »

The <<= Operator


The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example


let x = -100;
x <<= 5;

Try it Yourself »

The >>= Operator


The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example


let x = -100;
x >>= 5;

Try it Yourself »

The >>>= Operator


The Unsigned Right Shift Assignment Operator right shifts a variable
(unsigned).

Unsigned Right Shift Assignment Example


let x = -100;
x >>>= 5;

MEAN Stack Technologies Unit-2 11


Try it Yourself »

The &= Operator


The Bitwise AND Assignment Operator does a bitwise AND operation on two
operands and assigns the result to the the variable.

Bitwise AND Assignment Example


let x = 10;
x &= 5;

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.

Bitwise OR Assignment Example


let x = 10;
x |= 5;

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.

Bitwise XOR Assignment Example


let x = 10;
x ^= 5;

Try it Yourself »

The &&= Operator


The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example


let x = 10;
x &&= 5;

Try it Yourself »

MEAN Stack Technologies Unit-2 12


The ||= Operator
The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example


let x = 10;
x ||= 5;

Try it Yourself »
The ||= operator is an ES2020 feature.

The ??= Operator


The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example


let x = 10;
x ??= 5;

JavaScript Comparison Operators


Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

MEAN Stack Technologies Unit-2 13


JavaScript String Comparison
All the comparison operators above can also be used on strings:
Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
Try it Yourself »
Note that strings are compared alphabetically:
Example
let text1 = "20";
let text2 = "5";
let result = text1 < text2;
Try it Yourself »

JavaScript String Addition


The + can also be used to add (concatenate) strings:
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
Try it Yourself »
The += assignment operator can also be used to add (concatenate) strings:
Example
let text1 = "What a very ";
text1 += "nice day";
The result of text1 will be:
What a very nice day
Try it Yourself »
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will
return a string:
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;

The result of x, y, and z will be:


10
55
Hello5

MEAN Stack Technologies Unit-2 14


Try it Yourself »
JavaScript Logical Operators
Operator Description

&& logical and

|| logical or

! logical not

JavaScript Type Operators


Operator Description

typeof Returns the type of a variable

instanceof Returns true if an object is an instance of an


object type

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right 5 >>> 1 0101 >>> 1 0010 2


shift

Expressions in javascript

MEAN Stack Technologies Unit-2 15


This chapter describes JavaScript's expressions and operators, including
assignment, comparison, arithmetic, bitwise, logical, string, ternary and
more.

At a high level, an expression is a valid unit of code that resolves to a value.


There are two types of expressions: those that have side effects (such as
assigning values) and those that purely evaluate.

The expression x = 7 is an example of the first type. This expression uses


the = operator to assign the value seven to the variable x. The expression
itself evaluates to 7.

The expression 3 + 4 is an example of the second type. This expression uses


the + operator to add 3 and 4 together and produces a value, 7. However, if
it's not eventually part of a bigger construct (for example, a variable
declaration like const z = 3 + 4), its result will be immediately discarded — this
is usually a programmer mistake because the evaluation doesn't produce
any effects.

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

These operators join operands either formed by higher-precedence operators


or one of the basic expressions. A complete and detailed list of operators and
expressions is also available in the reference.

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

Despite * and + coming in different orders, both expressions would result


in 7 because * has precedence over +, so the *-joined expression will always
be evaluated first. You can override operator precedence by using
parentheses (which creates a grouped expression — the basic expression).

MEAN Stack Technologies Unit-2 16


To see a complete table of operator precedence as well as various caveats,
see the Operator Precedence Reference page.

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:

operand1 operator operand2


Copy to Clipboard

For example, 3 + 4 or x * y. This form is called an infix binary operator,


because the operator is placed between two operands. All binary operators
in JavaScript are infix.

A unary operator requires a single operand, either before or 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.

Type of Control Statement in JavaScript


Every programming language, basically, has two types of control statements as follows:

 Conditional Statements: based on an expression passed, a conditional statement makes a


decision, which results in either YES or NO.
 Iterative Statements (Loop): Until and unless the expression or the condition given is satisfied,
these statements repeat themselves.

Examples
let’s understand these statements along with examples:

MEAN Stack Technologies Unit-2 17


1. Conditional Statements
This is where the flow of the execution in a program is decided. Conditional Statements decide
the next step based of the result. Conditional statement results in either True or False. Whatever
the condition is passed, if that is true, then the program moves to the next step and if the
condition is False, then the program moves to another step. These statements are executed only
once, unlike Loop statements.
Following are the different types of Conditional Statements:
IF
when you want to check for a specific condition. With the IF condition, the inner code block is
executed if the condition provided is satisfied.
Syntax:
if (condition) {
//code block to be executed if condition is satisfied
}
IF-ELSE
an extended version of IF. When you want to check a specific condition and two
Syntax:

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

MEAN Stack Technologies Unit-2 18


Break;
case b:
//code block to be executed
Break;
case n:
//code block to be executed
Break;
default:
//default code to be executed if none of the above case is executed
}
The above code contains an expression at the very beginning, which is check and compared with
the cases included. If the expression passed matches with the case a, the code block inside the
case is executed. The same applies for case b and n, and when the expression passed matches
with none of the cases mentioned, it code enters default case and the code under default case is
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

MEAN Stack Technologies Unit-2 19


}
DO-WHILE
Similar to a while loop, with a twist that keeps a condition at the end of the loop. Also known as
Exit Control Loop, DO-WHILE executes the code and then checks for the condition.

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:

for (initialize; condition; increment/decrement)


{
//code block to be executed
}
With initialize, it starts the loop, here a declared variable is used. Then the exit condition for the
loop is checked in condition part. When this condition returns true, the code block inside is
executed. When, in case, if the condition returns false or fails, it goes to increment/decrement
part and the variable is assigned an updated value. Values are updated until the condition is
satisfied.

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:

MEAN Stack Technologies Unit-2 20


var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
Test it Now
The .length property returns the length of an array.
Output of the above example
Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Test it Now
Output of the above example
Arun
Varun
John

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in
constructor so that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Test it Now
Output of the above example
Jai
Vijay
Smith

MEAN Stack Technologies Unit-2 21


JavaScript Array Methods
Let's see the list of JavaScript array methods with their description.

Methods Description

concat() It returns a new array object that contains two or more


merged arrays.

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.

every() It determines whether all the elements of an array are


satisfying the provided function conditions.

flat() It creates a new array carrying sub-array elements


concatenated recursively till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens
the result into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another


array element.

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.

forEach() It invokes the provided function once for each element of an


array.

includes() It checks whether the given array contains the specified


element.

indexOf() It searches the specified element in the given array and


returns the index of the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the
array, then loops through these keys.

MEAN Stack Technologies Unit-2 22


lastIndexOf() It searches the specified element in the given array and
returns the index of the last match.

map() It calls the specified function for every array element and
returns the new array

of() It creates a new array from a variable number of arguments,


holding any type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to


initial) right and reduces the array to a single value.

reduceRight() It executes a provided function for each value from right to


left and reduces the array to a single value.

some() It determines if any element of the array passes the test of


the implemented function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the
given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified


array.

toString() It converts the elements of a specified array into string form,


without affecting the original array.

unshift() It adds one or more elements in the beginning 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

MEAN Stack Technologies Unit-2 23


array (generally denoted by the name of the array). The base value is index 0
and the difference between the two indexes is the offset.

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,

const words = ['hello', 'world', 'welcome'];

Here, words is an array. The array is storing 3 values.

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,

const array1 = ["eat", "sleep"];

2. Using the new keyword


You can also create an array using JavaScript's new keyword.

const array2 = new Array("eat", "sleep");

In both of the above examples, we have created an array having two


elements.

Note: It is recommended to use array literal to create an array.

MEAN Stack Technologies Unit-2 24


Here are more examples of arrays:

// empty array
const myList = [ ];

// array of numbers
const numberArray = [ 2, 4, 6, 8];

// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];

// array with mixed data types


const newData = ['work', 'exercise', 1, true];

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')}
];

Access Elements of an Array


You can access elements of an array using indices (0, 1, 2 …). For example,
const myArray = ['h', 'e', 'l', 'l', 'o'];

// first element
console.log(myArray[0]); // "h"

// second element
console.log(myArray[1]); // "e"
Run Code

Array indexing in JavaScript

MEAN Stack Technologies Unit-2 25


Note: Array's index starts with 0, not 1.

Add an Element to an Array


You can use the built-in method push() and unshift() to add elements to an
array.
The push() method adds an element at the end of the array. For example,
let dailyActivities = ['eat', 'sleep'];

// add an element at the end


dailyActivities.push('exercise');

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']


Run Code

The unshift() method adds an element at the beginning of the array. For
example,
let dailyActivities = ['eat', 'sleep'];

//add an element at the start


dailyActivities.unshift('work');

console.log(dailyActivities); // ['work', 'eat', 'sleep']


Run Co

Change the Elements of an Array


You can also add elements or change the elements by accessing the index
value.
let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 2 index


dailyActivities[2] = 'exercise';

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']


Run Code

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'];

MEAN Stack Technologies Unit-2 26


// this will add the new element 'exercise' at the 3 index
dailyActivities[3] = 'exercise';

console.log(dailyActivities); // ["eat", "sleep", undefined, "exercise"]


Run Code

Basically, if you try to add elements to high indices, the indices in between will
have undefined value.

Remove an Element from an Array


You can use the pop() method to remove the last element from an array.
The pop() method also returns the returned value. For example,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// remove the last element


dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']


const removedElement = dailyActivities.pop();

//get removed element


console.log(removedElement); // 'sleep'
console.log(dailyActivities); // ['work', 'eat']
Run Code

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'];

// remove the first element


dailyActivities.shift();

console.log(dailyActivities); // ['eat', 'sleep']


Run Code

Array length
You can find the length of an element (the number of elements in an array)
using the length property. For example,

const dailyActivities = [ 'eat', 'sleep'];

MEAN Stack Technologies Unit-2 27


// this gives the total number of elements in an array
console.log(dailyActivities.length); // 2

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

concat() joins two or more arrays and returns a result

indexOf() searches an element of an array and returns its position

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

forEach() calls a function for each element

includes() checks if an array contains a specified element

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

sort() sorts the elements alphabetically in strings and in ascending order

slice() selects the part of an array and returns the new array

splice() removes or replaces existing elements and/or adds new elements

JavaScript Functions
JavaScript functions are used to perform operations. We can call
JavaScript function many times to reuse the code.

MEAN Stack Technologies Unit-2 28


Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many
lines of code each time to perform a common task.

JavaScript Function Syntax


The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }

JavaScript Functions can have 0 or more arguments.

JavaScript Function Example


Let’s see the simple example of function in JavaScript that does not has
arguments.

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

Output of the above example

JavaScript Function Arguments


We can call function by passing arguments. Let’s see the example of function
that has one argument.

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>

MEAN Stack Technologies Unit-2 29


6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now

Output of the above example

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see
the example of function that returns value.

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

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new
Function object. It executes the code globally. However, if we call the
constructor directly, a function is created dynamically but in an unsecured
way.

Syntax
1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

MEAN Stack Technologies Unit-2 30


JavaScript Function Methods
Let's see function methods with description.

Method Description

apply() It is used to call a function contains this value and a single array
of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument


list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples


Example 1
Let's see an example to display the sum of given numbers.

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:

MEAN Stack Technologies Unit-2 31


8

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.

What Happens When A Constructor Gets Called?

When a constructor gets invoked in JavaScript, the following sequence of operations take place:

 A new empty object gets created.


 The this keyword begins to refer to the new object and it becomes the current instance
object.
 The new object is then returned as the return value of the constructor.

JavaScript Constructor Examples

Here’s a few examples of constructors in JavaScript:

Using the "this" Keyword

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();

Create Multiple Objects

In JavaScript, multiple objects can be created in a constructor:

//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 with Parameters

A constructor can also have parameters:

//Constructor

MEAN Stack Technologies Unit-2 32


function User (name, age) {
this.name = name;
this.age = age;
}
var user1 = new User('Bob', 25);
var user2 = new User('Alice', 27);

In the above example, arguments are passed to the constructor during object creation. This
allows each object to have different property values.

Constructor vs Object Literal

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

Properties and methods can be added to a constructor using a 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.

MEAN Stack Technologies Unit-2 33


Built-in Constructors

JavaScript has some built-in constructors, including the following:

var a = new Object();


var b = new String();
var c = new String('Bob')
var d = new Number();
var e = new Number(25);
var f = new Boolean();
var g = new Boolean(true);

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.

JavaScript RegExp Reference


A regular expression is a pattern of characters.

The pattern is used to do pattern-matching "search-and-replace" functions on text.

In JavaScript, a RegExp Object is a pattern with Properties and Methods.

Syntax
/pattern/modifier(s);

Example
let pattern = /w3schools/i;

Try it Yourself »

Example explained:

w3schools The pattern to search for

/w3schools/ A regular expression

/w3schools/i A case-insensitive regular expression


For a tutorial about Regular Expressions, read our JavaScript RegExp Tutorial.

MEAN Stack Technologies Unit-2 34


Browser Support

/regexp/ is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Modifiers

Modifiers are used to perform case-insensitive and global searches:

Modifier Description

g Perform a global match (find all matches rather than stopping after the
first match)

i Perform case-insensitive matching

m Perform multiline matching


Brackets

Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

Metacharacters

Metacharacters are characters with a special meaning:

MEAN Stack Technologies Unit-2 35


Metacharacter Description

. Find a single character, except newline or line terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like this: \bHI,


end like this: HI\b

\B Find a match, but not at the beginning/end of a word

\0 Find a NULL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal number dd

\udddd Find the Unicode character specified by a hexadecimal number dddd


Quantifiers
Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

n{X} Matches any string that contains a sequence of X n's

MEAN Stack Technologies Unit-2 36


n{X,Y} Matches any string that contains a sequence of X to Y n's

n{X,} Matches any string that contains a sequence of at least X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific string n

?!n Matches any string that is not followed by a specific string n


RegExp Object Properties
Property Description

constructor Returns the function that created the RegExp object's prototype

global Checks whether the "g" modifier is set

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern


RegExp Object Methods
Method Description

compile() Deprecated in version 1.5. Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

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

MEAN Stack Technologies Unit-2 37


to ease to development of the applications for the enterprise, that has been valued by the
megabyte. It is now maintained by Google. AngularJS was released with version 1.6, which
contains the component-based application architecture concept. This release version removed
the Sandbox, which facilitates security, despite having the various vulnerabilities that have
evolved, which bypassed the sandbox.
Features of AngularJS:
 Easy to work with: All you need to know to work with AngularJS is the basics of HTML,
CSS, and JavaScript, not necessarily to be an expert in these technologies.
 Time-saving: AngularJS allows us to work with components and hence we can use them
again which saves time and unnecessary code.
 Ready to use the template: AngularJS is mainly plain HTML, and it mainly makes use of
the plain HTML template and passes it to the DOM and then the AngularJS compiler. It
traverses the templates and then they are ready to use.
AngularJS (version 1.5) was replaced by Angular (Typescript) in 2016. They are completely
different frameworks. Angular is currently at version 10.

Difference between JavaScript and AngularJS:


JavaScript AngularJS

It was developed by Netscape. It was developed by Google.

It is a lightweight and object-oriented


It is an open-source framework.
scripting language

It works on the concept of dynamic It works on the model view controller (MVC)
typing. concept for building apps.

JavaScript is fast in comparison to


It is slow in comparison to JavaScript.
AngularJS.

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.

MEAN Stack Technologies Unit-2 38


MEAN Stack Technologies Unit-2 39

You might also like