0% found this document useful (0 votes)
2 views49 pages

Module 3 Javascript

This document provides an introduction to JavaScript, covering its purpose, syntax, and how to include it in HTML files. It explains variables, data types, operators, functions, and events in JavaScript, along with examples for clarity. The document serves as a comprehensive guide for beginners to understand the basics of JavaScript programming.

Uploaded by

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

Module 3 Javascript

This document provides an introduction to JavaScript, covering its purpose, syntax, and how to include it in HTML files. It explains variables, data types, operators, functions, and events in JavaScript, along with examples for clarity. The document serves as a comprehensive guide for beginners to understand the basics of JavaScript programming.

Uploaded by

Shreyash Gavali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 3

JavaScript & AJAX


Class: SE
Sem: IV
Subject: MDM- Introduction to web Lab
What is Javascript?

• JavaScript is a programming language initially designed to interact


with elements of web pages.
• JavaScript allows you to add interactivity to a web page. It enhance
a web page’s functionality, such as validating forms, creating
interactive maps, and displaying animated charts.
• The JavaScript engine is a component of web browsers responsible
for interpreting and executing JavaScript code. It includes a parser
to analyze the code, a compiler to convert it into machine code, and an
interpreter to run the compiled code.
• When JavaScript is used on a web page, it is executed in web browsers,
serving as a client-side language.
What is Javascript?
• JavaScript code is written inside <script> ... </script> tags in an
HTML page.
• These tags can be placed anywhere in the page, but best practice is
to put them inside the <head> section.
• It tells the browser to interpret everything inside as JavaScript
code.
• Attributes:
• language="javascript" (older usage, now obsolete).
• type="text/javascript" (recommended in older HTML versions,
but optional in HTML5 since JavaScript is the default).
example: <script>
[Link]("Hello World!");
</script>
Program to display Hello World using JS.
<html>
<head>
<title> Your first JavaScript program </title>
<head>
<body>
<script language = "javascript" type = "text/javascript">
[Link]("Hello World!")
</script>
</body>
</html>
How to include JS in HTML File?

1. Inline JavaScript in HTML


You can write JavaScript directly inside a <script> tag in your
HTML file.

<html><body>
<h1>Hello World</h1>

<script>
alert("This is inline JavaScript!");
</script>

</bdy></html>
How to include JS in HTML File?

2. External JavaScript in HTML


You can write JavaScript as a separate file with extension
as .js and include it in html using src attribute of <script>

<html><body>
<button onclick="display()">Click me</button>
<script src="[Link]"></script>
</body>
</html></bdy></html>
function display() {
[Link] alert("Hello from external JS file!");
}
Variables (Dynamic Values)

A variable is a label that references a value like a number or string.


Before using a variable, you need to declare it.
variables can be declared using var, let, or const
1. var (Legacy) : Oldest form of variable declaration. Function-scoped
or global-scoped.
2. let (Modern): Block-scoped (only accessible inside {}).Cannot be re-
declared in the same scope. Reassignment is allowed.
e.g let b = 20;
b = 25;
3. const (Immutable): Block-scoped like let. Must be initialized at
declaration. Cannot be reassigned.
e.g const second = 4;
second=50; //not allowed
Datatypes in JS
Datatypes in JavaScript

• JavaScript data types define what kind of values a variable can hold
and how those values behave in a program.
• They determine how data is stored in memory .
• Two Types:
1. Primitive Data Type : Simple, immutable values stored
directly in memory, ensuring efficiency in both memory
usage and performance
2. Non-Primitive Data Types: The data types that are derived
from primitive data types are known as non-primitive data
types.
1. Primitive Datatypes .

1. Number
• Represents integers and floating-point numbers.
• Special values: Infinity, -Infinity, NaN (Not-a-Number).

let n1 = 2;
[Link](n1)

let n2 = 1.3;
[Link](n2)

let n3 = Infinity;
[Link](n3)

let n4 = 'something here too' / 2;


[Link](n4)
1. Primitive Datatypes .

2. String
Sequence of characters enclosed in quotes.
Supports double quotes, single quotes, and template literals
(backticks with interpolation).

let s1 = "Hello There";


let s2 = 'Single quotes work fine';
let s3 = `can embed ${s1}`;
3. Boolean
Logical values: true or false.
e.g let b1 = true;
let b2 = false;
1. Primitive Datatypes .

4. Null
Special type with only one value: null.
Represents “nothing” or an empty value.
3. Undefined
A variable that has been declared but not initialized
with a value is automatically assigned the undefined value. It
means the variable exists, but it has no value assigned to it.
let a;
[Link](a); // undefined
2. Non-Primitive Datatypes .

1. Object
JavaScript objects are key-value pairs used to store data, created with {}
or the new keyword. They are fundamental as nearly everything in
JavaScript is an object.

let gfg = {
type: "Company",
location: "Noida"
}
[Link](gfg)
[Link]([Link])
2. Arrays
An Array is a special kind of object used to store an
ordered collection of values, which can be of any data
type.

let a1 = [1, 2, 3, 4, 5];


[Link](a1);

let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];


[Link](a2);
3. Function
A function in JavaScript is a block of reusable code designed to
perform a specific task when called.
// Defining a function to greet a user
function greet(name) { return "Hello, " + name + "!"; }
// Calling the function
[Link](greet("Ajay"));

5. Regular Expression
A RegExp (Regular Expression) in JavaScript is an object used to
define search patterns for matching text in strings.
4. Date Object
The Date object in JavaScript is used to work with dates and
times, allowing for date creation, manipulation, and formatting.

// current date and time


let currentDate = new Date();

// Displaying the current date and time


[Link](currentDate);
Operators in JS

operators are symbols or keywords used to perform operations on


values and variables.
Types of Operators:
1. Arithmetic Operator
2. Logical Operator
3. Assignment Operator
4. Comparison Operator
5. Bitwise Operator
6. Ternary/Conditional Operator
7. Typeof Operator
8. Unary Operator
9. Comma Operator
1. Arithmetic Operators in JS

+ adds two numbers.


- subtracts the second number from the first.
* multiplies two numbers.
/ divides the first number by the second.

Example:

const sum = 5 + 3; // Addition


const diff = 10 - 2; // Subtraction
const p = 4 * 2; // Multiplication
const q = 8 / 2; // Division
[Link](sum, diff, p, q);
2. Assignment Operators in JS (=)
used to assign values to variables. They can also perform operations like
addition or multiplication while assigning the value.
+= adds the value to the right operand to a variable and assigns the
result to the variable.
-= subtracts the value of the right operand from a variable and
assigns the result to the variable.* multiplies two numbers.
*= multiplies the value of the right operand from a variable and
assigns the result to the variable.
let n = 10;
n += 5;
Example:
n *= 2;
[Link](n); //displays 30
3. Comparison Operators in JS
Compare two values and return a boolean (true or false). They are useful
for making decisions in conditional statements.

[Link](10 > 5); //true


[Link](10 === "10"); //false
Example:
4. Logical Operators in JS
used to perform the logical operations that determine the equality or
difference between the values.

Example: const a = true, b = false;


[Link](a && b); // Logical AND
[Link](a || b); // Logical OR
5. Conditional Operators in JS (?:)
evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.
The conditional operator is also known as the ternary operator.

var variable = condition ? exp1 : exp2 ;

condition − It is a conditional statement.


exp1 − If the condition is trute, control flow executes the exp1 expression.
exp2 − If the condition is false, control flow executes the exp2 expression.
Program to find Largest among two Numbers using ternary operator

<html>
<body>
<div id="output"></div>
<script>
var num1 = 90;
var num2 = 67;
var res = num1 > num2 ? num1: num2;
[Link]("output").innerHTML = "Largest Number is :" + res;
</script>
</body>
</html>
6. Unary Operator/Increment -Decrement Operator
• The unary increment operator (++) adds 1 to its operand's value and
evaluates to the updated value.
• The unary decrement operator (--) subtracts 1 from its operand's value
and evaluates it to the updated value.

• Postfix inc/dec (x++ /x--): In postfix form, the current value of the
variable is used in the expression, and then the variable's value is
incremented/decremented by 1.
• Prefix inc/dec (++x/--x): In prefix form, the variable's value is first
incremented/ decremented by 1, and then the updated value is used
in the expression.
let x = 8;
let y = x--;
[Link](x); //displays 7
[Link](y); // displays 8

x = 8;
y = --x;
[Link](x); //displays 7
[Link](y); //displays 7
7. typeof Operator
• The typeof operator in JavaScript is a unary operator used to get the data
type of a particular variable.
• It is placed before its single operand, which can be of any type.
• Its returns a string value indicating the data type of its operand.
JavaScript contains primitive and non-primitive data types.

typeof (operand);
[Link](typeof (10)); // returns 'number'
[Link](typeof ('Hello World')); // returns 'string'
[Link](typeof (true)); // returns 'boolean'
8. Comma Operator
• Evaluates the multiple expression from left to right.
• You can use the resultant value of the left expression as an input of the
right expression.
• After evaluating all expressions, it returns the resultant value of the
rightmost expression.

var answer = (exp1, exp2, exp3, ex4, ...);


let a = 5;
let ans = (a = 9, a++, a += 2);
[Link]( "The value of the ans variable is: " + ans);
9. Bitwise Operators in JS
perform operations on the integer values at the binary level.
Explain Function In Javascript.

• Functions are reusable code blocks designed to perform


a particular task.
• Functions are executed when they are called or invoked.
• Functions are fundamental in all programming.
• Functions help you to:
1. Reuse code (write once, run many times)
2. Organize code into smaller parts
3. Make code easier to read and maintain
Syntax of function definition: Syntax of function call:
function name( p1, p2, ... ) name(value1,value2);
{
// code to be executed OR

} let variable = name(value1,value2);

Example Example
function multiply(a, b)
{ let result = multiply (20,5);
return a * b;
}
return statement is used to send a value out of a function.
function definition:
Function Call:
Parameters vs. Arguments

Parameters Parameters are the names


listed in the function
definition.
function multiply(a, b)
{
return a * b;
}
Arguments
Arguments are the real values
passed to, and received by the
function.
let result = multiply (20 , 5);
//Program to perform addition of two number using function (Method 1)

function addNumbers(num1, num2) //function definition


{
let result = num1 + num2;
[Link](“Sum: “ + result);
}

addNumbers(5, 4); //function call with two argument


//Program to perform addition of two number using function (Method 2)
<html>
<body>
<input type="number" placeholder="Enter first number" id="t1">
<input type="number" placeholder="Enter second number" id="t2">
<button onclick="addNumbers()">ADD</button>
<p id="one"></p>
<script>
function addNumbers()
{
let num1=parseInt([Link]("t1").value);
let num2=parseInt([Link]("t2").value);
let result = num1 + num2;
[Link]("one").innerText="Sum:"+result;
}
</script></body></html>
Output
Program to hide html element
<!DOCTYPE html>
<html>
<body>
<p id="myPara">
This paragraph that will be hide when you click the button.
</p>
<button onclick="hideParagraph()">Hide Paragraph</button>
<script>
// Function to hide the paragraph
function hideParagraph() {
const para = [Link]("myPara");
[Link] = "none"; // Hides the element
}
</script>

</body>
</html>
Explain Arrow Function In Javascript.

• Arrow Functions allow a shorter syntax for function


expressions.
• You can skip the function keyword, the return keyword,
and the curly brackets.
// Regular function
function add(a, b)
{
return a + b;
}
both are same

let result =add(2,6);


[Link](result);
// Arrow function
const add = (a, b) => a + b;

let result=add(2,6);
[Link](result);
Explain Events in JS
Events are things that happen to HTML elements.
Examples of events:
• An HTML button is clicked
• A web page has finished loading
• The mouse moves over an element
• A keyboard key is pressed
• An HTML input field is changed

When JavaScript is used in HTML pages, JavaScript can react on events.


JavaScript lets you execute code when events are detected.
Syntax:

Method1:

<element eventhandler='some JavaScript'>


Method2:
<element eventhandler=”some JavaScript”>

<button onclick="alert('Button clicked!')"> Add </button>


1. Windows Events in JavaScript

These events occur globally, so they are associated with web pages and
windows.
<!DOCTYPE html>
<html>
<head>
<title>Window Event Example</title>
</head>
<body onload="showMessage()">
<script>
function showMessage() {
alert("Page has fully loaded!");
}
</script>

</body>
</html>
2. Mouse Event
Mouse Events happen when the user interacts with the mouse.
<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert("Button clicked successfully!");
}
</script>
3. Keyboard Events in JavaScript
When the keys present in the keyboard move, we call them keyboard events, such as
keypress, keydown and keyup. These different events may look the same, but their
behavior is distinct from each other.
<input type="text" onkeydown="showMessage()" placeholder="Press any key">

<script>
function showMessage() {
alert("A key was pressed!");
}
</script>
4. Form Events
<form onsubmit="showMessage()">
<input type="text" placeholder="Enter your name" required>
<button type="submit">Submit</button>
</form>

<script>
function showMessage() {
alert("Form submitted successfully!");
}
</script>

You might also like