0% found this document useful (0 votes)
18 views22 pages

WT JAVASCRIPT Notes

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

WT JAVASCRIPT Notes

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

ARMY BURN HALL COLLEGE FOR GIRLS

Course Title: Web Technologies Course code: CS4304

JAVASCRIPT

Introduction to JavaScript
JavaScript is the most powerful and versatile web programming language. It is used for
making the websites interactive. JavaScript helps us add features like animations, interactive
forms and dynamic content to web pages.

JavaScript is a programming language used for creating dynamic content on websites. It


is a lightweight, cross-platform and single-threaded programming language. JavaScript is
an interpreted language that executes code line by line providing more flexibility. It is a
commonly used programming language to create dynamic and interactive elements in web
applications.

JavaScript is an essential programming language for web developers to learn as it grows


rapidly. JavaScript is responsible for behaviour of the web pages.

Key Features of JavaScript:

1. Versatility: JavaScript can be used to develop websites, games, mobile apps, and
more.

2. Client and Server-Side: With frameworks like Node.js and Express.js, JavaScript is
now used for building server-side applications.

3. End-to-End Solutions: JavaScript enables developers to create complete solutions


for various problems.

4. Constant Evolution: JavaScript continually evolves with new features and standards.

5. Vibrant Community: A large community of users and mentors actively contributes


to JavaScript’s growth.
ARMY BURN HALL COLLEGE FOR GIRLS

Applications of JavaScript

I. Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
II. 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.
III. It uses Application Programming Interfaces (APIs) that provide extra power to the
code. The Electron and React are helpful in this department.
IV. Server Applications: With the help of Node.js, JavaScript made its way from client
to server and Node.js is the most powerful on the server side.
V. Games: Not only in websites, but JavaScript also helps in creating games for leisure.
The combination of JavaScript and HTML 5 makes JavaScript popular in game
development as well. It provides the EaseJS library which provides solutions for
working with rich graphics.
VI. Machine Learning: This JavaScript ml5.js library can be used in web development
by using machine learning.
VII. Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating
mobile applications. This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for different
operating systems. We do not require to write code for different systems. Write once
use it anywhere!

Limitations of JavaScript

1. Security risks: JavaScript can be used to fetch data using AJAX or by manipulating
tags that load data such as <img>, <object>, <script>. These attacks are called cross-
site script attacks. They inject JS that is not part of the site into the visitor’s browser
thus fetching the details.
2. Performance: JavaScript does not provide the same level of performance as offered
by many traditional languages as a complex program written in JavaScript would be
ARMY BURN HALL COLLEGE FOR GIRLS
comparatively slow. But as JavaScript is used to perform simple tasks
in a browser, so performance is not considered a big restriction in its use.
3. Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, and client and
server-side objects otherwise it would be difficult for them to write advanced scripts
using JavaScript.
4. Weak error handling and type checking facilities: It is a weakly typed language as
there is no need to specify the data type of the variable. So wrong type checking is not
performed by compile

How to Link JavaScript File in HTML


JavaScript can be added to HTML file in two ways:
 Internal JS: We can add JavaScript directly to our HTML file by writing the code
inside the <script> tag. The <script> tag can either be placed inside the <head> or the
<body> tag according to the requirement.
 External JS: We can write JavaScript code in another files having an extension.js and
then link this file inside the <head> tag of the HTML file in which we want to add this
code.

Syntax:

<script>
// JavaScript Code
</script>

Example:

<!DOCTYPE html>
<html lang="en">

<head>
<title>
Basic Example to Describe JavaScript
</title>
</head>

<body>

<!-- JavaScript code can be embedded inside


head section or body section -->
<script>
ARMY BURN HALL COLLEGE FOR GIRLS
console.log("Welcome to MY WEBSITE");
</script>
</body>

</html>

Is JavaScript Compiled or Interpreted or both?

JavaScript is both compiled and interpreted. In the earlier versions of JavaScript, it used
only the interpreter that executed code line by line and shows the result immediately. But
with time the performance became an issue as interpretation is quite slow. Therefore, in the
newer versions of JS, probably after the V8, the JIT compiler was also incorporated to
optimize the execution and display the result more quickly. This JIT compiler generates a
bytecode that is relatively easier to code. This bytecode is a set of highly optimized
instructions.

JavaScript Values
There are two types of values defined in JavaScript Syntax:
 Fixed Values: These are known as the literals.
 Variable values: These are called variables.

JavaScript Literals
Syntax Rules for the JavaScript fixed values are:
 JavaScript Numbers can be written with or without decimals.
 JavaScript Strings are text that can be written in single or double quotes.

JavaScript Variables
A JavaScript variable is the simple name of the storage location where data is stored. There
are two types of variables in JavaScript which are listed below:
 Local variables: Declare a variable inside of a block or function.
 Global variables: Declare a variable outside function or with a window object.

Variables are used to store data in JavaScript. Variables are used to store reusable values.
The values of the variables are allocated using the assignment operator(“=”).

JavaScript Assignment Operator


JavaScript assignment operator is equal (=) which assigns the value of the right-hand
operand to its left-hand operand.
y = "JAVASCRIPT"
ARMY BURN HALL COLLEGE FOR GIRLS

JavaScript Identifiers
JavaScript variables must have unique names. These names are called Identifiers.
Basic rules to declare a variable in JavaScript:
 These are case-sensitive
 Can only begin with a letter, underscore(“_”) or “$” symbol
 It can contain letters, numbers, underscore, or “$” symbol
 A variable name cannot be a reserved keyword.

JavaScript is a dynamically typed language so the type of variables is decided at runtime.


Therefore there is no need to explicitly define the type of a variable. We can declare variables
in JavaScript in three ways:

1. JavaScript var keyword

2. JavaScript let keyword

3. JavaScript const keyword

Variable Description Example

Used to initialize to value, redeclared and its value can be


var var x= value;
reassigned.

let Similar to var but is block scoped let y= value;

const Used to declare a fixed value that cannot be changed. const z= value;

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Variables</h1>
ARMY BURN HALL COLLEGE FOR GIRLS

<p>In this example, x, y, and z are variables.</p>

<script>

var x = 5;

var y = 6;

var z = x + y;

document.write(z);

</script>

/body>

</html>

___________________________________________________________________________

<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Variables</h1>

<p>Strings are written with quotes.</p>

<p>Numbers are written without quotes.</p>

<p id="demo"></p>

<script>

const pi = 3.14;

let person = "John Doe";

let answer = 'Yes I am!';

document.write(pi+ "<br>");
ARMY BURN HALL COLLEGE FOR GIRLS

document.write(person + "<br>");

document.write(answer + "<br>");

</script>

</body>

</html>

___________________________________________________________________________
Value = undefined

In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined.

JavaScript Operators

JavaScript operators are symbols that are used to compute the value or in other words, we
can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute
the value, and Assignment operators ( =, +=, %= ) are used to assign the values to variables.
JavaScript operators are used to perform different types of mathematical and logical
computations.
Examples:
The Assignment Operator = assigns values
The Addition Operator + adds values
The Multiplication Operator * multiplies values
The Comparison Operator > compares values

Types of JavaScript Operators


There are different types of JavaScript operators:
 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 String Operators
 Logical Operators
 Bitwise Operators
 Ternary Operators
 Type Operators
ARMY BURN HALL COLLEGE FOR GIRLS
Example: This example shows the use of javascript operators.
JavaScript

// Variable Declarations
let x, y, sum;

// Assign value to the variables


x = 3;
y = 23;

// Use arithmetic operator to


// add two numbers
sum = x + y;

console.log(sum);

Output

26

JavaScript Expressions
Javascript Expression is the combination of values, operators, and variables. It is used to
compute the values.
Example: This example shows a JavaScript expression.
// Variable Declarations
let x, num, sum;

// Assign value to the variables


x = 20;
y = 30\

// Expression to divide a number


num = x / 2;
// Expression to add two numbers
sum = x + y;

console.log(num + "\n" + sum);

Output

10

50
ARMY BURN HALL COLLEGE FOR GIRLS
JavaScript Keywords
The keywords are the reserved words that have special meanings in JavaScript.
// let is the keyword used to
// define the variable
let a, b;
// function is the keyword which tells
// the browser to create a function
function(){};

JavaScript Comments
The comments are ignored by the JavaScript compiler. It increases the readability of code.
It adds suggestions, Information, and warning of code. Anything written after double
slashes // (single-line comment) or between /* and */ (multi-line comment) is treated as a
comment and ignored by the JavaScript compiler.
Example: This example shows the use of javascript comments.
JavaScript

// Variable Declarations
let x, num, sum;

// Assign value to the variables


x = 20;
y = 30

/* Expression to add two numbers */


sum = x + y;

console.log(sum);

Output

50

JavaScript Data Types


JavaScript provides different datatypes to hold different values on variables. JavaScript is a
dynamic programming language, which means do not need to specify the type of variable.
There are two types of data types in JavaScript.
 Primitive data type
ARMY BURN HALL COLLEGE FOR GIRLS
 Non-primitive (reference) data type
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.
1. Number: JavaScript numbers are always stored in double-precision 64-bit binary
format IEEE 754. Unlike other programming languages, you don’t need int, float, etc to
declare different numeric values.
2. String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks”
etc.
3. Boolean: Represent a logical entity and can have two values: true or false.
4. Null: This type has only one value that is null.
5. Undefined: A variable that has not been assigned a value is undefined.
6. Symbol: Symbols return unique identifiers that can be used to add unique property keys
to an object that won’t collide with keys of any other code that might add to the object.

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.
Object: It is the most important data type and forms the building blocks for modern
JavaScript. We will learn about these data types in detail in further articles.
In JavaScript, understanding the difference between global and local variables is important
for writing clean, maintainable, and error-free code. Variables can be declared with
different scopes, affecting where and how they can be accessed.
// It store string data type
let txt = "hello";

// It store integer data type


let a = 5;
let b = 5;

// It store Boolean data type


(a == b )

// To check Strictly (i.e. Whether the datatypes


// of both variables are same) === is used
(a === b)---> returns true to the console

// It store array data type


let places= ["College", "Computer", "Hello"];

// It store object data (objects are


// represented in the below way mainly)
let Student = {
firstName: "Johnny",
ARMY BURN HALL COLLEGE FOR GIRLS
lastName: "Diaz",
age: 35,
mark: "blueEYE"
}

JavaScript Functions
JavaScript functions are the blocks of code used to perform some particular operations.
JavaScript function is executed when something calls it. It calls many times so the function
is reusable.
Syntax:
function functionName( par1, par2, ....., parn ) {
// Function code
}
The JavaScript function can contain zero or more arguments.
Example: This example shows the use of Javascript functions.
JavaScript

// Function definition
function func() {

// Declare a variable
let num = 45;
// Display the result
console.log(num);
}
// Function call
func();

Output

45

JavaScript Case Sensitive


JavaScript Identifiers are case-sensitive.
Example: Both the variables firstName and firstname are different from each other.
JavaScript
ARMY BURN HALL COLLEGE FOR GIRLS
let firstName = "JAVA";
let firstname = 100;

console.log(firstName);
console.log(firstname);

Output

JAVA
100

JavaScript Camel Case


In JavaScript Camel case is preferred to name a identifier.
Example:
let firstName
let lastName

JavaScript Output
JavaScript provides different methods to display output, such as console.log(), alert(),
document.write(), and manipulating HTML elements directly. Each method has its specific
use cases, whether for debugging, user notifications, or dynamically updating web content.
Here we will explore various JavaScript output methods, demonstrating how and when to use
them effectively.
There are primarily multiple distinct methods for displaying output in JavaScript. Although
there are other methods for output display, they are not advisable, so it is recommended to
refrain from using alternative output approaches.

1. JavaScript innerHTML Property


The innerHTML property is used with the HTML element. JavaScript can be used to select
an element using the document.getElementById(id) method , and then use the innerHTML
property to display the output on the specified element (selected element).
Syntax:
document.getElementById("id").innerHTML;

Example: The document.getElementById(id) method with innerHTML property is used to


display the output.
html

<!DOCTYPE html>
<html lang="en">
ARMY BURN HALL COLLEGE FOR GIRLS
<head>
<title>JavaScript Output</title>
</head>

<body>
<h2>
Display Output using innerHTML Property
</h2>

<p id="GFG"></p>

<!-- Script to use innerHTML -->


<script>
document.getElementById("GFG").innerHTML
= "Hello!";
</script>
</body>

</html>

2. JavaScript console.log() Method

The console.log() method is used for logging messages to the console. It is a debugging
tool available in most web browsers. It is used during development to output information
about the state of the program.
Syntax:
console.log();
Example: This example uses the console.log() property to display data.

<!DOCTYPE html>
<html lang="en">

<head>
<title>JavaScript Output</title>
</head>

<body>
<h2>
Display Output using console.log() Method
</h2>

<!-- Script to use console.log() -->


<script>
ARMY BURN HALL COLLEGE FOR GIRLS
console.log("Hello!");
</script>
</body>

</html>

3. JavaScript document.write() Method

To use the document.write(), simply call this method and provide the content you want to
be written to the document. This method is often used for directly adding content to the
HTML document while it is being parsed.

Note: If we use document.write() after the HTML document is loaded, it will delete all
existing HTML.

Syntax:
document.write();

Example: The document.write() method display the output.


html

<!DOCTYPE html>
<html lang="en">

<head>
<title>JavaScript Output</title>
</head>

<body>
<h2>
Display Output using document.write() Method
</h2>

<!-- Script to uses document.write() -->


<script>
document.write("Hello Everyone!");
</script>
</body>

</html>

4. JavaScript window.alert() Method


ARMY BURN HALL COLLEGE FOR GIRLS
The window.alert() method is used to display an alert box with a specified
output (or message) and an OK button.

Syntax:

window.alert();

Note: We can skip the window keyword in this method.


Example: The window.alert() method display the output data.
html

<!DOCTYPE html>
<html lang="en">

<head>
<title>JavaScript Output</title>
</head>

<body>
<h2>
Display Output using window.alert() Method
</h2>

<!-- Script to use window.alert() -->


<script>
window.alert("Good Morning!");
</script>
</body>

</html>

5. JavaScript window.print() Method

The window.print() method is used to open the browser’s print dialog, allowing the user to
print the current page. JavaScript does not contain any default print object or methods.

Syntax:
window.print();

Example: The window.print() method prints the current page.


HTML

<!DOCTYPE html>
<html>
ARMY BURN HALL COLLEGE FOR GIRLS
<body>
<h2>JavaScript window.print() Method</h2>

<button onclick="window.print()">
Click here to Print
</button>
</body>

</html>

6. JavaScript window.prompt() Method

The window.prompt() method is used to display a dialog box that prompts the user input. It
returns the text entered by the user as a string. It doesn’t display output directly but captures
user input.

Note: This method is not used for output, it only use to take input from user.

Syntax:

window.prompt();

Example: The window.prompt() method to take user input and display the entered data
used alert() method.

<!DOCTYPE html>
<html lang="en">

<head>
<title>JavaScript Output</title>
</head>

<body>
<h2>
Display prompt box for user input
</h2>

<script>
let userInput = window.prompt("Please Enter your Input");

if (userInput !== null) {


window.alert("Hello, " + userInput + "!");
} else {
ARMY BURN HALL COLLEGE FOR GIRLS
window.alert("You clicked Cancel or closed the prompt.");
}
</script>
</body>

</html>
Output:

JavaScript output methods is crucial for interactive and dynamic web applications. By using
console.log() for debugging, alert() for alerts, document.write() for writing directly to the
document, and manipulating HTML elements, you can control and present data efficiently.
Understanding these methods enhances your ability to create responsive and user-friendly
web applications. Start experimenting with these techniques to improve your JavaScript
skills and enhance your web development projects.

CONDITIONAL STATEMENTS

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.

if(expression){
//content to be evaluated
}

Let’s see the simple example of if statement in javascript.


<script>
var a=20;
if(a>10){
ARMY BURN HALL COLLEGE FOR GIRLS
document.write("value of a is greater than 10");
}
</script>
Output of the above example
value of a is greater than 10

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Output of the above example
a is even number

JavaScript If...else if statement


It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
ARMY BURN HALL COLLEGE FOR GIRLS
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Simple example of if else if statement in javascript.


<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

Output of the above example


a is equal to 20

JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions. It is
just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}
ARMY BURN HALL COLLEGE FOR GIRLS
Let’s see the simple example of switch statement in javascript.

<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output of the above example
B Grade

The switch statement is fall-through i.e. all the cases will be evaluated if you don't use
break statement.

JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

1) JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.

for (initialization; condition; increment)


{
code to be executed
}
ARMY BURN HALL COLLEGE FOR GIRLS
Let’s see the simple example of for loop in javascript.

< script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

Output:

1
2
3
4
5

2) JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.

while (condition)
{
code to be executed
}
Let’s see the simple example of while loop in javascript.

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

Output:

11
12
13
14
15
ARMY BURN HALL COLLEGE FOR GIRLS
3) JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition is true or false.
The syntax of do while loop is given below.

do{
code to be executed
}while (condition);

Let’s see the simple example of do while loop in javascript.

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

Output:

21
22
23
24
25

4) JavaScript for in loop


The JavaScript for in loop is used to iterate the properties of an object. We will discuss
about it later.

You might also like