Unit 4 Java Script
Unit 4 Java Script
JavaScript
Overview of JavaScript
JavaScript is a lightweight, cross-platform, and interpreted compiled programming language
which is also known as the scripting language for webpages. Its syntax is based on the Java
and C languages — many structures from those languages apply to JavaScript as well.
JavaScript can be used for Client-side developments as well as Server-side developments.
Javascript is both imperative and declarative type of language. JavaScript contains a standard
library of objects, like Array, Date, and Math, and a core set of language elements
like operators, control structures, and statements.
● Client-side: It supplies objects to control a browser and its Document Object Model
(DOM). Like if client-side extensions allow an application to place elements on an HTML
form and respond to user events such as mouse clicks, form input, and page navigation.
● Server-side: It supplies objects relevant to running JavaScript on a server. Like if the
server-side extensions allow an application to communicate with a database, and provide
continuity of information from one invocation to another of the application, or perform file
manipulations on a server.
● Imperative language – imperative code focuses on writing an explicit sequence of
commands to describe how you want the computer to do things.
● Declarative programming – declarative code focuses on specifying the result of what
you want. Developers are more concerned with the answer that is received. It declares what
kind of results we want and leave programming language aside focusing on simply figuring
out how to produce them.
Features of JavaScript:
Here are a few things that we can do with JavaScript:
● JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
● Functions in JS are objects. They may have properties and methods just like another object.
They can be passed as arguments in other functions.
● Can handle date and time.
● Performs Form Validation although the forms are created using HTML.
● No compiler is needed.
Applications of JavaScript:
● Web Development: Adding interactivity and behavior to static sites
● Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming
Interfaces(APIs) that provide extra power to the code.
● Server Applications: With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful on the server-side.
● Games: Not only in websites, but JavaScript also helps in creating games.
● Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This framework
works for applications that require the internet for its functioning.
● Art: Artists and designers can create whatever they want using JavaScript to draw on
HTML 5 canvas.
● Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.
● Mobile Applications: The features and uses of JavaScript make it a powerful tool for
creating mobile applications.
Advantages of JavaScript
The merits of using JavaScript are −
● Less server interaction − You can validate user input before sending the page off to
the server. This saves server traffic, which means less load on your server.
● Immediate feedback to the visitors − They don't have to wait for a page reload to see
if they have forgotten to enter something.
● Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
● Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the following
important features −
● Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
● JavaScript cannot be used for networking applications because there is no such support
available.
● JavaScript doesn't have any multi-threading or multiprocessor capabilities.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are
valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
other actions that the user initiates explicitly or implicitly.
The <script> tag
The <script> tag in HTML is used to define the client-side script.
The <script> tag contains the scripting statements, or it points to an external script file.
The JavaScript is mainly used in form validation, dynamic changes of content, image
manipulation, etc.
Syntax:
<script> Script Contents... </script>
Attribute Description
The script tag can be used within <body> or <head> tag to embed the scripting code.
The browser loads all the scripts included in the <head> tag before loading and rendering
the <body> tag elements. So, always include JavaScript files/code in the <head> that are going
to be used while rendering the UI. All other scripts should be placed before the
ending </body> tag. This way, you can increase the page loading speed.
Example Program:
<html>
<body>
<script type="text/javascript">
[Link]("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>
Output:
Let's see the example to have script tag within HTML head tag.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
Output:
The script tag can be used to link external script file by src attribute. It must be used within the
<head> tag only. write JavaScript code in a separate file with .js extension and include it in a
web page using <script> tag and reference the file via src attribute.
Example Program:
[Link]
function msg(){
alert("Hello Javatpoint");
}
[Link]
<html>
<head>
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body> </html>
General Syntactic Characteristics
● All JavaScript scripts will be embedded in HTML documents.
o Either directly, as in
<script type = "text/javaScript">
-- JavaScript script -
</script>
o Or indirectly, as a file specified in the src attribute of <script>, as in
<script type = "text/javaScript"
src = "[Link]">
</script>
● Language Basics:
o Identifier form: begin with a letter or underscore, followed by any number of letters,
underscores, and digits
o Javascript is case sensitive
o 25 reserved words, plus future reserved words Eg: break, continue, switch, case,
if, else, while, for….
o Comments: both // and /* ... */
● Scripts are usually hidden from browsers that do not include JavaScript interpreters by
putting them in special comments
<!--
-- JavaScript script -
//-->
o Also hides it from HTML validators
● Semicolons can be a problem
o They are "somewhat" optional.
o You can omit the semicolon between two statements if they are written on separate
lines.
o You can omit a semicolon at the end of a program or if the next token in the program
is a closing curly brace }.
o You should put each statement on its own line whenever possible and terminate each
statement with a semicolon.
Problem: When the end of the line may not be the end of a statement – JavaScript puts
a semicolon there. But this implicit insertion can lead to problems.
Eg: return
x;
The interpreter will insert a semicolon after return, because return need not be followed
by an expression, making x an invalid orphan.
To avoid this problem, put each statement on its own line and terminate each statement
with a semicolon.
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Primitives
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and
has no methods or properties.
The typeof operator tells you what type a primitive value is. To get the current type of the value
that the variable stores, you use the typeof operator.
String:
Example:
let greeting = 'Hi';
let message = "Bye";
● If you want to single quote or double quotes in a literal string, you need to use the
backslash to escape it.
For example:
let message = 'I\'m also a valid string'; // use \ to escape the single quote (')
● JavaScript strings are immutable. This means that it cannot be modified once created.
However, you can create a new string from an existing string.
For example:
let str = 'JavaScript';
str = str + ' String';
In this example:
● First, declare the str variable and initialize it to a string of 'JavaScript'.
● Second, use the + operator to combine 'JavaScript' with ' String' to make its
value as 'Javascript String'.
● Behind the scene, the JavaScript engine creates a new string that holds the new
string 'JavaScript String' and destroys the original strings 'JavaScript' and ' String'.
The following example attempts to change the first character of the string JavaScript:
let s = 'JavaScript';
s[0] = 'j';
[Link](s)
Number:
● JavaScript uses the number type to represent both integer and floating-point numbers
(decimals and exponentials).
● The following statement declares a variable and initializes its value with an integer:
let num = 100;
For example:
let price= 12.5;
let discount = 0.05;
● The reason is that Javascript always wants to use less memory since a floating-point
value uses twice as much memory as an integer value.
For example:
let price = 200.00; // interpreted as an integer 200
For example:
[Link](Number.MAX_VALUE); // 1.7976931348623157e+308
[Link](Number.MIN_VALUE); // 5e-324
● A number type can also be +Infinity, -Infinity, and NaN (not a number).
For example,
const number1 = 3/0;
[Link](number1); // Infinity
bigint:
● The bigint type represents the whole numbers that are larger than 253 – 1. To form
a bigint literal number, you append the letter n at the end of the number.
For Example:
1. let pageView = 9007199254740991n;
[Link](typeof(pageView)); // 'bigint'
● The boolean type has two literal values: true and false in lowercase. The following
example declares two variables that hold the boolean values.
For example:
[Link](Boolean('Hi'));// true
[Link](Boolean('')); // false
[Link](Boolean(20)); // true
[Link](Boolean(Infinity)); // true
[Link](Boolean(0)); // false
[Link](Boolean({foo: 100})); // true on non-empty object
[Link](Boolean(null));// false
Undefined:
● The undefined type is a primitive type that has only one value undefined.
● By default, when a variable is declared but not initialized, it is assigned the value
of undefined.
In this example, the counter is a variable. Since counter hasn’t been initialized, it is
assigned the value undefined. The type of counter is also undefined.
● It’s important to note that the typeof operator also returns undefined when you call it
on a variable that hasn’t been declared:
Example: [Link](typeof undeclaredVar); // undefined
● It is also possible to explicitly assign a variable value undefined.
For example,
let name = undefined;
[Link](name); // undefined
Symbol:
● Different from other primitive types, the symbol type does not have a literal form.
● A Symbol is a value created by invoking the Symbol function which is guaranteed to
create a unique value every time you call it.
● It takes one parameter, a string description, that will show up when you print the
symbol.
Example:
let x = Symbol("this is a symbol");
typeof x; // 'symbol'
[Link](Symbol() == Symbol()); // false
null:
● The null type is the second primitive data type that also has only one value null.
For example,
let number = null;
[Link](typeof obj); // object
Variables
Variables are containers for storing data (storing data values) that can be changed later on.
Declare a Variable
● To declare a variable, write the keyword let followed by the name of the variable you
want to give, as shown below.
Example: Variable Declaration
let msg; // declaring a variable without assigning a value
In the above example, var msg; is a variable declaration. It does not have any value
yet.
● The default value of variables that do not have any value is undefined.
● You can assign a value to a variable using the = operator when you declare it or after
the declaration and before accessing it.
Example: Variable Initialization
let msg;
msg = "Hello JavaScript!"; // assigning a string value
In the above example, the msg variable is declared first and then assigned a string value
in the next line.
● You can declare a variable and assign a value to it in the same line. Values can be of
any datatype such as string, numeric, boolean, etc.
Example: Variable Declaration and Initialization
let name = "Steve"; //assigned string value
let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value
● You can copy the value of one variable to another variable, as shown below.
Example: Copy Variable
let num1 = 100;
let num2 = num1;
● JavaScript allows multiple white spaces and line breaks when you declare a variables.
Example: Whitespace and Line Breaks
let name = "Steve",
num = 100,
isActive = true;
The general rules for constructing names for variables (unique identifiers) are:
● Names can contain letters, digits, underscores, and dollar signs.
● Names must begin with a letter.
● Names can also begin with $ and _.
o These names are valid:
let $ = 1; // declared a variable with the name "$"
let _ = 2;
alert($ + _); // 3
● Names are case sensitive. So, the variable names msg, MSG, Msg, mSg are considered
separate variables.
● Reserved words (lik
● Dynamic Typinge JavaScript keywords) cannot be used as names.
● JavaScript is a loosely typed language. It means that you don't need to specify what
data type a variable will contain.
● You can update the value of any type after initialization. It is also called dynamic
typing.
Example: Loosely Typed Variable
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
● The value of the constant variables can't be changed after initialized them.
● The value of a constant variable cannot be changed but the content of the value can be
changed. For example, if an object is assigned to a const variable then the underlying
value of an object can be changed.
● It is best practice to give constant variable names in capital letters to separate them from
other non-constant variables.
Variable Scope
In JavaScript, a variable can be declared either in the global scope or the local scope.
Global Variables
Variables declared out of any function are called global variables. They can be accessed
anywhere in the JavaScript code, even inside any function.
Local Variables
Variables declared inside the function are called local variables of that function. They can only
be accessed in the function where they are declared but not outside.
The following example includes global and local variables.
function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}
myfunction();
● Variables can be declared and initialized without the var or let keywords. However, a
value must be assigned to a variable declared without the var keyword.
● The variables declared without the var keyword become global variables, irrespective
of where they are declared.
myfunction();
alert(msg); // msg becomes global variable so can be accessed here
Points to Remember:
Typeof operator
In JavaScript, the typeof operator returns the data type of its operand in the form of a string.
The operand can be any object, function, or variable.
Syntax:
typeof operand
OR
typeof (operand)
Example:
typeof "John" // Returns "string"
typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"
let type;
type = typeof 'Hi';
[Link](type); // 'string'
we will pass numbers as operands and use the typeof operator and log the result to the console.
We will use a positive integer, negative integer, zero, floating-point number, infinity, NaN, and
Math equations as operands. We will also use the concept to explicitly typecasting and parsing
a string to an integer or float and use it as an operand.
Example:
[Link](typeof 12) //number
[Link](typeof -31) //number
When passing an expression to the typeof operator, you need to use parentheses.
For example:
let type = typeof (100 + '10');
[Link](type);
Output:
'string'
string concatenation
In this example, the expression 100 + '10' returns the string '10010'. Therefore, its type
is 'string'. If you don’t use the parentheses, you’ll get an unexpected result.
For example:
let type = typeof 100 + '10';
[Link](type);
Output:
'number10'
In this example, the typeof 100 returns 'number'. Therefore, the result is a string that is the
concatenation of the string 'number' and '10'.
● Arithmetic Operators
● Assignment Operators
● Comparison Operators
● Logical Operators
● Conditional Operators
● Type Operators
i. Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y = 5, the table below explains the arithmetic operators:
ii. Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x = 10 and y = 5, the table below explains the assignment operators:
const person = {
name: "John",
age: 30
};
iii. Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.
v. Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators:
The difference between the two operators is that the double equals == will compare the
values loosely, meaning that it will try to convert values with different types before
comparing them.
The triple equals === won’t convert values of different types. It will simply return false when
comparing values of different types.
To understand their differences, let’s try comparing two different values between the number
value 0 and boolean value false:
As you can see from the code above, the == operator returns true because the boolean value
false is converted to a number before comparing it with 0.
On the other hand, the triple equals === will simply return false for the same values as above
because it doesn’t do conversion at all.
Screen Output
JavaScript can "display" data in different ways:
i. Using innerHTML
To access an HTML element, JavaScript can use the [Link](id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example:
<html>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Output
ii. Using [Link]()
For testing purposes, it is convenient to use [Link]():
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call [Link] after the document has finished loading.
It will overwrite the whole document.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Output
<html>
<body>
[Link](5 + 6);
</script>
</body>
</html>
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
Keyboard Input
The prompt() method in JavaScript is used to display a prompt box that prompts the user for
the input. It is generally used to take the input from the user before entering the page. It can be
written without using the window prefix. When the prompt box pops up, we have to click "OK"
or "Cancel" to proceed.
The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the default
string, which displays in the textbox. The prompt box consists of two buttons, OK and Cancel.
It returns null or the string entered by the user. When the user clicks "OK," the box returns the
input value. Otherwise, it returns null on clicking "Cancel". [Link]
Label (First Argument): This is the text or label that is displayed in the
box. It typically serves as an instruction or a prompt to inform the
user about what kind of input is expected. For example, if you want the
user to enter their name, you might set the label as "Please enter your
name."
Syntax
b. Default String (Second Argument): This is the default value or text that
prompt(message, default) is initially displayed in the input field of the dialog box. It serves as a
placeholder or suggestion for what the user can enter. If the user doesn't
change this default value and directly clicks "OK" or presses Enter, this
default string will be returned as the result.
message: It is an optional parameter. It is the text displays to the user. We can omit this value
if we don't require to show anything in the prompt.
default: It is also an optional parameter. It is a string that contains the default value displayed
in the textbox.
<html>
<head>
<script type = "text/javascript">
function fun() { default
prompt ("This is a prompt box", "Hello world");
} message
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>
message argument
default argument
The prompt box takes the focus and forces the user to read the specified message. So, it should avoid
overusing this method because it stops the user from accessing the other parts of the webpage until the
box is closed.
Keyboard Events
i. onkeydown Event
The onkeydown event occurs when the user presses a key on the keyboard.
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Accessing Array Elements
You access an array element by referring to the index number:
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
JavaScript Maps
like dictionary?
A Map holds key-value pairs where the keys can be any datatype.
You can create a Map by passing an Array to the new Map() constructor:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Creating a Map from an Array:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>
Output:
2. The set() Method
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map();
// Set Map Values
[Link]("apples", 500);
[Link]("bananas", 300);
[Link]("oranges", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>
Output:
The set() method can also be used to change existing Map values:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("apples", 200);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>
Output:
Output:
4. The size Property
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Maps</h2>
<p>Using [Link]:</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link];
</script>
</body>
</html>
Output:
Output:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Maps</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
[Link]("demo").innerHTML = [Link]("apples");
</script>
</body>
</html>
Output:
The forEach() method calls a function for each key/value pair in a Map:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
[Link] (function(value, key) {
text += key + ' = ' + value + "<br>"
})
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
Output:
8. The entries() Method
The entries() method returns an iterator object with the [key, values] in a Map:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Map Objects</h2>
<p>Using [Link]():</p>
<p id="demo"></p>
<script>
// Create a Map
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);
let text = "";
for (const x of [Link]()) {
text += x + "<br>";
}
[Link]("demo").innerHTML = text;
</script>
</body>
</html>
Output:
Javascript control statements:
1. If Statement
2. If else statement
3. if else if statement
JavaScript If Statement:
If statement is used to execute a block of statements if specified condition is true.
Syntax:
if(condition)
Syntax:
if(condition)
{
//Block of JavaScript statements1.
}
else
{
//Block of JavaScript statements2.
}
JavaScript If Else If Statement:
If else statement is used to execute one block of statements from many depends upon the
condition. If condition1 is true then block of statements1 will be executed, else if condition2
is true block of statements2 is executed and so on. If no condition is true, then else block of
statements will be executed.
Syntax:
if(condition 1)
{
//Block of JavaScript statements1.
}
else if(condition 2)
{
//Block of JavaScript statements2.
}...
else if(condition n)
{
//Block of JavaScript statementsn.
}
else
{
//Block of JavaScript statements.
}
Example
<html>
<head>
<script>
var num=2;
if(num==1){
[Link]("JavaScript Statement 1");
}
else if(num==2){
[Link]("JavaScript Statement 2");
}
else if(num==3){
[Link]("JavaScript Statement 3");
}
else{
[Link]("JavaScript Statement n");
}
</script>
</head>
<body>
</body>
</html>
Output:
JavaScript Statement 2
Strings
JavaScript strings are for storing and manipulating text.
A JavaScript string is zero or more characters written inside quotes.
Example
Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:
Example
String Methods
● String length
● String slice()
● String substring()
● String substr()
● String replace()
● String replaceAll()
● String toUpperCase()
● String toLowerCase()
● String concat()
● String trim()
● String trimStart()
● String trimEnd()
● String padStart()
● String padEnd()
● String charAt()
● String charCodeAt()
● String split()
String Length
The length property returns the length of a string:
Output: 26
String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
Example
Output: Banana
First position is 0.
Second position is 1
String substring()
substring() is similar to slice().
The difference is that start and end values less than 0 are treated as 0 in substring().
Example
Output: Banana
If you omit the second parameter, substring() will slice out the rest of the string.
String substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
Example
Output: Banana
If you omit the second parameter, substr() will slice out the rest of the string.
If the first parameter is negative, the position counts from the end of the string.
Example
Output: Kiwi
Example
Example
Example
To replace all matches, use a regular expression with a /g flag (global match):
Example
let len=[Link];
Example [Link](len);
let slice=[Link](0,3);
[Link](slice);
text = [Link](/Cats/g,"Dogs");
let subs=[Link](5);//from 5th position everything
[Link](subs);
text = [Link](/cats/g,"dogs");
let subss=[Link](5,7);//from 5th position everything till 7th position
[Link](subss);
let substr2=[Link](-5,8);//backward
[Link](substr2);
Example let substr3=[Link](-9,10);
[Link](substr3);
let lcase=[Link]();
let text2 = [Link](); [Link](lcase);
let name1="tanmayi";
let name2="s balija";
Output: hello world! let conact=[Link](" ",name2);
let conact1=[Link](name2);
[Link](conact);
[Link](conact1);
String concat()
concat() joins two or more strings:
Example
String trim()
The trim() method removes whitespace from both sides of a string:
Example
Output:
Length text1 = 22
Length text2 = 12
String trimStart()
The trimStart() method works like trim(), but removes whitespace only from the start
of a string.
Example
Output:
Length text1 = 22
Length text2 = 17
String trimEnd()
The trimEnd() method works like trim(), but removes whitespace only from the end of a
string.
Example
Output:
Length text1 = 22
Length text2 = 17
String padStart()
The padStart() method pads a string with another string:
Example
Output:
xxx5
Example
Output:
0005
String padEnd()
The padEnd() method pads a string with another string:
Example
Output: 5xxx
String charAt()
The charAt() method returns the character at a specified index (position) in a
string:
Example
Output: H
String charCodeAt()
The charCodeAt() method returns the unicode of the character at a specified index
in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
Output: 72
JavaScript Objects
diff btw object and variable
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Object Properties
The name:values pairs in JavaScript objects are called properties:
Accessing Object Properties
You can access object properties in two ways:
[Link]
Example:
[Link];
OR
objectName["propertyName"]
Example:
person["lastName"];
Object Methods
Objects can also have methods.
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
};
[Link]()
Example
name = [Link]();
When you search for data in a text, you can use this search pattern to describe what
you are searching for.
Regular expressions can be used to perform all types of text search and text replace
operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
here,
The search() method uses an expression to search for a match, and returns the position
of the match.
The replace() method returns a modified string where the pattern is replaced.
Example
let n = [Link]("W3Schools");
let n = [Link](/w3schools/i);
Visit W3Schools!
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
// code to be executed
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables can only be accessed from within the function.
Example
function myFunction() {
Since local variables are only recognized inside their functions, variables with the
same name can be used in different functions.
Local variables are created when a function starts, and deleted when the function is
completed.
Window Object
• Through it, you can access the current page’s URL, the browser’s history, and what’s
being displayed in the status bar, as well as opening new browser windows.
Method Description
confirm() displays the confirm dialog box containing message with ok and cancel
button.
prompt() displays a dialog box to get input from the user.
setTimeout() performs action after specified time like calling function, evaluating
expressions etc.
Example program
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function input()
{
[Link]("BMS College of Engineering, Bangalore");
alert("Welcome to BMSCE");
var registration=confirm("Do You want to register for 3rd Sem ?");
if(registration)
{
var name=prompt("Enter your name:");
if(name=="CPN")
{
alert("CPN");
}
else
{
alert("You are not CPN");
}
}
else
alert("Please Register later");
}
setTimeout(function(){
[Link]("Tutorix is the best e-learning platform");
}, 2000);
[Link]("[Link]
function openWin() {
myWindow = [Link]("[Link] "_blank", "width=200,
height=100");
}
openWin();
function closeWin() {
[Link]();
}
closeWin();
input();
</script>
</body>
</html>
DOM Nodes
• In DOM Tree the root or topmost object is called the Document Root.
• Each element within the HTML document is called a node. If the DOM is a tree, then
each node is an individual branch.
• There are:
1) Element nodes,
2) Text nodes,
3) Attribute nodes
Document Object
• The DOM document object is the root JavaScript object representing the entire
HTML document.
• It contains some properties and methods that we will use extensively in development
and is globally accessible as document.
• Accessing the properties is done through the dot notation.
•
getElementById(“Id”)
getElementByClassName(“name”)
getElementByTagName(“name”)