MEAN (Unit 2)
MEAN (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
Objects in Javascript
An object in JavaScript is a data structure used to store related data
collections. It stores data as key-value pairs, where each key is a unique
identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.
There are two primary ways to create an object in JavaScript: Object
Literal and Object Constructor.
1. Creation Using Object Literal
The object literal syntax allows you to define and initialize an object with
curly braces {}, setting properties as key-value pairs.
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
console.log(obj);
Output
{ name: 'Sourav', age: 23, job: 'Developer' }
console.log(obj);
Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Basic Operations on JavaScript Objects
1. Accessing Object Properties
You can access an object’s properties using either dot
notation or bracket notation
Output
Sourav
23
obj.age = 23;
console.log(obj);
Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
Output
{ model: 'Tesla', color: 'Red' }
console.log(obj);
Output
{ model: 'Tesla' }
Output
false
true
Output
name: Sourav
age: 23
7. Merging Objects
Objects can be merged using Object.assign() or the spread syntax
{ ...obj1, ...obj2 }.
Output
{ name: 'Sourav', age: 23 }
8. Object Length
You can find the number of properties in an object using Object.keys().
Output
2
JavaScript Operators
JavaScript operators are symbols or keywords used to perform operations
on values and variables. They are the building blocks of JavaScript
expressions and can manipulate data in various ways.
Output
8 8 8 4
+ adds two numbers.
- subtracts the second number from the first.
* multiplies two numbers.
/ divides the first number by the second.
2. JavaScript Assignment Operators
Assignment operators are used to assign values to variables. They can
also perform operations like addition or multiplication before assigning the
value.
let n = 10;
n += 5;
n *= 2;
console.log(n);
Output
30
= assigns a value to a variable.
+= adds and assigns the result to the variable.
*= multiplies and assigns the result to the variable.
3. JavaScript Comparison Operators
Comparison operators compare two values and return a boolean (true or
false). They are useful for making decisions in conditional statements.
Output
true
false
> checks if the left value is greater than the right.
=== checks for strict equality (both type and value).
Other operators include <, <=, >=, and !==.
4. JavaScript Logical Operators
Comparison operators are mainly used to perform the logical operations
that determine the equality or difference between the values.
Output
false
true
&& returns true if both operands are true.
|| returns true if at least one operand is true.
! negates the boolean value.
5. JavaScript Bitwise Operators
Bitwise operators perform operations on binary representations of
numbers.
Output
1
& performs a bitwise AND.
| performs a bitwise OR.
^ performs a bitwise XOR.
~ performs a bitwise NOT.
6. JavaScript Ternary Operator
The ternary operator is a shorthand for conditional statements. It takes
three operands.
Output
Adult
condition ? expression1 : expression2 evaluates expression1 if the
condition is true, otherwise evaluates expression2.
7. JavaScript Comma Operator
Comma Operator (,) mainly evaluates its operands from left to right
sequentially and returns the value of the rightmost operand.
let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
console.log(res);
Output
3
Each expression is evaluated from left to right.
The final result of the expression is the rightmost value.
8. JavaScript Unary Operators
Unary operators operate on a single operand (e.g., increment,
decrement).
let x = 5;
console.log(++x); // Pre-increment
console.log(x--); // Post-decrement (Output: 6, then x becomes 5)
Output
6
6
++ increments the value by 1.
-- decrements the value by 1.
typeof returns the type of a variable.
9. JavaScript Relational Operators
JavaScript Relational operators are used to compare its operands and
determine the relationship between them. They return a Boolean value
(true or false) based on the comparison result.
Output
true
true
in checks if a property exists in an object.
instanceof checks if an object is an instance of a constructor.
10. JavaScript BigInt Operators
BigInt operators allow calculations with numbers beyond the safe integer
range.
Output
1111111110111111111011111111100n
Operations like addition, subtraction, and multiplication work with
BigInt.
Use n suffix to denote BigInt literals.
11. JavaScript String Operators
JavaScript String Operators include concatenation (+) and concatenation
assignment (+=), used to join strings or combine strings with other data
types.
Output
Hello World
+ concatenates strings.
+= appends to an existing string.
12. JavaScript Chaining Operator (?.)
The optional chaining operator allows safe access to deeply nested
properties without throwing errors if the property doesn’t exist.
const obj = { name: "Aman", address: { city: "Delhi" } };
console.log(obj.address?.city);
console.log(obj.contact?.phone);
Output
Delhi
undefined
?. safely accesses a property or method.
Returns undefined if the property doesn’t exist.
Control Statements in JavaScript
JavaScript control statement is used to control the execution of a
program based on a specific condition. If the condition meets then a
particular block of action will be executed otherwise it will execute another
block of action that satisfies that particular condition.
Types of Control Statements in JavaScript
Conditional Statement: These statements are used for decision-
making, a decision
n is made by the conditional statement based on an expression that is
passed. Either YES or NO.
Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement
will keep repeating itself until and unless it is satisfied.
There are several methods that can be used to perform control statements
in JavaScript:
Table of Content
If Statement
Using If-Else Statement
Using Switch Statement
Using the Ternary Operator (Conditional Operator)
Using For loop
Approach 1: If Statement
In this approach, we are using an if statement to check a specific
condition, the code block gets executed when the given condition is
satisfied.
Syntax:
if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Example: In this example, we are using an if statement to check our
given condition.
const num = 5;
if (num > 0) {
console.log("The number is positive.");
};
Output
The number is positive.
Approach 2: Using If-Else Statement
The if-else statement will perform some action for a specific condition. If
the condition meets then a particular code of action will be executed
otherwise it will execute another code of action that satisfies that particular
condition.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Example: In this example, we are using the if..else statement to verify
whether the given number is positive or negative.
if (num > 0)
console.log("The number is positive.");
else
console.log("The number is negative");
Output
The number is negative
Approach 3: Using Switch Statement
The switch case statement in JavaScript is also used for decision-making
purposes. In some cases, using the switch case statement is seen to be
more convenient than if-else statements.
Syntax:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example: In this example, we are using the above-explained approach.
let num = 5;
switch (num) {
case 0:
console.log("Number is zero.");
break;
case 1:
console.log("Nuber is one.");
break;
case 2:
console.log("Number is two.");
break;
default:
console.log("Number is greater than 2.");
};
Output
Number is greater than 2.
Approach 4: Using the Ternary Operator (Conditional Operator)
The conditional operator, also referred to as the ternary operator (?:), is a
shortcut for expressing conditional statements in JavaScript.
Syntax:
condition ? value if true : value if false
Example: In this example, we are using the ternary operator to find
whether the given number is positive or negative.
let num = 10;
Output
The number is Positive.
Approach 5: Using For loop
In this approach, we are using for loop in which the execution of a set of
instructions repeatedly until some condition evaluates and becomes false
Syntax:
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
Example: In this example, we are using Iterative Statement as a for loop,
in which we find the even number between 0 to 10.
Output
0
2
4
6
8
10
JavaScript Arrays
In JavaScript, an array is an ordered list of values. Each value is called an
element, and each element has a numeric position in the array, known as
its index. Arrays in JavaScript are zero-indexed, meaning the first element
is at index 0, the second at index 1, and so on.
Array in JavaScript
1. Create Array using Literal
Creating an array using array literal involves using square brackets [] to
define and initialize the array.
Output
[]
[ 10, 20, 30 ]
2. Create using new Keyword (Constructor)
The "Array Constructor" refers to a method of creating arrays by
invoking the Array constructor function.
console.log(a);
Output
[ 10, 20, 30 ]
Note: Both the above methods do exactly the same. Use the array literal
method for efficiency, readability, and speed.
Recommended Links
Insert Elements in a JS array
Delete Elements from a JS Array
Interesting Facts about JavaScript Arrays
JavaScript Array Reference
JavaScript Array Examples
Cheat Sheet-A Basic guide to JavaScript .
Basic Operations on JavaScript Arrays
1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The
index in the arrays starts with 0.
Output
HTML
CSS
Output
First Item: HTML
Output
First Item: JS
a[1]= "Bootstrap";
console.log(a);
Output
[ 'HTML', 'CSS', 'JS' ]
[ 'HTML', 'Bootstrap', 'JS' ]
console.log(a);
Output
[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]
Output
Original Array: HTML,CSS,JS
After Removing the last: HTML,CSS
After Removing the First: CSS
After Removing 2 elements starting from index 1: CSS
7. Array Length
We can get the length of the array using the array length property.
Output
Array Length: 3
Output
HTML
CSS
JS
Example: It is the example of Array.forEach() loop.
Output
HTML
CSS
JS
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new
array containing joined arrays elements.
Output
Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React',
'Node.js', 'Expess.js' ]
Output
HTML,CSS,JS
Output
Using Array.isArray() method: true
Using instanceof method: true
Note: A common error is faced while writing the arrays:
const a = [5]
// and
const a = new Array(5)
The above two statements are not the same.
Output: This statement creates an array with an element " [5] ". Try with
the following examples
// Example 1
const a1 = [5]
console.log(a1)
// Example 2
const a2 = new Array(5)
console.log(a2)
Output
[ 5 ]
[ <5 empty items> ]
Functions in JavaScript
Functions in JavaScript are reusable blocks of code designed to perform
specific tasks. They allow you to organize, reuse, and modularize code. It
can take inputs, perform actions, and return outputs.
function sum(x, y) {
return x + y;
}
console.log(sum(6, 9));
Output
15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in
JavaScript:
Begin with the keyword function followed by,
A user-defined function name (In the above example, the name
is sum)
A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
A list of statements composing the body of the function enclosed within
curly braces {} (In the above example, the statement is "return x + y").
Return Statement
In some situations, we want to return some values from a function after
performing some operations. In such cases, we make use of the return.
This is an optional statement. In the above function, "sum()" returns the
sum of two as a result.
Function Parameters
Parameters are input passed to a function. In the above example, sum()
takes two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by
the value of parameters enclosed between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}
let nameVal = "User";
Output
Hello User welcome to GeeksforGeeks
Why Functions?
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
Advantages of Functions in JavaScript
Reusability: Write code once and use it multiple times.
Modularity: Break complex problems into smaller, manageable pieces.
Improved Readability: Functions make code easier to understand.
Maintainability: Changes can be made in one place without affecting
the entire codebase.
JavaScript Object Constructors
An object is the collection of related data or functionality in the form
of key. These functionalities usually consist of several functions and
variables. All JavaScript values are objects except primitives.
const GFG = {
subject : "programming",
language : "JavaScript",
}
Here, subject and language are
the keys and programming and JavaScript are the values.
Object Constructor
A constructor function is a special type of function in JavaScript that is
used to create and initialize objects. Constructors are used with the new
keyword to create instances of a particular type (object). By using
constructors, we can easily create multiple instances of the same type of
object, all with their own unique properties and methods.
↔
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(`My name is ${this.name} and I am ${this.age} years
old.`);
};
}
↔
Output
My name is Akash and I am 30 years old.
My name is Anvesh and I am 25 years old.
this keyword
The this keyword refers to the object it belongs to, like OOPs languages
C++, C#, JAVA etc. this keyword is used in different ways in different
areas. While executing a function in JavaScript that has a reference to its
current execution context, that is the reference by which the function or
data member is called. See the previous example.
Adding Property to an Object
The property can be added to the object by using dot(.) operator
or square bracket.,
const GFG = {
articles: 'computer science',
quantity: 3000,
};
The GFG has two properties "articles" and "quantity". Now we wish to add
one more property name called subject.
Using dot (.) operator
GFG.subject: 'JavaScript';
Using square bracket:
GFG['subject']: 'JavaScript';
Here, subject is the property and 'JavaScript' is the value of the
property. Adding a property to Constructor: We cannot add a property
to an existing constructor like adding a property to an object (see previous
point), for adding a property we need to declare under the constructor.
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.G = "GEEK";
}
Here, we add a property name G with value "GEEK", in this case the
value "GEEK" is not passed as an argument.
Adding a Method to an Object
We can add a new method to an existing object.
GFG.n = function () {
return this.A + this.B;
};
Here, the object is GFG.
Adding a Method to Constructor
function GFG(a, b, c) {
this.A = a;
this.B = b;
this.C = c;
this.n = function () {
return this.A + this.B;
}
}
Here, in the last line a method is added to an object.
Instantiating an object constructor
There are two ways to instantiate object constructor,
const object_name = new Object(); // or
const object_name = new Object("java", "JavaScript", "C#");
const object_name = { };
In 1st method, the object is created by using new keyword like normal
OOP languages, and "Java", "JavaScript", "C#" are the arguments, that
are passed when the constructor is invoked. In 2nd method, the object is
created by using curly braces "{ }".
Assigning properties to the objects: There are two ways to assigning
properties to the objects.
Using dot (.) operator:
object_name . properties = value;
Using third bracket:
object_name [ 'properties'] = value;
Example 1: Object creation by using new keyword and assigning
properties to the object using dot(.) operator.
gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
Output
Subject: JavaScript
Author: GeeksforGeeks
Example 2: Object creation using curly braces and assigning properties
to the object using third bracket "[]" operator.
let gfg = { };
gfg['a'] = "JavaScript";
gfg['b']= "GeeksforGeeks";
Output
Subject: JavaScript
Author: GeeksforGeeks
Example 3: This example shows how to use function() with object
constructor.
gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = function () {
return (gfg.a +" "+ gfg.b);
};
Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks
Example 4: Another way to create a function using function name.
let gfg = { };
gfg.a = "JavaScript";
gfg.b = "GeeksforGeeks";
gfg.c = add;
// Declare function add()
function add() {
return (gfg.a +" "+ gfg.b);
};
Output
Subject: JavaScript
Author: GeeksforGeeks
Adding the strings: JavaScript GeeksforGeeks
console.log(patt.test(s1));
console.log(patt.test(s2));
Output
true
true
Creating a RegExp in JavaScript
There are two primary ways to create a RegExp in JavaScript
1. Using the RegExp Constructor
The RegExp constructor is useful when you need to create a regular
expression dynamically, such as when the pattern or flags might change
based on user input or other conditions.
let pattern = "hello"; // Pattern to match
let flags = "i"; // Case-insensitive flag
let regex = new RegExp(pattern, flags);
console.log(regex.test(s));
Output
true
Here, we dynamically create a RegExp object using the RegExp()
constructor.
The pattern "hello" will match the string "Hello" because of the 'i' flag,
which makes the search case-insensitive.
regex.test(s) returns true because "Hello" matches the pattern "hello" in
a case-insensitive manner.
2. Using Regular Expression Literal
This is the most common and simple way to create a regular expression in
JavaScript. It’s especially useful when the pattern is static (doesn’t change
dynamically).
console.log(regex.test(s));
Output
true
In this example, we define the regular expression directly using literal
notation.
/hello/i means we're looking for the word "hello", and the 'i' flag
ensures the search is case-insensitive.
regex.test(s) returns true because "Hello" matches the pattern "hello"
case-insensitively.
Regular Expression Modifiers can be used to perform multiline
searches which can also be set to case-insensitive matching:
Expressions Descriptions
\d Find a digit
constructor Return the function that created the RegExp object’s prototype
Output
true
Output
[ '123', '456' ]
3. Replacing Substrings
Regular expressions are often used in replacing certain substrings in text.
Output
baz bar baz
introduction to AngularJS
AngularJS is a popular open-source framework that simplifies web
development by creating interactive single-page applications (SPAs).
Unlike traditional websites that load new pages for each click, SPAs offer
a smoother user experience by updating content on the same page.
AngularJS makes this possible by transforming static HTML into dynamic
content that adapts to user interactions. Features like data binding and
dependency injection streamline development, saving you time and effort.
With regular updates and a large community, AngularJS ensures your
web applications stay modern and efficient.
Why Choose AngularJS?
1. Easy to Work With: AngularJS requires only basic knowledge of
HTML, CSS, and JavaScript. You don’t need to be an expert; just bring
your curiosity and creativity.
2. Time-Saving Components: AngularJS allows you to work with
reusable components, saving time and reducing unnecessary code.
Components are the building blocks of your application.
3. Ready-to-Use Templates: AngularJS leverages plain HTML
templates, which it compiles and makes ready for use. No complex
setup—just write your HTML and let AngularJS do the heavy lifting.
4. Directives: AngularJS extends HTML with custom elements and
attributes called directives. These enable you to create reusable
components and define custom behaviors for your application.
Directives make it easier to manipulate the DOM, handle events, and
encapsulate complex UI logic within a single component.
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>
<body style="text-align:center">
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""
ng-init="name='GeeksforGeeks'">
<p> {{ name }} is a portal for geeks.</p>
</div>
</body>
</html>
Output:
Example 2: This example displays the content of the object that we feed
in the ng-init directive.
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>
<body>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""
ng-init="sort={one:'quick sort',
two:'merge sort',
three:'bubble sort'}">
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body>
<center>
<h1 style="color:green">
GeeksforGeeks
</h1>
<h3 style="color:green">
AngularJS Expressions
</h3>
<div ng-app="" ng-init="data={Course:'AngularJS',
topic:'Expression'}">
<p>This is
<span ng-bind="data.Course"></span>
<span ng-bind="data.topic"></span>
Tutorial
</p>
</div>
</center>
</body>
</html>
Output: