Javascript Fundamentalss Org
Javascript Fundamentalss Org
TRADE: SOFTWARE
DEVELOPMENT
TEACHER’S GUIDE
MODULE NAME: JAVASCRIPT
FUNDAMENTALS 1
MODULE NAME: APPLY JAVASCRIPT
2022
Acronyms
JS: JavaScript
AJAX: Asynchronous JavaScript and XML
Introduction
This JavaScript module covers all the fundamental and advanced
programming concepts. We have designed this JavaScript handout for
students. JavaScript is among the most powerful and widely used
programming languages for the web. It is an open-source and interpreted
programming language supported by all browsers. JavaScript is a lightweight,
interpreted programming language. It is designed for creating network-centric
applications. It is complimentary to and integrated with Java. JavaScript is
very easy to implement because it is integrated with HTML. It is open and
cross-platform.
2
Module Code and Title: SWDJF301: JAVASCRIPT FUNDAMENTALS
1
Objectives apply JavaScript Basic Concepts
By the end of the learning outcome, the trainees will be able to:
1. Integrate properly JavaScript in HTML based on project structure
2. Use correctly Variables based on task
3. use correctly the Datatype based on variables
4. Use correctly the Operators based on task
Definition of JAVASCRIPT
JavaScript is a lightweight, interpreted programming language. It
is designed for creating network-centric applications. It is
complimentary to and integrated with Java. JavaScript is very easy
to implement because it is integrated with HTML. It is open and
cross-platform.
JavaScript is among the most powerful and widely used
programming languages for the web. It is an open-source and
interpreted programming language supported by all browsers.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.
✔ Application of Javascript
As mentioned before, Javascript is one of the most widely used programming
languages (Front-end as well as Back-end). It has it is presence in almost
every area of software development. I am going to list few of them here:
Client side validation - This is really important to verify any user
input before submitting it to the server and Javascript plays an
important role in validating those inputs at front-end itself.
Manipulating HTML Pages - Javascript helps in manipulating HTML
page on the fly. This helps in adding and deleting any HTML tag very
easily using javascript and modify your HTML to change its look and
feel based on different devices and requirements.
2
User Notifications - You can use Javascript to raise dynamic pop-
ups on the webpages to give different types of notifications to your
website visitors.
Back-end Data Loading - Javascript provides Ajax library, which
helps in loading back-end data while you are doing some other
processing. This really gives an amazing experience to your website
visitors.
Presentations - JavaScript also provides the facility of creating
presentations, which gives website look and feel. JavaScript provides
RevealJS and BespokeJS libraries to build web-based slide
presentations.
Server Applications - Node JS is built on Chrome's Javascript
runtime for building fast and scalable network applications. This is
an event-based library, which helps in developing very sophisticated
server applications including Web Servers.
Server Applications
Web Servers
Games
Art
Smartwatch Apps
3
Mobile Apps
Flying Robots
Last but not least, you can use JavaScript to program a flying robot. With
the Node.js ecosystem, users can control numerous small robots, creative
maker projects, and IoT devices. Step into the exciting world of drones,
flying robots, and quadcopters with JavaScript.
This list goes on, there are various areas where millions of software developers
are happily using Javascript to develop great websites and others softwares.
Install VS Code & node
Visual Studio Code is a lightweight but powerful source code editor, which
runs on your desktop and is available for Windows, macOS and Linux. It
comes with built-in support for JavaScript, TypeScript and Node.js and has a
rich ecosystem of extensions for other languages and runtimes (such as C++,
C#, Java, Python, PHP, Go, .NET).
Installation
1. Download the Visual Studio Code installer for Windows.
2. Once it is downloaded, run the installer (VSCodeUserSetup-
{version}.exe). This will only take a minute.
3. By default, VS Code is installed
under C:\Users\{Username}\AppData\Local\Programs\Microsoft VS
Code.
Alternatively, you can also download a Zip archive, extract it and run Code
from there.
Intelligent Code Completion
4
JAVASCRIPT key concepts
Variable: A variable is simply a container, which contains some
values.
Data Types: in programming, is a classification that specifies which
type of value a variable has and what type of mathematical,
relational or logical operations can be applied to it without causing
an error. A string, for example, is a data type that is used to classify
text and an integer is a data type used to classify whole numbers.
5
class Float package try
double In super
Any text between // and the end of the line will be ignored by JavaScript (will
not be executed).
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Multi-line Comments
6
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
● React Javascript
React (also known as React.js or ReactJS) is a free and open-source
front-end JavaScript library for building user interfaces based on UI
components.
● JQuery
It's a library of JavaScript functions that make it easy for webpage
developers to do common tasks-- like manipulating the webpage, responding
to user events, getting data from their servers, building effects and
animations, and much more.
● Three Javascript
Three.js is a cross-browser JavaScript library and application programming interface
(API) used to create and display animated 3D computer graphics in a web.
Vue Javascript
Angular Javascript
7
AngularJS is a client side JavaScript MVC framework to develop a dynamic web
application.
Express Javascript
Express is a minimal and flexible Node.js web application framework that provides a
robust set of features for web and mobile applications.
8
Execution of JavaScript can be done by placing JavaScript statements
within the HTML tags in a web page. JavaScript is an easy language when it
comes to coding.
Generally there are three places where you can put the JavaScript code:
Inside Body Tag
Inside head
External JavaScript file
Here is an example to understand this from an initial level:
<script type="text/javascript">
document.write("PHPTPOINT is the place to study javascript easily");
</script>
Using the script tag signifies that we are using JavaScript
3 Places to put JavaScript code
1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)
9
JavaScript Syntax: Code between the Body Tags
In the above-explained example, there is a depiction of the dynamic content
using the JavaScript. Here is another example displaying alert box.
<html>
<head>
<title>JavaScript Inside Body</title>
</head>
<body>
<script type="text/javascript">
function msg()
{
alert("Hello phptpoint");
}
</script>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function msg()
{
alert("Hello phptpoint");
}
</script>
</head>
<body>
<p>Welcome to phptpoint</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
10
Using External JavaScript
With JavaScript, a external JavaScript file can be created and can easily be
embedded into many HTML pages. Since a single JavaScript file can be used
in various HTML pages hence, it provides code re usability.
In order to save a JavaScript file, .js extension must be used. To increase
the speed of the webpages, it is recommended to embed the entire
JavaScript file in to a single file.
1. <html>
<head>
<title>External Javascript Example-Phptpoint</title>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body>
<p>Welcome to Phptpoint</p>
<input type="button" value="click" onclick="msg()"/>
</body>
</html>
Example:
<!DOCTYPE html>
11
<html>
<center>
<body>
<h2>External JavaScript</h2>
<p id="demo">Geeks For Geeks.</p>
<button type="button" onclick="myFunction()">Try
it</button>
<script src="myScript.js"></script>
</body>
<center>
</html>
<script src=
"https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.nostyle.js">
</script>
JavaScript output
JavaScript Display Possibilities. JavaScript can "display" data in different
ways:
Using innerHTML
Example
<Html>
<Head>
12
<Body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example: 1
<! DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph. </p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Example: 2
</body>
</html>
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
13
<script>
alert(5 + 6);
</script>
</body>
</html>
Using console.log ()
For debugging purposes, you can call the console.log() method in the
browser to display data.
Example
JavaScript Print
JavaScript does not have any print object or print methods. You cannot
access output devices from JavaScript. The only exception is that you can
call the window.print() method in the browser to print the content of the
current window.
<!DOCTYPE html>
<html>
<body>
<button onclick="window.print()">Print this page</button>
</body>
</html>
14
A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are
different variables.
JavaScript variables
1. var x = 10;
2. var _value="sonoo";
Example of JavaScript variable
Let us see a simple example of JavaScript variable.
1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
30
JavaScript local variable
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
Or,
1. <script>
2. If(10<13){
15
3. var y=20;//JavaScript local variable
4. }
5. </script>
1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
1.4 Use of data types in JAVASCRIPT
To hold different types of values, JavaScript provides different data types.
In JavaScript, there are only two types of data types:
16
<script>
var x=20;//holding number
var y="Phptpoint";//holding string
var bool=true;//holding boolean true
var bools=false;//holding boolean false
var blank=null;//holding null value
<script>
2. Non-Primitive Data Types in JavaScript
There are generally three types of non-primitive data types which are as
follows:
<script>
//example of Object
stu={id:101,name:"sanjeev"}
alert(stu.id+" "+stu.name);
</script>
Example of Array:
<script>
//example of Array
arr=Array(101,"sanjeev");
alert(arr[0]+" "+arr[1]);
</script>
3. Type-casting
Typecasting in JavaScript means converting one data type to another data
type i.e., the conversion of a string data type to Boolean or the conversion of
an integer data type to string data type. The typecasting in JavaScript is also
known as type conversion or type coercion.
Types of conversions
The type casting is of two types in JavaScript. They are the implicit type
conversions and the explicit type conversions.
Typecasting in JavaScript means converting one data type to another data type.
17
Converting Strings to Numbers
Converting Numbers to Strings
Converting Dates to Numbers
Converting Numbers to Dates
Converting Booleans to Numbers
Converting Numbers to Booleans
The global method Number() converts a variable (or a value) into a number.
A numeric string (like "3.14") converts to a number (like 3.14).
An empty string (like "") converts to 0.
A non numeric string (like "John") converts to NaN (Not a Number).
Examples
Number("3.14")
Number(Math.PI)
Number(" ")
Number("")
Number("99 88")
Number("John")
Number Methods
In the chapter Number Methods, you will find more methods that can be
used to convert strings to numbers:
Method Description
18
Number() Returns a number, converted from its argument
Example
If the variable cannot be converted, it will still become a number, but with
the value NaN (Not a Number):
Example
Example
19
Example
x.toString()
(123).toString()
(100 + 23).toString()
More Methods
In the chapter Number Methods, you will find more methods that can be
used to convert numbers to strings:
Method Description
toFixed() Returns a string, with a number rounded and written with a specified
number of decimals.
d = new Date();
Number(d) // returns 1404568027739
d = new Date();
d.getTime() // returns 1404568027739
20
Converting Dates to Strings
String(Date()) // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"
Example
Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight
Time)"
In the chapter Date Methods, you will find more methods that can be used
to convert dates to strings:
Method Description
21
getMonth() Get the month (0-11)
Number(false) // returns 0
Number(true) // returns 1
When JavaScript tries to operate on a "wrong" data type, it will try to convert
the value to a "right" type.
22
5 + null // returns 5 because null is converted to 0
"5" + null // returns "5null" because null is converted to "null"
"5" + 2 // returns "52" because 2 is converted to "2"
"5" - 2 // returns 3 because "5" is converted to 5
"5" * "2" // returns 10 because "5" and "2" are converted to 5 and 2
JavaScript automatically calls the variable's toString() function when you try
to "output" an object or a variable:
document.getElementById("demo").innerHTML = myVar;
The implicit type casting is the conversion of data type done due to the
internal requirement or automatic conversion by the compiler or the
interpreter. To understand the implicit conversion let us consider the
example of the boolean values (primitive). JavaScript expects a boolean
value in a conditional expression. So JavaScript will temporarily convert the
value in parentheses to a Boolean to evaluate the if expression
val = 1;
if (val) {
console.log( 'yes, val exists' );
}
23
1.4. Use of operators in Javascript
In JavaScript, words and symbols in expressions that perform operations
certain values to arrive at another value are known as operators. Any value
on which an operator performs some action is called an operand. An
expression may contain one operand and one operator (called a unary
operator) or two operands separated by one operator (called a binary
operator). Many of the same symbols are used in a variety of operators. The
combination and order of those operator symbols are what distinguish their
powers. In simple words, an operator is the one operating the operand.
There are many use of operators in JavaScript such as comparing values,
performing arithmetic operations, etc.
Operator Description
24
var a = 2, b = 4;
a + b; //returns 6
b - a; //returns 2
a * b; //returns 8
b / a; //returns 2
a % 2; //returns 1
a++; //returns 3
a--; //returns 1
Comparison Operators
Any time you compare two values in JavaScript, the result is a Boolean true
or false value.
You have a wide selection of comparison operators to choose from,
depending on the kind of test you want to apply to the two operands.
There are basically 4 ways by which the equality is tested that are listed as
follows:
'==' operator
'===' operator
SameValuezero: this is mainly used in maps, arrays and sets.
SameValue: these are used elsewhere.
All the various types of comparison operators are mentioned in the table
below:
25
< Less than 22<12 = false
<= Less than or equal to 22<=12 = false
'==' operator:
In javascript, the use of this operator is mainly in comparing two value on
both the sides and then return true or false as a result. This javascript
operator, evaluates the equality only after converting or we can say bringing
both the values to a common type known as type coercion.
For numeric values, the results are the same as those you would expect
from your high school algebra class.
10 == 10 // true
10 == 10.0 // true
9 != 10 // true
9 > 10 // false
9.99 <= 9.98 // false
'===' operator:
This JavaScript operator is also called as strict equality operator, it
simultaneously compares the value and the type.
The bitwise operator’s carryout bitwise operations on the operands. Here are
the bitwise operators:
26
! Logical Not !(12==22) = true
Syntax
Example
If the variable age is a value below 18, the value of the variable voteable
will be "Too young", otherwise the value of voteable will be "Old enough".
27
Example
Example
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Ask for car name:
document.getElementById("demo").innerHTML = car?.name;
28
Indicative contents (headings of indicative content from the module
of the curriculum)
2.1. Conditional statements are properly implemented according to the
control flow
1.2. Loop functions are appropriately used based on task
1.3. Functions are appropriately used based on the task
1.4. Object are correctly defined based on task
1.5. Arrays are appropriately applied based on task
Duration: ……….hrs
JavaScript If-else
29
}
Here is an example of If statement in JavaScript:
Example
<script>
var x=22;
if(x>11)
{
document.write("value of x is bigger than 11");
}
</script>
30
3. If-else-if statement in JavaScript
If-else-if statement computes the content only if expression is true from
various.
When we want to use condtion more than one times then we can use Nested
if-else.
syntax :
<script>
if(expression1)
{
//content that is to be evaluated if expression1 is true
}
else if(expression2)
{
//content that is to be evaluated if expression2 is true
}
else if(expression3)
{
//content that is to be evaluated if expression3 is true
}
else
{
//content that is to be evaluated if no expression is true
}
</script>
Here is an example of else-if-else statement in JavaScript;
Example 1
<script>
var x=10;
if(x==5){
document.write("x is equal to 5");
}
else if(x==10){
document.write("x is equal to 10");
}
else if(x==15){
document.write("x is equal to 15");
}
else{
document.write("x is not equal to 5, 10 or 15");
}
</script>
Output: x is equal to 10
JavaScript Switch
In order to execute one code from multiple expressions, JavaScript Switch is
used. It is known to be very similar to the if-else statement and due to the
31
permitted use of numbers and characters it is more convenient than if-else-
if.
switch(expression)
{
case value1:
code that is to be executed;
break;
case value2:
code that is to be executed;
break;
.
.
.
.
default:
code that is to be executed if above values are not matched;
}
Example 1
<script>
var Class='B';
var result;
switch(Class)
{
case 'A':
result="A Class";
break;
case 'B':
result="B Class";
break;
case 'C':
result="C Class";
break;
default:
result="No class";
}
document.write(result);
</script>
Output: The output for the above-mentioned example is B Class.
32
<script>
var Class='B';
var result;
switch(Class)
{
case 'A':
result=" A Class";
case 'B':
result=" B Class";
case 'C':
result=" C Class";
default:
result=" No Class";
}
document.write(result);
</script>
Output: No Class
JavaScript Loop
In order to iterate the piece of code using the for, while, do-while, or for-in
loops JavaScript is used. It is generally used in array and helps in making
the code compact.
In JavaScript, there are generally four types of loops:
1. for loop
2. while loop
3. do-while loop
4. for-in loop
1.For Loop in JavaScript
The For Loop in JavaScript iterates the elements for a finite number of times
and should be used when the number of iteration is known.
Here is the syntax mentioned below:
JavaScript Loop
In order to iterate the piece of code using the for, while, do-while, or for-in
loops JavaScript is used. It is generally used in array and helps in making
the code compact.
In JavaScript, there are generally four types of loops:
1. for loop
33
2. while loop
3. do-while loop
4. for-in loop
1. For Loop in JavaScript
The For Loop in JavaScript iterates the elements for a finite number of times
and should be used when the number of iteration is known.
Here is the syntax mentioned below:
<script>
for (i=2; i<=6; i++)
{
document.write(i + "<br/>")
}
</script>
Here is the output for the above mentioned example:
2
3
4
5
6
<script>
var sum=0;
for (var i=1; i<=100; i++)
{
sum=sum+i;
}
document.write("Sum of 1 to 100="+sum);
</script>
34
Here is the output for the above mentioned example: Sum of 1 to
100=5050
while (condition)
{
code that you wants to be executed
}
Let's take an example for while loop
<script>
var i=10;
while(i<=12)
{
document.write(i + "<br/>");
i++;
}
</script>
<script>
var table=5;
var i=1;
var tab=0;
while(i<=10)
{
var tab=table*i;
document.write(tab + " ");
i++;
35
}
</script>
do
{
code that you wants to be executed
}
while (condition);
Let's take an example for Do-while loop
<script>
var i=20;
do
{
document.write(i + "<br/>");
i++;
}
while (i<=23);
</script>
Here is the output for the above-mentioned example:
20
21
22
23
The most basic loop in JavaScript is the while loop which would be discussed
in this chapter. The purpose of a while loop is to execute a statement or code
block repeatedly as long as an expression is true. Once the expression
becomes false, the loop terminates.
36
Syntax
While (expression) {
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
document.write("Starting Loop ");
while (count < 10) {
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop stopped!");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
37
Set the variable to different value and then try...
<html>
<body>
<script type = "text/javascript">
var user = {fname:"sanjeev", lname:"kumar",country:"india"};
var x;
for (x in user)
{
document.write(x+": "+user[x]+"<br>");
}
</script>
</body>
</html>
Here is the output for the above mentioned example:
fname: sanjeev
lname: kumar
country: india
Example 2:
<html>
<body>
<script type = "text/javascript">
var aProperty;
document.write("Navigator Object Properties:<br/>");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br/>");
}
38
document.write ("Exiting from the loop!");
</script>
<p>Set the variable to different object and then try...<p>
</body>
</html>
Here is the output for the above mentioned example:
Navigator Object Properties:
vendorSub
productSub
vendor
maxTouchPoints
hardwareConcurrency
cookieEnabled
appCodeName
appName
appVersion
platform
product
userAgent
language
languages
onLine
doNotTrack
geolocation
mediaCapabilities
connection
plugins
mimeTypes
webkitTemporaryStorage
webkitPersistentStorage
getBattery
sendBeacon
getGamepads
javaEnabled
vibrate
userActivation
mediaSession
permissions
registerProtocolHandler
unregisterProtocolHandler
deviceMemory
clipboard
credentials
keyboard
locks
mediaDevices
serviceWorker
39
storage
presentation
bluetooth
usb
requestMediaKeySystemAccess
getUserMedia
webkitGetUserMedia
requestMIDIAccess
Exiting from the loop!
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
1. var stringname="string value";
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
Here, new keyword is used to create instance of string. Let's see the example of
creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
40
document.write(stringname);
</script>
The following example uses the backslash character to escape the single
quote character in a string:
JavaScript Function
41
Less amount of coding: There is no need of writing multiple lines of
code each time to execute a common task hence, it makes the
program compact.
Debugging becomes easier: Codes are divided in to blocks hence
debugging a code becomes easier.
<html>
<head>
<title>JavaScript Function</title>
<script>
function msg()
{
alert("Welcome to PHPTPOINT");
}
</script>
</head>
<body>
<input type="button" onclick="msg()" value="Welcome"/>
</body>
</html>
Output :Output of the above mentioned example is a call button named
‘Welcome’ that displays the message ‘Welcome to PHPTPOINT whenever the
button is clicked.
<html>
42
<head>
<title>JavaScript Function</title>
<script>
function getcube(Integer)
{
alert(Integer* Integer * Integer);
}
</script>
</head>
<body>
<input type="button" value="get value" onclick="getcube(6)"/>
</body>
</html>
Output :The output of the above mentioned example is the clickable button
named ‘get value’ that diplays the cube of the number 6 that equals to 216.
Here, we can use the value returned by the function and it can be used in
the program. Here is one example of a JavaScript Function that returns a
value.
<html>
<head>
<title>JavaScript Function</title>
</head>
<body>
<script>
function getInfo()
{
return "Hello PHPTPOINT! How are Things?";
}
document.write(getInfo());
</script>
</body>
</html>
43
Object Of Javascript Function
Method Description
apply() In order to call a function that contains this value and a single
array of arguments.
call() In order to call a function that contains this value and an argument
list.
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(5,25));
4. </script>
1. <script>
44
2. var pow=new Function("num1","num2","return
Math.pow(num1,num2)");
3. document.writeln(pow(5,3));
4. </script>
**String Methods:**
**Array Methods:**
- `pop()`: Removes the last element from an array and returns that
element.
- `shift()`: Removes the first element from an array and returns that
element.
45
- `unshift()`: Adds one or more elements to the beginning of an array
and returns the new length.
**Math Methods:**
**Object Methods:**
46
manipulating data. You can refer to the JavaScript documentation for
a comprehensive list of methods and their usage.
```javascript
functionName.apply(thisValue, argumentsArray);
```
```javascript
47
function greet(name, age) {
console.log("Hello, " + name + "! You are " + age + " years old.");
var person = {
name: "John",
age: 30,
};
```
The output will be: "Hello, Alice! You are 25 years old."
48
The `bind()` method returns a new function with the specified `this`
value and any additional arguments that are provided. It does not
invoke the original function immediately; instead, it creates a new
function that can be called later.
```javascript
```
- `arg1, arg2, ...`: Optional arguments that are pre-set in the bound
function. These arguments will be appended to any arguments passed
to the bound function when it is called.
```javascript
var module = {
x: 42,
getX: function() {
49
return this.x;
},
};
console.log(boundGetX()); // Output: 42
```
The `bind()` method is useful when you want to create a new function
that has a specific `this` value and pre-set arguments. It allows you to
bind functions to objects or specify fixed arguments in advance, which
can be handy in situations like event handling or when you need to
pass a callback function with predefined context or arguments.
```javascript
function outerFunction() {
50
function innerFunction() {
console.log(outerVariable);
return innerFunction;
```
51
Closures are commonly used in scenarios like creating private
variables, implementing function factories, and handling
asynchronous operations where functions need access to variables
that persist across multiple callback invocations.
52
asynchronous code. By using the `async` keyword before a function,
you can define an asynchronous function that returns a promise.
Inside the async function, you can use the `await` keyword to pause
the execution until a promise is resolved or rejected. This way, you
can write asynchronous code that looks like synchronous code,
making it easier to reason about and maintain.
```javascript
function delay(ms) {
try {
return data;
} catch (error) {
console.error('Error:', error);
throw error;
53
try {
console.log('Fetching data...');
await delay(2000);
console.log('Data:', result);
} catch (error) {
console.error('Error:', error);
process();
```
54
```javascript
var result = confirm("Are you sure you want to delete this item?");
```javascript
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
```
55
Next, another `await` keyword is used to pause the execution until the
Promise returned by the `response.json()` method resolves. This method
converts the response body to JSON. The resulting data is stored in the
`data` variable.
If there are any errors during the process, the code inside the `catch` block
will be executed. The error is logged to the console using `console.error()`
and then re-thrown to propagate the error to the caller.
```javascript
getData()
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
```
Here, we use the `then()` method to handle the resolved value returned by
the Promise. In this case, it will log the retrieved `data` to the console.
If any error occurs during the execution of the async function, the `catch()`
method will be triggered, allowing you to handle and log the error
appropriately.
56
data. Here are some common operations and examples related to arrays in
JavaScript:
JavaScript can be used to perform form validation on the client side,
providing immediate feedback to users and preventing the submission of
invalid data. Here's an example of how to perform form validation using
JavaScript:
HTML:
```html
<form id="myForm" onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<input type="password" id="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
```
JavaScript:
```javascript
function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
57
return false;
}
if (!isValidEmail(email)) {
alert('Please enter a valid email address.');
return false;
}
if (password.length < 6) {
alert('Password should be at least 6 characters long.');
return false;
}
function isValidEmail(email) {
// Regular expression pattern for email validation
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
```
58
In the example above, we have a simple form with three input fields: name,
email, and password. The `validateForm()` function is triggered when the
form is submitted. It retrieves the values entered in the input fields using
`document.getElementById().value`.
If all validation checks pass, `return true` allows the form submission to
proceed.
This is a basic example, and you can customize the validation logic
according to your specific requirements. You can add more validation rules,
validate other types of fields, display validation messages in different ways,
or apply more sophisticated validation techniques using JavaScript.
1. Creating an Array:
```javascript
const fruits = ['apple', 'banana', 'orange'];
const numbers = [1, 2, 3, 4, 5];
```
59
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
```
4. Array Length:
```javascript
console.log(fruits.length); // Output: 3
```
60
console.log(fruits); // Output: ['apple', 'grape', 'orange']
```
These are just a few examples of what you can do with arrays in JavaScript.
Arrays have many more methods and properties, such as `splice()`,
`concat()`, `sort()`, and `map()`, which provide flexibility for handling and
manipulating array data in various ways.
The HTML5 Canvas element is a powerful feature in JavaScript that allows
you to dynamically draw graphics and create interactive visual elements on
a web page. Here's a basic example of how to apply the Canvas element in
JavaScript:
HTML:
61
```html
<canvas id="myCanvas" width="500" height="500"></canvas>
```
JavaScript:
```javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Drawing a rectangle
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
// Drawing a circle
ctx.beginPath();
ctx.arc(200, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
// Drawing text
ctx.font = '24px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello, Canvas!', 250, 250);
```
62
We then proceed to draw different shapes on the canvas. We start by
drawing a red rectangle using the `fillRect()` method, specifying the x and y
coordinates, as well as the width and height.
Next, we draw a blue circle using the `arc()` method. The parameters define
the x and y coordinates of the center, the radius, and the starting and
ending angles.
Finally, we draw text using the `fillText()` method. We specify the text, font
size, and position (x and y coordinates) to render it on the canvas.
These are just a few basic examples of what you can achieve with the
HTML5 Canvas element in JavaScript. You can explore more advanced
features, such as gradients, transformations, image manipulation, and
interactivity, by utilizing the various methods and properties provided by the
Canvas API.
In this example, the `confirm()` function displays a dialog box with the
message "Are you sure you want to delete this item?" The function returns a
Boolean value indicating whether the user clicked "OK" (`true`) or "Cancel"
(`false`). Based on the user's response, you can perform different actions or
make decisions in your code.
```javascript
element = document.querySelector(selector);
63
```
Here, `selector` is a string representing the CSS selector for the element(s)
you want to select. `element` will be assigned the first matching element.
```javascript
// Select the first element with class "example"
var element = document.querySelector('.example');
// Select the first <p> element with class "paragraph" within an element
with ID "container"
var elementWithinContainer = document.querySelector('#container
.paragraph');
```
```javascript
elementList = document.querySelectorAll(selector);
```
The `selector` parameter is the CSS selector for the element(s) you want to
select, and `elementList` will be assigned the NodeList containing all
matching elements.
```javascript
64
// Select all elements with class "example"
var elements = document.querySelectorAll('.example');
// Select all <p> elements with class "paragraph" within an element with ID
"container"
var elementsWithinContainer = document.querySelectorAll('#container
.paragraph');
```
65