0% found this document useful (0 votes)
16 views36 pages

MSD Unit-1 Material

The document outlines the syllabus for a Mean Stack Development course at St. Ann's College, focusing on JavaScript fundamentals including its purpose, features, and differences from Java. It covers topics such as data types, identifiers, and scripting methods, as well as the practical aspects of writing and running JavaScript code. Additionally, it explains primitive and non-primitive data types, and provides examples of variable declarations and object creation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views36 pages

MSD Unit-1 Material

The document outlines the syllabus for a Mean Stack Development course at St. Ann's College, focusing on JavaScript fundamentals including its purpose, features, and differences from Java. It covers topics such as data types, identifiers, and scripting methods, as well as the practical aspects of writing and running JavaScript code. Additionally, it explains primitive and non-primitive data types, and provides examples of variable declarations and object creation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

ST.

ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
MEAN STACK DEVELOPMENT (UNIT-1)
(Job Oriented Course)
SYLLOBUS:
JavaScript: Introduction, Working with Identifiers, Type of Identifiers, Primitive and Non
Primitive Data Types, Operators and Types of Operators, Types of Statements, Non -
Conditional Statements, Types of Conditional Statements, If and Switch Statements, Types of
Loops, Types of Functions, Declaring and Invoking Function, Arrow Function, Built-in
Functions, Working with Classes, Creating and Inheriting Classes, Working with Objects,
Types of Objects, Creating Objects, Creating Arrays, Accessing Arrays, Array Methods,
Creating and Consuming Modules.

1. Why we need JavaScript


 JavaScript is a light-weight object-oriented programming language that is used by
several websites for scripting the web pages.
 It is an interpreted, full-fledged programming language.
 JavaScript enables dynamic interactivity on websites when it is applied to an HTML
document.
 JavaScript helps the users to build modern web applications to interact directly
without reloading the page every time.
 JavaScript is commonly used to dynamically modify HTML and CSS to update a user
interface by the DOM API. It is mainly used in web applications.
 If client-side scripting language JavaScript is used then, this can be done without
consulting the server as can be seen in the below diagram.

2. What is JavaScript
 JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a
popular browser of that time. The language was initially called LiveScript and was
later renamed JavaScript.
 JavaScript is the programming language for web users to convert static web pages to
dynamic web pages.
 JavaScript is a platform independent object-based scripting language that helps
implement client-side and server-side processing for a website. Java script is a case
sensitive language.
 Script means small piece of code. Java script can easily create interactive web pages.
It is designed to add interactivity to HTML pages. JavaScript is a weakly typed
language.
 In general client-side scripting is used for verifying simple validation at client side,
server-side scripting is used for database verifications.
 VBScript, JavaScript and Jscript are examples for client-side scripting and
ASP,JSP,PHP etc., are examples of server-side scripting.
 Web pages are two types.
Static webpage
 Static web page where there is no specific interaction with the client. Web page
designed using HTML and CSS is static.
2. Dynamic webpage
 JavaScript combined with HTML and CSS makes it dynamic. Dynamic web page
which is having interactions with client and as well as validations can be added.

 JavaScript code can be embedded within the HTML page or can be written in an
external file.
 There are mainly two ways of writing JavaScript depending on the platform :
i. Internal Scripting
ii. External Scripting
i. Internal Scripting
 When JavaScript code are written within the HTML file itself, it is called internal
scripting.
 Internal scripting, is done with the help of HTML tag : <script> </script>
 This tag can be placed either in the head tag or body tag within the HTML file.
 JavaScript code written inside <head> element is as shown below :
<html>
<head>
<script>
//internal script
</script>
</head>
<body>
</body>
 All java script statements end with a semicolon. JavaScript code written inside
<body> element is as shown below :
<html>
<head> </head>
<body>
<script>
//internal script
</script>
</body>
</html>

ii. External Scripting


 JavaScript code can be written in an external file also. The file containing JavaScript
code is saved with the extension *.js (e.g. fileName.js). In external file, JavaScript
code is not written inside <script> </script> tag.
 To include the external JavaScript file, the script tag is used with attribute 'src' as
shown in the below-given code-snippet:
<html>
<head>
<script src=“filename.js"></script>
</head>
<body>
</body>
</html>
3. Difference between JavaScript and Java
 Java is object –oriented programming language where as java script is object-based
scripting language.
 Java is a very complex programming language whereas JavaScript is only a scripting
language. The syntax of JavaScript is mostly influenced by the programming
language C.
 Java source code is first compiled and the client interprets the code.
 JavaScript is an interpreted language. The browser interprets the JavaScript code
embedded inside the web page, executes it, and displays the output. It is not compiled
to any other form to be executed.
 Java is a strongly typed language and variables must be declared first to use in the
program. In Java, the type of a variable is checked at compile-time. JavaScript is a
loosely typed language and has a more relaxed syntax and rules.
 Java applications can run in any virtual machine(JVM) or browser. JavaScript code
used to run only in the browser, but now it can run on the server via Node.js.
 Java is mainly used for backend. JavaScript is used for the frontend and backend both.
 Java has a file extension “.Java”, whereas JavaScript has the file extension “.js”. Java
uses more memory. JavaScript uses less memory.
4. Features of JavaScript
 Array handling
 Unicode support
 JavaScript console
 Block scope variables using let and const keywords
 Template Literals
 Error handling
 De-structuring
 Arrow functions
 Enhanced for loop
 Default and Rest parameters
 Classes and Objects
 Inheritance
5. JavaScript Comments
 JavaScript supports line as well as block comments. Line comments(//) instructs
JavaScript interpreter to ignore the text till the end of the line.
 Block comments (/* */) instructs JavaScript interpreter to ignore a text or lines
between them.
6. JavaScript Reserved Words (or) Keywords
 JavaScript has a number of reserved words. These are the words that you cannot use
as identifiers.
 Reserved words have a specific meaning to the JavaScript language and these
meanings does not change during execution of the program. The JavaScript reserved
words are as follows:

7. How to Run JavaScript?


 Being a scripting language, JavaScript cannot run on its own. In fact, the browser is
responsible for running JavaScript code.
 When a user requests an HTML page with JavaScript in it, the script is sent to the
browser and it is up to the browser to execute it.
 The main advantage of JavaScript is that all modern web browsers support JavaScript.
So, you do not have to worry about whether your site visitor uses Internet Explorer,
Google Chrome, Firefox or any other browser. JavaScript will be supported.
 Also, JavaScript runs on any operating system including Windows, Linux or Mac.

8. WORKING WITH IDENTIFIERS(VARIABLES)


 Identifiers are those names that help in naming the elements in JavaScript. JavaScript
variables must have unique names. These names are called Identifiers.
 In JavaScript, variables can be used to store reusable values. Identifiers should follow
below rules:
 Identifier names must start with either a letter, an underscore _, or the dollar sign $.
Identifier names cannot start with numbers.
 Subsequent characters can be letters of alphabets or digits or underscores (_) or a
dollar sign ($).
Example for valid identifiers:let a = 500; const _b = ‘cse'; var $a = ‘welcome';
 Identifiers are case-sensitive. Hence, firstName and FirstName are not the same.
 Reserved keywords are part of programming language syntax and cannot be used as
identifiers.
Type of Identifiers
 The identifiers in JavaScript can be categorized into three as shown below. They can
be declared into specific type based on the data which an identifier will hold and the
scope of the identifier.
i) let
ii) var
iii) const
i) let:
 JavaScript let is a keyword used to declare variables that are block-scoped i.e., it is
available only within the block in which it is defined. Variables defined with
the let keyword cannot be re-declared and must be declared before use.
 The variables which are declared inside the { } block are known as block-scoped
variables. Syntax: let variable_name = value;
 Example, let name=‘cse’;
 The value assigned to the identifier can be done either at the time of declaration or
later in the code and can also be altered further.
var:
 JavaScript var keyword is used to declare variables that are function-scoped. The
variables declared inside a function are function-scoped and cannot be accessed
outside the function.
 The variables declared with var can only be accessed inside that function and its
enclosing function.
 The variables declared using the var statement are hoisted at the top and are initialized
before the execution of code with a default value of undefined.
Syntax: var variableName = value;
Example, var name=“sacet”;
const:
 The identifier to hold data that does not vary is called 'Constant' and to declare a
constant, 'const' keyword is used, followed by an identifier. The value is initialized
during the declaration itself and cannot be altered later.
 The identifiers declared using 'const' keyword have block scope i.e., they exist only in
the block of code within which they are defined.
Syntax: const const_name = value;
Example. const pi = 3.14;
console.log("The value of Pi is: "+pi);
9. WORKING WITH DATA TYPES
 Data type mentions the type of value assigned to a variable. In JavaScript, the type is
not defined during variable declaration. Instead, it is determined at run-time based on
the value it is initialized with.
 JavaScript is a dynamically typed or loosely typed scripting language. In JavaScript,
variables can receive different data types over time.
 To be able to proceed with the manipulation of the data assigned to the variables, it is
mandatory for a programming language to know the type of value or the type of data
that the variable holds. JavaScript provides different data types to hold different types
of values.
JavaScript defines the following data types:

 There are two types of data types in JavaScript.


i. Primitive data types
ii.Non-primitive (reference) data types
i) Primitive Data Types:
 The predefined data types provided by JavaScript language are known as primitive
data types. Primitive data types are also known as in-built data types. The data is said
to be primitive if it contains an individual value. JavaScript has five primitive types:
Number, String, Boolean, Undefined, and Null.
Number :
 To store a variable that holds a numeric value, the primitive data type number is
used. In almost all the programming languages a number data type gets classified as
shown below:
 But in JavaScript. the data type number is assigned to the values of type integer, long,
float, and double. For example, the variable with number data type can hold values
such as 300, 20.50, 1001, and 13456.89.
Example:
const pi = 3.14; // its value is 3.14
const smallestNaturalNumber = 0; // its value is 0
let result = “Nine" * 5; //its value is NaN
String :
 When a variable is used to store textual value, a primitive data type string is
used. Thus, the string represents textual values. String values are written in
quotes, either single or double in JavaScript.
Example1:
let personName= “sacet”; //OR
let personName = ‘sacet’; // both will have its value as sacet
 You can use quotes inside a string but that shouldn't match the quotes surrounding the
string. Strings containing single quotes must be enclosed within double quotes and
vice versa.
Example2: let ownership= “Stann's"; (OR) let ownership = 'Stann"s';
 To access any character within the string, it is important to be aware of its position in
the string. The first character exists at index 0, next at index 1, and so on.
Boolean :
 When a variable is used to store a logical value that can always be true or false then,
primitive data type Boolean is used. Thus, Boolean is a data type which represents
only two values: true and false.
 Values such as 100, -5, “cse”, 10<20, 1, 10*20+30, etc. evaluates to true whereas 0,
“”, NaN, undefined, null, etc. evaluates to false.
 Example, let k1 ="true"; let k2 ="false";
Undefined :
 When the variable is used to store "no value", primitive data type undefined is used.
 Any variable that has not been assigned a value has the value undefined and such
variable is of type undefined. The undefined value represents "no value".
Example 1: let custName; // here value and the data type are undefined
 The JavaScript variable can be made empty by assigning the value undefined.
Example 2:
 let custName = “Flag"; //here value is Flag and the data type is String
 custName = undefined; //here value and the data type are undefined
null :
 Null represents no value at all. Null data type is required as JavaScript variable
intended to be assigned with the object at a later point in the program can be assigned
null during the declaration.
Example 1:
let item = null;
 // variable item is intended to be assigned with object later. Hence null is assigned
during variable declaration.
 If required, the JavaScript variable can also be checked if it is pointing to a valid
object or null.
Example 2: document.write(item==null); // returns true
BigInt :
 BigInt is a special numeric type that provides support for integers of random length.
BigInt is a built-in object in JavaScript that provides a way to represent whole
numbers larger than 253-1.
 A BigInt is generated by appending n to the end of an integer literal or by calling the
function. BigInt that generates BigInt from strings, numbers, etc.
Example:
const bigint var = 67423478234689887894747472389477823647n; (OR)
const bigint var = BigInt("67423478234689887894747472389477823647");
Symbol :
 A "symbol" represents a unique identifier. You can make use of Symbol() to generate
a value of this type.
Example1:
let empid = Symbol(); // empid is a new symbol
 Also, a description of the symbol generated can be provided which can be mostly
used as a name during debugging.
Example2:
// empid is a symbol with the description "empno"
let empid = Symbol("empno");
ii) Non-Primitive Data Types:
 The data types that are derived from primitive data types of the JavaScript language
are known as non-primitive data types. It is also known as derived data types or
reference data types.
 The variables in JavaScript may not always hold only individual values which are
with one of the primitive data types.
 There are times a group of values are stored inside a variable. JavaScript gives non-
primitive data types named Object and Array, to implement this.
Object :
 Objects in JavaScript are a collection of properties and are represented in the form of
[key-value pairs].
 The 'key' of a property is a string or a symbol and should be a legal identifier.
 The 'value' of a property can be any JavaScript value like Number, String, Boolean, or
another object.
 JavaScript provides the number of built-in objects as a part of the language and user-
defined JavaScript objects can be created using object literals.
Syntax: Example:
let objectName= { let mySmartPhone = {
key1 : value1, name: "iPhone",
key2 : value2, brand: "Apple",
key3 : value3 platform: "iOS",
---------------- price: 50000
key N : value N };
};

Array :
 The Array object is used to store multiple values in a single variable. An array is a
special variable, which can hold more than one value at a time.
 In most programming languages array elements are of same type, but in JavaScript,
values assigned to an array elements can be different type.
 There are two ways of creating an array:
let dummyArr = new Array(); (OR) let dummyArr = [ ];
Example: let digits =[1,2,3,"four"];
10. OPERATORS AND TYPES OF OPERATORS
 Operators in a programming language are the symbols used to perform operations on
the values. In JavaScript, an operator is a special symbol used to perform operations
on operands. Operators are used in expressions to store or return a value. Operators
can be classified into number of categories. They are as follows:
i) Arithmetic Operators
ii) Comparison Operators
iii) Logical Operators
iv) Assignment Operators
v) Conditional operators or Ternary Operators
vi) Unary Operators or Increment/Decrement Operators
vii) The String Catenation operator
viii) typeof operator
i) Arithmetic Operators
 Arithmetic operators are used to perform arithmetic operations on the operands.
 JavaScript has the typical collection of numeric operators: the binary operators + for
addition, - for subtraction, * for multiplication, / for division, and % for modulus.
 The table below lists the arithmetic operators in JavaScript:

Operator Name Description Example Result

x+y Addition Sum of x and y 2+2 4


x-y Subtraction Difference of x and y 5-2 3
x*y Multiplication Product of x and y 5*2 10
x/y Division Quotient of x and y 15 / 5 3

x%y Modulus Remainder of x divided by y 10%2 0

ii) Comparison Operators:


 Relational operators are used for comparing values and the result of comparison is
always either true or false. The table below lists the relational operators in JavaScript:
Operator Name Description Example

x == y Equal True if x is equal to y 5==8 returns false

x !=y Not equal True if x is not equal to y 5!=8 returns true


True if value and data type are
x===y Strict equality 10===“10” returns false
equal
True if value and data type are
x!==y Strict inequality 10!==“10” returns true
inequal
x <> y Not equal True if x is not equal to y 5<>8 returns true
x >y Greater than True if x is greater than y 5>8 returns false
x<y Less than True if x is less than y 5<8 returns true
Greater than or
x >= y True if x is greater than or equal to y 5>=8 returns false
equal to
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true
iii) Logical Operators
 Logical operators allow a program to make a decision based on multiple
conditions. Each operand is considered a condition that can be evaluated to true or
false. The table below lists the Logical operators in JavaScript:
Operator Name Description Example
x=6,y=3
x && y Logical AND True if both x and y are true
(x < 10 && y > 1) returns true
x=6,y=3
x || y Logical OR True if either or both x and y are true
(x==5 || y==5) returns false
x=6,y=3
!x Logical NOT True if x is not true
!(x==y) returns true

iv) Assignment Operators


 Assignment operators are used to assign the result of an expression to a variable. They
are =, +=, -=, *=, /=, %=
 The table below lists the assignment operators in JavaScript:
Operator Name Example Description

= Assign a=b The value of right operand is assigned to the left


operand.
+= Add then Assign a+=b Addition same as a = a +b
-= Subtract then Assign a-=b Subtraction same as a = a - b
*= Multiply then Assign a*=b Multiplication same as a = a *b
/= Divide then Assign a/=b Find quotient same as a = a / b
(quotient)
%= Divide then Assign ( a%=b Find remainder same as a = a / b
remainder)
v) Conditional Operators:
 JavaScript contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax: variable name = (condition)?value1:value2;
 Example, Max = (a > b) ? a : b;
 The condition is evaluated first. If the condition is true then a value will be return to
the Max. otherwise b value will be return.
vi) Incrementing/Decrementing Operators
 The JavaScript increment and decrement Operators used to increase and decrease the
value by 1. The increment operator ++, adds 1 to the operand and decrement operator-
-, subtracts 1 from the operand.
 The table below lists the increment and decrement Operators in JavaScript:
Operator Name Example Description
++ Increment ++i (pre-increment) Increment the i value by 1, then return i.
i++ (post-increment) Return i, then increment the i value by 1.
-- Decrement - -i (pre-decrement) Decrement the i value by 1, then return i
i- - (post-decrement) Return i, then decrement the i value by 1.
vii) The String Catenation Operator:
 The string operators are used to perform the operation on strings. To add two are more
string variables together, use the + operator.
For example, var1 = “ JavaScript is ”;
var2 = “ a Scripting Language”;
var3 = var1 + var2;
 After execution of the above statements, the variable var3 contains JavaScript is a
Scripting Language.
viii) typeof operator:
 “typeof" is an operator in JavaScript. JavaScript is a loosely typed language i.e., the
type of variable is decided at runtime based on the data assigned to it. This is also
called dynamic data binding.
 As programmers, if required, the typeof operator can be used to find the data type of a
JavaScript variable. The following are the ways in which it can be used and the
corresponding results that it returns.
 Examples,
typeof "JavaScript World" //string
typeof 10.5 // number
typeof 10 > 20 //boolean
typeof undefined //undefined
typeof {itemPrice : 500} //Object
typeof[1,2,3,"four"] //Array

11. WORKING WITH STATEMENTS AND EXPRESSIONS


 Statements are instructions in JavaScript that have to be executed by a web browser.
JavaScript code is made up of a sequence of statements and is executed in the same
order as they are written. A Variable declaration is the simplest example of a
JavaScript statement. Syntax: var firstName = "Newton" ;
 Other types of JavaScript statements include conditions/decision making, loops, etc.
 While writing client-logic in JavaScript, variables and operators are often combined to
do computations. This is achieved by writing expressions.
 Different types of expressions that can be written in JavaScript are:
10 + 30; //Evaluates to numeric value
"Hello" + "World"; //Evaluates to string value
itemRating > 5; //Evaluates to boolean value
Types of Statements:
 In JavaScript, the statements can be classified into two types.
1) Conditional Statements:
2) Non-Conditional Statements:
1) Conditional Statements:
 Conditional statements help you to decide based on certain conditions. These
conditions are specified by a set of conditional statements having boolean expressions
that are evaluated to a boolean value true or false.
Types of Conditional Statements:
 Conditional statements help in performing different actions for different conditions.
The conditional control statements are used to control the flow of execution of
statements in a program.
 Conditional statements are used to decide the flow of execution based on different
conditions. If a condition is true, you can perform one action and if the condition is
false, you can perform another action
 To perform different actions on different decisions, we can use conditional statements
in JavaScript.
 There are various ways to use if statement in JavaScript. In JavaScript, we have use
the following conditional statements:
1) if statement
2) switch statement
1) if statement:
The 'if' statement evaluates the expression given in its parentheses giving a Boolean value as
the result. There are various ways to use if statement in JavaScript:
i) Simple 'if' statement
ii) if -else statement
iii) Nested if-else statement
iii) if … else if statement or else-if ladder statement
i) Simple 'if' statement:
 It is a powerful two way decision making statement and it is used to control the flow
of execution of statements. The 'if' statement is used to execute a block of code if the
given condition evaluates to true. The general form of if statement is
if (condition)
{
// block of code that will be executed, if the condition is true ;
}
For example,
<!DOCTYPE HTML>
<html>
<head>
<title> Example for simple if statement</title>
</head>
<body>
<script type ="text/JavaScript">
let num1 = 12;
if (num1 % 2 == 0) {
document.write("It is an even number");
}
}
</script> </body>
</html> OUTPUT: It is an even number!! Because 12%2 evaluates to true
ii) if… else statement
 It is used to execute some code if a condition is true and another code if the condition
is not true. The 'else' statement is used to execute a block of code if the given
condition evaluates to false. The syntax for if-else statement is given below.
if (condition) {
// block of code that will be executed, if the condition is true
}
else {
// block of code that will be executed, if the condition is false
}
 If the condition is true then block-1 statements are executed. Otherwise block-2
statements are executed. But both are not executed at the same time.
For example, To check whether given number is even or odd
<!DOCTYPE HTML>
<html>
<head>
<script language="javascript">
let num=prompt(“Enter the number”);
if(num%2==0){
document.writeln(“number is even number");
}
else{
document.writeln(“number is odd number");
}
</script> </head>
</html>
iii) Nested if-else statement
When a series of conditions are involved, we can use more than on if-else statement in
nested form.The general form of nested if-else statement is as follows:
if(condition 1)
{
if(condition 2)
{
block-1 Statements;
}
else
{
block-2 Statements;
}
}
else
{
block-3 Statements;
}
 If condition1 is true then second condition is performed. If second condition is true
then statement-1 will be executed.
 If condition2 is false then statement-2 will be executed. If condition1 is false then
statement-3 will be executed and then the control is transferred to the out of the if
statement.
For example, Find the biggest number from the given 3 integer numbers.
<!DOCTYPE HTML>
<html>
<head>
<script language="javascript">
var a=40 ,b=30, c=10;
if(a>b)
{
if(a>c) {
document.writeln ("a is biggest number“);
}
else
{
document.writeln("c is biggest number";
} }
else
{
if(b>c)
{
document.writeln( "b is biggest number“);
}
else
{
document.writeln("c is biggest number“);
}
}
</script>
</head>
</html>
Output: 40 is biggest number
iv) if … else if statement or else-if ladder statement
 JavaScript if-else-if is a special statement used to combine multiple if-else statements.
 It evaluates the code only if condition is true from several expressions. To test
multiple conditions, we have to use else-if ladder. The syntax is as follows:
if(condition1) {
block-1 Statements; // if condition1 is true
}
else if(condition2)
{
block-2 Statements; // if condition2 is true
}
……..
else
{
default block Statements; // if no condition is true
}
For example,
<!DOCTYPE HTML>
<html>
<head><title> Example for if-else-if statement</title>
<script language="javascript">
var a=20, b=30, c=10;
if(a>b && a>c) {
document.write("a is biggest number");
}
else if(b>a && b>c){
document.write("b is biggest number");
}
else if(c>a && c>b){
document.write("c is biggest number");
}
else {
document.write("invalid nubers");
}
</script> </head>
</html>
2) switch statement:
 The switch statement is a multi-way decision maker. The switch statement is used to
select and evaluate one of the many blocks of code.
 It is just like if..else..if statement but it is convenient than if..else..if because it can be
used with numbers, characters etc.
 Use this statement to select one of many blocks of code to be executed. The syntax
for switch statement is as follows;
switch(expression) {
case label-1: block-1 statement(s);
break;
case label-2: block-2 statement(s);
break;
…………
case label-n: block-n statement(s);
break;
default: default- block statement(s);
}
 The switch statement test the value of a variable or expression. The expression is an
integer or character.
 This statement with in the group must be preceded by one or more case labels and
case label end with a colon(:) operator.
 If the expression value is equal to case label-1 then block-1 statements will be
executed. If the expression value is equal to case label-2 then block-2 statements will
be executed.
 If the expression value does not equal to any case label then default block statements
will be executed.
 There is no need to put the braces around these blocks. The break statement is used to
break the particular case and the control is transferred to the out of the switch
statement.
For example,
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script type="text/javascript">
var ch=prompt("Enter the character");
switch(ch)
{
case 'a': document.write("The given character is Vowel");
break;
case 'e': document.writeln("The given character is Vowel");
break;
case 'i': document.writeln("The given character is Vowel");
break;
case 'o': document.writeln("The given character is Vowel");
break;
case 'u': document.writeln("The given character is Vowel");
break;
default: document.writeln("The given character is Consonant");
}
</script>
</body>
</html>
2. Non-Conditional Control Statements
• Non-Conditional statements are those statements that do not need any condition to
control the program execution flow. These are as follows:
i) continue Statement
ii) break Statement
iii) return Statement
i) continue Statement
The continue statement is used within a loop structure to skip the loop iteration and
continue execution at the beginning of condition execution. It is mainly used to skip the
current iteration and check for the next condition.
Syntax: continue;
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script type="text/javascript">
let num;
for (num = 1; num < 10; num++) {
if (num % 2 == 0)
{
continue;
}
document.writeln( num + " ");
}
ii) break Statement
break is used to immediately terminate the loop and the program control resumes at the next
statement following the loop. The break statement is also used to break the particular case
and the control is transferred to the out of the switch statement. Syntax: break;
For example, let seats=2;
for (let i = 1; i<=seats; i++){
if (seats<=2){
document.write('<br>The cost per '+seats+ ' ticket(s) Rs: '+totalcost);
break;
}}
iii) return Statement
The purpose of return statement in JavaScript is to return control of program execution back
to the environment from which it was called.
If return statement occurs inside a function, execution of current function is terminated,
handing over the control back to the environment from which it was called.
Syntaxes: return; return variable; return expression;
For example, function add(a, b){
return(a+b);
}
document.writeln (“Addition:“)+add(10,20);

12. LOOP CONTROL STATEMENTS


 Loops are useful when you have to execute the same lines of code repeatedly, for a
specific number of times or as long as a specific condition is true. The loop control
statements are used to execute a group of statements repetitively. There are three
types of loops in JavaScript.
1. while loop
2. for loop
3. do-while loop
i) while loop
 'while' loop is used when the block of code is to be executed as long as the specified
condition is true. Once the condition gets FALSE, it exits from the body of loop. The
while loop starts with the keyword while.
 The while loop is called an Entry control loop because the condition is checked before
entering the loop body.
 This means that first the condition is checked. If the condition is true, the block of
code will be executed.
 The value for the variable used in the test condition should be updated inside the loop
only. The general form of the while statement is as follows:
while (condition){
statement(s);
iteration variable updation;
}
For example, To check whether given number is Prime number or not .
//A prime number is a positive integer and that is divisible only by itself and 1
<!DOCTYPE HTML>
<html>
<head>
<title> Prime nimber or not</title>
</head>
<body>
<script type="text/javascript">
var i=1,k=0;
var num=prompt("Enter the number");
while(i<=num)
{
if(num%i==0)
k++;
i++;
}
if(k==2)
document.writeln("prime number");
else
document.writeln("not prime number");
</script>
</body>
</html>

ii) for loop


 The for statement is used to execute a group of statements repeatedly based on some
condition. The for loop starts with the keyword for.
 The for loop is also called as entry control loop. The syntax of a for statement is as
follows:
for(initialization; condition; increment/decrement)
{
statement(s);
}
 Initialization - Initialize the loop counter value. The initial value of the for loop is
done only once.
 condition - Evaluate each iteration value. The loop continuously executes until the
condition is false. If TRUE, the loop execution continues, otherwise the execution of
the loop ends. But condition is only one condition.
 Increment/decrement - It increments or decrements the value of the variable.
For example, to find the factorial of a given number
<!DOCTYPE HTML>
<html>
<head>
<title> Factorial of a given number</title>
</head>
<body>
<script type="text/javascript">
var i, num, fact = 1;
var num=prompt("Enter the number");
for(i=1; i< = num; i++)
fact*=i;
alert("FACT is: " + fact + "\n");
</script>
</body>
</html>
ii) do-while loop
 The do-while statement is related to the while statement, but the test for completion is
logically at the end rather than the beginning of the loop construct.
 The body of a do-while construct is always executed at least once. The do-while loop
is also called as exit control loop.
 The value for the variable used in the test condition should be updated inside the loop
only. The syntax of a do-while statement is as follows:
do
{
statement(s);
}while(condition);
For example, to print the sum of n natural numbers (1+ 2 + 3 ….)
<!DOCTYPE HTML>
<html>
<head>
<title> sum of n natural numbers</title>
</head>
<body>
<script type="text/javascript">
var i=1,sum=0;
var num=prompt("Enter the range");
do {
sum+=i;
i++;
}while(num>=i);
document.writeln("SUM is: "+sum);
</script>
</body>
</html>

13. FUNCTIONS
 A function is self contained block of code that performs specified task. JavaScript
functions are used to perform operations. We can call JavaScript function many times
to reuse the code.
 Functions are used to reduce the length of the program. JavaScript has two types of
functions.
1. Built-in functions or Library Functions
2. User defined Functions
1. Built-in functions : JavaScript provides several predefined functions that perform tasks
such as displaying dialog boxes, parsing a string argument, timing-related operations, and so
on.
 Examples, concat(), length(), toLowerCase(), valueOf(), join(), pop(), push(),
reverse(),sort(), Date(), abs(), max() etc.,
2. User defined functions:- JavaScript allows to write own functions called as user-defined
functions. The user-defined functions can also be created using a much simpler syntax
called arrow functions.
 A user defined function first needs to be declared and coded, then it can be called by
using the name given to the function when it was declared. The function name can
start with a letter or underscore (not a number or special symbol)
Declaring and Invoking Function:
 To use a function, it must be defined or declared and then it can be invoked anywhere
in the program.
 A function declaration also called a function definition, consists of the function
keyword, followed by:Function name
 A list of parameters to the function separated by commas and enclosed in parentheses,
if any.
 A set of JavaScript statements that define the function, also called a function body,
enclosed in curly brackets {…}.Syntax for Function Declaration:
function function_name(parameter 1, parameter 2 , …, parameter n) {
// statements to be executed
}
Example: function multiply(num1, num2) {
return num1 * num2;
}
 The code written inside the function body will be executed only when it is invoked or
called. Syntax for Function Invocation:
function_name(argument 1, argument 2, ..., argument n);
For example, multiply (5,6);
 Functions can be declared anywhere in the HTML file. We can define functions in
various types like with parameters, without parameters, return or without return
statement like C, C++, Java.
 If the number of parameters is more than the number of arguments, then the
parameters that have no corresponding arguments are set to undefined.
Example, function multiply(num1, num2) {
if (num2 == undefined) {
num2 = 1;
}
return num1 * num2;
}
document.write(multiply(5, 6)); // output: 30
document.write(multiply(5)); // output: 5
Rest parameter:
It allows to hold an indefinite number of arguments in the form of an array.
Syntax: function function_name(a1,a2,---an, …args) {
statement(s);
}
 The rest of the parameters can be included in the function definition by using three
dots ( … ) followed by the name of the array that will hold them.
Example:
function showNumbers(x, y, …z) {
return z;
}
document.write(showNumbers(1, 2, 3, 4, 5)); // output: [3,4,5]
console.log(showNumbers(3, 4, 5, 6, 7, 8, 9, 10)); //output: [5,6,7,8,9,10]
 The rest parameter should always be the last parameter in the function definition.
Write a program to check whether given number is perfect number or not using
functions in JavaScript.
 // A perfect number is a positive number that is equal to sum of its positive divisors ,
excluding number itself.
<!DOCTYPE HTML>
<html>
<head>
<title> Perfect Number Program</title>
</head>
<body>
<script type="text/javascript">
function perfect(num)
{
var i, s=0;
for(i=1;i<num;i++)
{
if(num%i==0)
{
s+=i;
}
}
if(s==num)

document.write("Perfect Number is"+" "+s);


else
document.write("Not Perfect Number");
}
</script>
<form name="form1" onsubmit="perfect(form1.text1.value)">
enter number:
<input type="text" name="text1">
<input type="submit" value="submit">
</form>
</body>
</html>
CONSTRUCTORS:
 A JavaScript constructor function is a special type of function which is used to
initialize and create an object. It is called when memory is allocated for an object.
 Constructors are like regular functions, but we use them with the new keyword. When
the constructor is called, this is a reference to the newly created object.
Example,
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<script type="text/javascript"> ;
function employ(id,name,job,salary){
this.id=id;
this.name=name;
this.job=job;
this.salary=salary;
}
var ob1=new employ("sacet180", "James","SOFTWARE",70000);
document.write(ob1.id+"<br>"+ob1.name+"<br>"+ob1.job+“<br>“+
ob1.salary);
</script>
</body>
</html>
constructor() function:
 constructor() is an ECMAScript6 (ES6) feature. The constructor() method is a special
method for creating and initializing objects created within a class.
 The constructor() method is called automatically when a class is initiated, and it has to
have the exact name "constructor“.
 A class cannot have more than one constructor() method. This will throw
a SyntaxError. You can use the super() method to call the constructor of a parent
class.
Example,
<!DOCTYPE html>
<html>
<head>
<title> Employee Details</title>
</head>
<body>
<script type="text/javascript">
class Person
{
constructor(name, age) // Constructor
{
this.name = name;
this.age = age;
}
}
class Employee extends Person
{
constructor(name, age, job,salary,role)
{
super(name, age);
this.job=job;
this.salary=salary;
this.role = role;
}
getEmployeeDetails()
{
document.write("*** EMPLOYEE DETAILS ***");
document.write(" <br> Name : "+this.name);
document.write(" <br> Age :",this.age);
document.write("<br> Job : ",this.job);
document.write("<br> Salary : ",this.salary);
document.write("<br> Role : ",this.role);
}
}
let employee1 = new Employee("Karth", 25,"Software",100000, “Developer”);
employee1.getEmployeeDetails();
</script>
</body>
</html>
Arrow Function:
 Arrow function is one of the features introduced in the ES6 version of
JavaScript. Arrow function ()=> is concise way of writing JavaScript functions in
shorter way. They make our code more structured and readable.
 Arrow functions are anonymous functions i.e. functions without a name but they are
often assigned to any variable. They are also called Lambda Functions.
Syntax: let myFunction = (arg1, arg2, ...argN) => {
statement(s);
}
 There are two parts for the Arrow function syntax:
1. let sayHello = (arg1, arg2, ...argN)
 This declares a variable sayHello and assigns a function to it using () to just say that
the variable is a function.
2. => {
statement(s)
}
 This declares the body of the function with an arrow and the curly braces.
Example: Arrow Function without Parameters
let sayHello = ( ) => {
document.write("Welcome to JavaScript");
}
sayHello( );
Arrow Function with Parameters:
calculateCost = (ticketPrice, noOfPerson)=>{
noOfPerson= ticketPrice * noOfPerson;
return noOfPerson;
}
document.write(calculateCost(500, 2)); Output:1000
Arrow Function with Default Parameters:
calculateCost = (ticketPrice, noOfPerson=2)=>{
noOfPerson= ticketPrice * noOfPerson;
return noOfPerson;
}
document.write(calculateCost(500));
 If the body has single statement or expression, you can write arrow function as: let
myFunction = (arg1, arg2, ...argN) => expression
Example, let k = (x, y) => x * y;
Advantages of Arrow Functions:
 Arrow functions reduce the size of the code.
 The return statement and function brackets are optional for single-line functions. It
increases the readability of the code.
 Arrow functions provide a lexical this binding. It means, they inherit the value of
“this” from the enclosing scope.
Nested Function:
 In JavaScript, the function within another function body is called a nested function.
The nested function is private to the container function and cannot be invoked from
outside the container function.
Example: function giveMessage(message) {
let userMsg = message;
function toUser(userName) {
let name = userName;
let greet = userMsg + " " + name;
return greet;
}
userMsg = toUser(“sacet");
return userMsg;
} document.write(giveMessage("The world says hello : "));

14. WORKING WITH CLASSES


 In 2015, JavaScript introduced the concept of the Class.
 Classes and Objects in JavaScript coding can be created similar to any other Object-
Oriented language.
 Classes can also have methods performing different logic using the class properties
respectively.
 The new feature like Class and Inheritance eases the development and work with
Classes in the application.
 JavaScript is an object-based language based on prototypes and allows to create
hierarchies of objects and to have inheritance of properties and their values.
14.1 CREATING AND INHERITING CLASSES:
Creating Classes:
 In 2015, ECMAScript introduced the concept of classes to JavaScript The
keyword class is used to create a class .The constructor method is called each time the
class object is created and initialized.
Syntax: class class_name {
statements;
}
 The Objects are a real-time representation of any entity. Different methods are used to
communicate between various objects, to perform various operations.
Example, To demonstrates a calculator accepting two numbers to do addition and subtraction
operations.
class Calculator {
constructor(num1,num2){ // Constructor used for initializing the class instance
this.num1 = num1; // Properties initialized in the constructor
this.num2 = num2;
}
add() { // Methods of the class used for performing operations
return this.num1 + this.num2;
}
subtract() {
return this.num1 - this.num2;
}
}
let calc = new Calculator(300, 100); // Creating Calculator class object
console.log("Add method returns" + calc.add()); // Add method returns400.
console.log("Subtract method returns" + calc.subtract()); // Subtract method returns 200.
Static methods:
Static methods can be created in JavaScript using the static keyword like in other
programming languages. Static values can be accessed only using the class name and not
using 'this' keyword. Else it will lead to an error.
Example for Static Methods : In the below example, display() is a static method and it is
accessed using the class name.
class Calculator {
constructor(num1, num2) { // Constructor used for initializing the class instance
this.num1 = num1; // Properties initialized in the constructor
this.num2 = num2;
}
static display() { /* static method */
console.log("This is a calculator app");
}
/* Methods of the class used for performing operations */
add() {
return this.num1 + this.num2;
}
subtract() {
return this.num1 - this.num2;
}
}
let calc=new Calculator(5,4);
console.log("Add method returns" + calc.add()); // Add method returns 400.
console.log("Subtract method returns" + calc.subtract());
// Subtract method returns 200.
/*static method display() is invoked using class name directly. */
Calculator.display(); The output of the static method is : This is a calculator app
Inheritance Classes:
 In JavaScript, one class can inherit another class using the extends keyword. The
subclass inherits all the methods ( both static and non-static ) of the parent class.
 Inheritance enables the reusability and extensibility of a given class.
 JavaScript uses prototypal inheritance which is quite complex and unreadable. But,
now you have 'extends' keyword which makes it easy to inherit the existing classes.
 Keyword super can be used to refer to base class methods/constructors from a
subclass. By calling the super()method in the constructor method, we call the parent's
constructor method and gets access to the parent's properties and methods.
Example for concept of Inheritance concept.
<!DOCTYPE html>
<html>
<head> <title>Classes Demo</title>
<script>
class Vehicle {
/* Base class Vehicle with constructor initializing two-member attributes */
constructor(make, model) {
this.make = make;
this.model = model;
}
}
class Car extends Vehicle {
constructor(make, model, regNo, fuelType) {
super(make, model); // Sub class calling Base class Constructor
this.regNo = regNo;
this.fuelType = fuelType;
}
getDetails() { // Template literals used for displaying details of Car.
console.log(`${this.make},${this.model},${this.regNo},${this.fuelType}`);
}
}
// Creating a Car object
let c1 = new Car("Hundai", "i20", “AP-02999", "Petrol");
c1.getDetails();
</script>
</head>
</html>

15. ARRAYS
 The Array object is used to store multiple values in a single variable. An array is a
special variable, which can hold more than one value at a time.
 Arrays are represented in JavaScript by array object. Each piece of data contained in
an array is called an element.
 In most programming languages array elements are of same type, but in JavaScript,
values assigned to an array elements can be different type.
Creating Arrays:
 Arrays can be created using the literal notation or array constructor.
 The “new” operator is used to declare and allocate memory for one dimensional
array. Operator new is also known as dynamic memory allocation operator.
 There are 3 ways to construct a one dimensional array in JavaScript. They are as
follows:
1. Creating an Array using Array Literal
2 .Creating an instance of Array directly (using new keyword)
3. Creating an Array using Array Constructor (using new Keyword)

1. Creating an Array using Array Literal


 Creating an array using array literal involves using square brackets [] to define and
initialize the array. This method is concise and widely preferred for its simplicity. The
syntax of creating array using array literal is,
var arrayname=[value1,value2.....valueN];
For example,
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
var emp=["SMITH",90000,“SOFTWARE"];
for (i=0;i<emp.length;i++) // length property returns the length of an array.
{
document.writeln(emp[i]+"<br>");
}
</script>
</body></html>
2. Creating an instance of Array directly (using new keyword)
 The new keyword is used to create instance of array. The syntax of creating array
using new operator is as follows:
var arrayname=new Array();
Accessing an Array:
 Array elements can be accessed using indexes. The first element of an array is at
index 0 and the last element is at the index equal to the number of array elements – 1.
Using an invalid index value returns undefined.
For example,
<!DOCTYPE html>
<html>
<head>
<title>7 days</title>
</head>
<body bgcolor="pink">
<center>
<br><br>
<pre>
<script language="javascript">
var days=new Array();
days[0]="sunday";
days[1]="monday";
days[2]="tuesday";
days[3]="wednsday";
days[4]="thursday";
days[5]="fridayy";
days[6]="saturday";
document.writeln(days[0]);
document.writeln(days[1]);
document.writeln(days[2]);
document.writeln(days[3]);
document.writeln(days[4]);
document.writeln(days[5]);
document.writeln(days[6]);
</script>
</pre></center></body></html>
3. Creating an Array using Array Constructor (new Keyword)
 The “Array Constructor” refers to a method of creating arrays by invoking the Array
constructor function. You need to create instance of array by passing arguments in
constructor so that we don't have to provide value explicitly.
 The syntax for creating an object by array constructor is as follows:
var arrayname = new Array( value 1, value 2, …… value N);
For example,
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
var emp=new Array(“James",90000,“SOFTWARE");
for (i=0;i<emp.length;i++){
document.write(emp[i]+"<br>");
}
</script></body></html>

Multi-dimensional or Two-dimensional Arrays:


 JavaScript does not provide the multidimensional array directly. A two-dimensional
array is implemented in JavaScript as an array of arrays. This can be done with the
new operator or with nested array literal.
// Create an array object with 3 arrays as its elements using nested array literal.
<!DOCTYPE html>
<html>
<head></head>
<body>
<script language=”javascript”>
var nested_array = [ [2, 3, 4], [ 1,5, 6 ], [ 7, 8, 9] ];
for( var row = 0; row<3; row++)
{
for(var col = 0; col<3; col++)
document.writeln(nested_array[row][col] + “ “);
document.write(“<br>”);
}
</script>
</body></html>

Properties of Array Object:


constructor --- Specifies the function that creates an object's prototype.
length --- Use to get the length of a string object.
prototype --- Use to add new properties and methods to an object
Array Methods:
concat() --- Joins two or more arrays and returns a copy of the joined arrays.
join() --- Joins all elements of an array into a string.
reverse() --- Reverses the order of the elements in an array.
sort() --- Sorts the elements of an array.
pop() -- Removes the last element of an array and returns that element.
push() --- Adds new elements to the end of an array, and returns the new length.
shift() --- Removes the first element of an array and returns that element.
unshift() --- Adds new elements to the beginning of an array, and returns the new length.
slice() --- Selects a part of an array and returns new array.
splice() --- Adds/Removes elements form an array.
toString() --- Converts an array to a string and returns the result.
valueOf() --- Returns the primitive value of an array.

For example,
<!DOCTYPE html>
<html>
<head>
<title> Example for Array Methods</title>
</head>
<body bgcolor=“pink”>
<script type="text/javascript">
var parents=[“Jan",“Kark" ];
var children=[“James",“Tarki"];
var family=parents.concat(children);
document.write(family + "<br>");
var fruits= new Array("banana","apple","grape");
document.write(fruits.slice(1,3) + "<br>");
document.write(fruits.join() + "<br>");
document.write(fruits.sort() + "<br>");
document.write(fruits.reverse() + "<br>");
document.write(fruits.shift() + "<br>");
var colors= new Array("green","blue","yellow");
document.write(colors.pop() + "<br>");
document.write(colors.push( "red") + "<br>");
</script>
</body>
</html>

16. WORKING WITH OBJECTS


 JavaScript is designed on a simple object-based paradigm. An object is a collection
of properties and functions. Objects in JavaScript, just as in many other programming
languages, can be compared to objects in real life. In JavaScript, an object is a
standalone entity, with properties and type.
 For instance, to create an online portal for the car industry, Car as an entity must be
modeled so that it can hold a group of properties.
 Such type of variable in JavaScript is called an Object. An object consists of state and
behavior.
 The State of an entity represents properties that can be modeled as key-value pairs.
 The Behavior of an entity represents the observable effect of an operation performed
on it and is modeled using functions.
Types of Objects: JavaScript objects are categorized as follows:

Creating Objects in JavaScript:


 In JavaScript objects, the state and behaviour is represented as a collection of
properties. Each property is a [key-value] pair where the key is a string and the value
can be any JavaScript primitive type value, an object, or even a function.
There are 3 ways to create objects in JavaScript.
1. Creating object using object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. Creating an Object using object literal
 Objects can be created using object literal notation. Object literal notation is a
comma-separated list of name-value pairs wrapped inside curly braces. The syntax of
creating a object using object literal is as follows:
objectName={ property1:value1,property2:value2....propertyN:valueN };
Example,
<!DOCTYPE html>
<html>
<head>
<title>Creating Objects</title>
</head>
<body>
<script>
let emp={id:102,name:"Shyam Kumar",job:"Software",salary:90000};
//to access the properties or methods using dot (or) bracket operators
document.write(emp.id+"<br> "+emp['name']+"<br> "+emp.job+"<br>" + emp.salary);
</script></body>
</html>
2. Creating an instance of object directly (using new keyword)
 The syntax for creating an instance of Object using new keyword is
let objectName = new Object();
objName.property1 = value1;
………….
For example,
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
let emp=new Object(); //built-in constructor
emp.id=101; // access the properties of an object
emp.name="Karth";
emp.job="Software";
emp.salary=100000;
document.writeln(emp.id+"<br>"+ emp.name+"<br>"+ emp.job+"<br>" +emp.salary);
</script>
</body></html>
3. Creating object with a constructor
 Constructor is a special function. Object constructor helps you create an object type
which can be reused to meet the need of individual instance. Each argument value can
be assigned in the current object by using this keyword. The this keyword refers to
the current object.
Syntax: let objectName = new constructorName( val1, val2, …. valN);
Example,
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function employ(id,name,job,salary){
this.id=id;
this.name=name;
this.job=job;
this.salary=salary;
}
var emp1=new employ("180", “Karth","Software",100000);
document.write(emp1.id+"<br>"+emp1.name+"<br>"+emp1.job+" <br>"+emp1.salary);
</script> </body></html>
 Earlier in JavaScript to add a dynamic property to an existing object, below
syntax was used.
let personalDetails = {name: "Stian Kirkeberg“,country: "Norway”};
let dynamicProperty = "age";
personalDetails[dynamicProperty] = 45;
console.log(personalDetails.age); //Output: 45
 With newer updates in JavaScript after 2015 the dynamic properties can be
conveniently added using hash notation and the values are computed to form a
key-value pair.
let dynamicProperty = "age";
let personalDetails = {
name: "Stian Kirkeberg",
country: "Norway",
[dynamicProperty]: 45
};
console.log(personalDetails.age); //Output: 45

16.1 Built-in Global Objects in Java Script :


 An object is a collection of variables and functions(methods).Syntax: object.method();
 A JavaScript object is an entity having state and behavior (properties and methods).
 They are different built-in objects in JavaScript.
Name of the Purpose of the Object
Object

Math Used for mathematical functions and standard constants in mathematics


String String manipulation can be done and also include to generate HTML
Date For date manipulations, mainly to get current date and time
Number To get number constants
Boolean Wrapper class for Boolean type

Math Object:
 The JavaScript math object provides several constants and methods to perform
mathematical operation.
Methods in Math Object:-
Method Meaning Example

Math.abs(x) Returns the absolute value Math.abs(-20) is 20


Math.ceil(x) Returns the ceil value Math.ceil(5.8) is 6
Math.ceil(2.2) is 3
Math.floor(x) Returns the floor value Math.floor(5.8) is 5
Math.floor(2.2) is 2
Math.round(x) Returns the round value, nearest Math.round(5.8) is 6
integer value Math.round(2.2) is 2
Math.trunc(x) Removes the decimal places it returns Math.trunc(5.8) is 5
only integer value Math.trunc(2.2) is 2
Math.max(x,y) Returns the maximum value Math.max(2,3) is 3
Math.max(5,2) is 5
Math.min(x,y) Returns the minimum value Math.min(2,3) is 2
Math.min(5,2) is 2
Math.abs(x) Returns the absolute value Math.abs(-20) is 20
Math.ceil(x) Returns the ceil value Math.ceil(5.8) is 6
Math.ceil(2.2) is 3
Math.floor(x) Returns the floor value Math.floor(5.8) is 5
Math.floor(2.2) is 2
Math.round(x) Returns the round value, nearest Math.round(5.8) is 6
integer value Math.round(2.2) is 2
Math.trunc(x) Removes the decimal places it returns Math.trunc(5.8) is 5
only integer value Math.trunc(2.2) is 2
Math.max(x,y) Returns the maximum value Math.max(2,3) is 3
Math.max(5,2) is 5
Math.min(x,y) Returns the minimum value Math.min(2,3) is 2
Math.min(5,2) is 2

Properties in Math Object:


LNIO  natural logorithm of 10 (roughly 2.302)
LN2  natural logorithm of 2 (roughly 0.693)
PI  ratio of circumference of a circle to diameter (roughly 3.1415)
For example, Write a program to explain Math object of JavaScript
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript"> //Properties
document.write(Math.E + "<br />");
document.write(Math.LN10 + "<br />");
document.write(Math.LN2 + "<br />");
document.write(Math.PI + "<br />");
document.write(Math.abs(-987) + "<br />"); //Methods
document.write(Math.round(0.40) + "<br />");
document.write(Math.ceil(0.60) + "<br />");
document.write(Math.floor(0.60) + "<br />");
//return a random number between 0 and 1
document.write(Math.random() + "<br />");
document.write(Math.cos(Math.PI) + "<br />");
document.write(Math.sin(Math.PI/2) + "<br />");
document.write(Math.tan(0) + "<br />");
document.write(Math.sqrt(9) + "<br />");
document.write(Math.pow(2,3) + "<br />");
</script></body></html>
String Object:
 A String is a collection of characters, these characters may be including any kind of
special characters, digits, normal characters and other characters. Strings may be
written with help of single quotation or double quotation marks.
 Methods in String Object:
Method Meaning Example
toLowerCase() It converts the given string var s=”SACET”
into lowercase s.toLowerCase()
output: sacet
toUpperCase() It converts the given string var s=”sacet”
into upper case s.toLowerCase()
output: SACET
substring(n) It returns starting of n th var s=”sacet”
position s.substring(3)
ouput: et
split(string) It specifies the split string var s=”sac,et”
from the given string s.split(‘,’)
output: sac, et
substring(m,n) It returns starting from mth var s=” sacet”
character up to nth s.substring(0,3)
character, not include nth ouput: sac
character
substr(m,n) It return starting from mth var s=” sacet”
character upto n characters s.substr(1,3)
ouput: ace
charAt(index) It gives the ith character of var s=”sacet”
string s.charAt(2)
output: c
charCodeAt(index) It returns ASCII value of var s=”teamwork”
the character present at the s.charCodeAt(2)
given index output:97
contact(string) It returns concatenation of var s1=”sac”
s1and s2. Java script var s2=”et”
strings can be s1.concat(s2)
concatenated using ‘+’ output:sacet
operator
Example, Write a program to explain String object of JavaScript
<!DOCTYPE HTML>
<html>
<head>
<title>String Methods</title>
</head>
<body bgcolor="pink">
<pre>
<script language="javascript">
string1="Welcome to SACET";
string2="Students";
document.writeln("Length of string1 is :"+string1.length);
document.writeln(string2.charAt(0));
document.writeln(string1.split(" "));
document.writeln(string1.toLowerCase());
document.writeln(string1.toUpperCase());
document.writeln(string1.italics());
document.writeln(string1.fontsize(10));
document.writeln(string1.bold());
</script></pre></body></html>

Date Object:
 This object is used to manipulate the dates and times. JavaScript includes a well-
defined Date class which provides methods to perform many different manipulations.
The dates and times represent the number of milliseconds.
 Java script date object provides several methods, they can be classified is string form,
get methods and set methods. All these methods are provided in the following .
 To create an instance (object) of data object we use ‘new’ keyword.
Example : var date=new date(<parameter>);
Method Meaning

getDate() Returns 1 to 31 ,day of the month


getDay() Returns 0 to 6, Sunday to Saturday respectively.
getMonth() Returns 0 to 11, jan to dec respectively.
getFullYear() Returns four-digit year number
getHours() Returns 0 to 23
get Minitues() Returns 0 to 59
getSeconds() Returns 0 to 59
setDate() Set the date value
setDay() Set the value of day
setMonth() Set the value of month
setHours()
setMinutes()
To set the hours, minutes, seconds ,and time
setSeconds()
setTime()
For example, Write a program to explain Date object of JavaScript
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var d=new Date(); //displaying today's date
document.write(d+ "<br />");
document.write(d.getDate()+ "<br />");
document.write(d.getDay()+ "<br />");
d.setDate(7);
document.write(d+ "<br />");
document.write(d.getDate()+ "<br />");
document.write(d.getHours()+ "<br />");
d.setHours(20);
document.write(d+ "<br />");
document.write(d.getTime()+ "<br />");
</script></body></html>
Boolean Object:
It is an object wrapper for a Boolean value and constructed with Boolean (value)
constructor. We can get an instance for Boolean by “new” operator as shown below.
var myboolean = new Boolean();
Properties:
constructor:- Returns the function that created the Boolean objects prototype.
Prototype :- Allows use to add properties and methods to an object.
Methods :
1. toString() :- converts a Boolean value to a string and returns the result.
2. valueOf():- Returns primitive value of Boolean object.
 While creating Boolean object with the Boolean() constructor, if there is no initial
value or if it is 0, -0, null, false, NaN undefined or the empty string (“ “), the initial value
is “false”. Otherwise even the string “false” it is “true”.
<!DOCTYPE HTML>
<html><head>></head>
<body>
<script language="javascript">
var bol1=new Boolean(0);
var bol2=new Boolean(5);
var bol3=new Boolean(1);
var bol4=new Boolean(" ");
var bol5=new Boolean("Hello");
var bol6=new Boolean('False');
var bol7=new Boolean(null);
var bol8=new Boolean(NaN);
document.write("0 value is boolean "+bol1+"<br>");
document.write("5 value is boolean "+bol2+"<br>");
document.write("1 value is boolean "+bol3+"<br>");
document.write("An empty is boolean "+bol4+"<br>");
document.write("String \"Hello\" is boolean "+bol5+"<br>");
document.write("String 'False'is boolean "+bol6+"<br>");
document.write("null is boolean "+bol7+"<br>");
document.write("NaN is boolean "+bol8+);
</script></body></html>

Number Object:
Object wrapper in JavaScript is number object, for any number data type, this act as
wrapper class. Same methods are applied for number object also. Constructor is as
follows: var n=new number (any value);
Properties:
The following table lists all the properties of Number type.

Methods of Number object: The following table lists all the methods of Number type

For example,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
<title>Number Object</title> </head>
<body>
<script language="javascript">
document.writeln("....Number properties....."+"<br>");
document.writeln(Number.MAX_VALUE+"<br>");
document.writeln(Number.MIN_VALUE+"<br>"); var x=123;
//toString() converts a number to string document.writeln("....toString()....."+"<br>");
document.writeln(x.toString()+"<br>");
</script> </body> </html>
17. INTRODUCTION TO MODULAR PROGRAMMING
 Modules are one of the most important features of any programming language.
Modules help in state and global namespace isolation and enable reusability and better
maintainability.
 We need modules in order to effectively reuse, maintain, separate, and encapsulate
internal behavior from external behavior.
 Each module is a JavaScript file.
 Modules are always by default in strict-mode code. That is the scope of the members
(functions, variables, etc.) which reside inside a module is always local.
 The functions or variables defined in a module are not visible outside unless they are
explicitly exported.
 The developer can create a module and export only those values which are required to
be accessed by other parts of the application.
 Modules are declarative in nature:
 The keyword "export" is used to export any variable/method/object from a module.
The keyword "import" is used to consume the exported variables in a different
module.
CREATING AND CONSUMING MODULES:
Creating Modules:
 The export keyword is used to export some selected entities such as functions,
objects, classes, or primitive values from the module so that they can be used by other
modules using import statements.
 There are two types of exports:
1. Named Exports (More exports per module)
2. Default Exports (One export per module)
1. Named exports are recognized by their names. You can include any number of named
exports in a module. There are two ways to export entities from a module.
i. Export individual features
ii. Export List
i. Export individual features
Syntax: export let name1, name2, …, nameN; // also var, const
export let name1 = Val1, name2 = Val2, …, nameN=valN;
export function functionName(){...}
export class ClassName {...}
Example:
export let var1,var2;
export function myFunction() { ... };
ii. Export List
Syntax: export { name1, name2, …, nameN };
Example: export { myFunction, var1, var2 };
2. Default Exports
 The most common and highly used entity is exported as default. You can use only one
default export in a single file. Syntax: export default entityname;
 where entities may be any of the JavaScript entities like classes, functions, variables,
etc.
Example: export default function () { ... }
export default class { .. }
 You may have both default and named exports in a single module.

Consuming Modules(How to import Named Exports ):


 If you want to utilize an exported member of a module, use the import keyword. You
can use many numbers of import statements.
Syntax:
// import multiple exports from module
import {entity1, entity 2... entity N} from modulename;
// import an entire module's contents
import * as variablename from modulename;
// import an export with more convenient alias
import {oldentityname as newentityname } from modulename;
Example: import {var1,var2} from './mymodule.js';
import * as myModule from './mymodule.js';
import {myFunction as func} from './mymodule.js';
How to import Default Exports?
 You can import a default export with any name. Syntax: import variablename from
modulename;
Example: import myDefault from './mymodule.js';
Example: Program for Modular Programming
 Implement the following requirements to understand the concept of Modular
Programming.
1. Create an application folder called "Default_Export_Import2" and then follow these steps.
2. Create a file "course1.js":
export let courseName = "Angular";
let course = {getCourseName:function(){ return courseName;},
setCourseName:function(newCourseName){ courseName = newCourseName; }
}; export default course;
3. Create a file "course2.js". This file utilizes the entities defined in the course1.js file.
import crs, {courseName} from "./course1.js";
console.log(courseName);
console.log(crs.getCourseName());
crs.setCourseName("ES6");
console.log(crs.getCourseName()); //Here "crs" is the default export.
4. Create a file “index.html” in VS COSE:
<!DOCTYPE html>
<html>
<head>
<title>Example</title></head>
<body>
<script type="module" src="./course2.js"></script>
</body>
</html>
 Here <script type="module"> at LineNo 9 indicates that the browser must consider a
script as a module. In the above mentioned index.html file we have loaded
course2.js module.
5. Open the index.html page in VS CODE.
ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA
(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
FAQs (UNIT-1)
Subject : MEAN STACK DEVELOPMENT Year/Sem: III B.Tech – II Sem
Academic Year: 2024-25 Regulation : R-22

1. Define Conditional statements. List and Explain the various Conditional Statements in
JavaScript with their syntax and examples.
2. a) Define an operator. Discuss about various Operators in JavaScript with examples
b) Explain about the Inheritance concept in JavaScript with example program.
3. a) Write a JavaScript that reads an integer and determines whether it is PRIME
Number or Not.
b) Describe the primitive data types that Java script uses.
4. a) Define JavaScript. Explain Identifiers and their types with an example.
b) Write a JavaScript code for displaying largest of 3 numbers. Input need to be taken from
user.
5.a) Discuss about Creating and Inheriting Classes with an example.
b) Elaborate on primitive and non-primitive data types of JavaScript.
6.a) How to create a function in JavaScript? Illustrate parameter passing mechanism?
b) Write a program to check whether given number is perfect number or not using functions
in JavaScript.
7.Define Loop. List and Explain various types of Loops with their syntax and Examples
8.a) What is Class in JavaScript? Demonstrate the syntax and example of Class in JavaScript.
b) Define Array in JavaScript? How to create and access the Arrays? Illustrate.
9. Discuss the role of JavaScript in client-side web development. How does it enhance user
Interaction and interface on web page?
10.a) What is Modular Programming? Discuss about creating and consuming modules in
JavaScript with example program?
b) What are the types of Objects in JavaScript? Explain about creation of Objects in JS
with examples.
11. What are the built-in Objects in JavaScript? Explain about them with example.
12. Implement the following functions: i) Function Celsius returns the Celsius equivalent of a
Fahrenheit temperature, C = 5.0 / 9.0 * ( F - 32 ); ii) Function Fahrenheit returns the
Fahrenheit equivalent of a Celsius temperature, F = 9.0 / 5.0 * C + 32; iii) Use these
functions to write a script that enables the user to enter either a Fahrenheit or a Celsius
temperature and displays the Celsius or Fahrenheit equivalent. Your HTML5 document
should contain two buttons—one to initiate the conversion from Fahrenheit to Celsius and
one to initiate the conversion from Celsius to Fahrenheit.

You might also like