Unit 1
Unit 1
Client-side scripting refers to scripts that are executed on the user's browser
rather than on the server.
JavaScript is the most commonly used client-side scripting language.
It enables dynamic content updates, interactive features, and improved user
experience without requiring a page reload.
Need of Client-Side Scripting Language
Interactivity:
Allows for dynamic content and user interaction without page reloads.
Performance:
Reduces server load and latency by handling operations on the client side.
Enhanced User Experience:
Provides immediate feedback and updates.
Form Validation:
Validates user input before sending data to the server, reducing errors.
Java Script
Java script is used to create client-side dynamic web pages.
It was created by Brendan Eich while working for Netscape Communications
Corporation and was first released in 1995.
Java script is an object-based scripting language which is lightweight and
cross platform.
Java script is a translated language because its translator (embedded in the
browser) is responsible for translating the java script code to the web browser.
Java script was designed to add interactivity to HTML pages.
A java script is usually embedded direct in HTML pages.
All major browsers like Netscape and internet explorer, support java script.
Java script was developed for Netscape, Netscape 2 was the first browser to
run java script.
After Netscape the Mozilla foundation continued to develop java script for the
Firefox browser.
JavaScript is an essential tool for web developers because it enables dynamic
content, interactivity, and a better user experience on websites.
Advantages of java script
Client-Side Execution
Speed:
JavaScript is executed directly in the user's browser, which reduces the load
on the server and speeds up the user interface.
Immediate Feedback:
Users get instant responses to their actions without the need for page reloads.
Versatility and Flexibility
Cross-Platform Compatibility:
JavaScript works on all major browsers and platforms, making it highly
versatile.
Wide Range of Uses:
It can be used for both client-side (frontend) and server-side (backend)
development with frameworks like Node.js.
Rich User Interfaces
Interactivity:
JavaScript enables dynamic content updates, animations, and interactive
elements, enhancing user engagement.
Rich Interfaces:
Libraries like jQuery and frameworks like React, Angular, and Vue.js allow
developers to create sophisticated and responsive user interfaces.
Community
Active Community:
A large, active community means abundant resources, tutorials, and support,
making it easier to learn and troubleshoot.
Ease of Learning and Use
Simple Syntax:
JavaScript’s syntax is relatively easy to learn, making it accessible for
beginners.
Flexibility:
It allows both procedural and object-oriented programming styles, catering to
different development preferences.
Real-Time Applications
Real-Time Updates:
JavaScript is ideal for real-time applications like chat apps, online gaming,
and live updates due to its ability to handle asynchronous operations.
Server-Side Development with Node.js
Unified Development:
Using JavaScript for both client-side and server-side development streamlines
the development process and enhances consistency.
Efficient Performance:
Node.js allows for high-performance server-side applications due to its non-
blocking, event-driven architecture.
Client-Side Dependency:
JavaScript runs on the client's browser, which can be a disadvantage if the
user's device has limited processing power or if JavaScript is disabled.
Dependency on the Internet:
Many JavaScript frameworks and libraries are hosted on CDNs (Content
Delivery Networks). If these resources are not available (e.g., due to network
issues), the functionality of the web application can be affected.
Cannot create database application:
By using java script, you cannot create the web site to the database. For this
you need to use server-side scripting.
Browser compatibility issues:
Not all browsers support the java script codes. The browser may support java
script as a whole, but may not support the codes or lines of codes written in
java script and may interpret differently.
JavaScript are crucial for writing clean, readable, and maintainable code.
These practices help developers understand and collaborate on codebases
more effectively.
formatting of JavaScript code is essential for readability, maintainability
developers. Below are key formatting guidelines, along with an example that
illustrates these principles.
Coding conventions are style guidelines for programming.
Coding conventions can be documented rules for teams to following or just be
your individual coding practice. Such as
Naming Conventions
Variables and Functions:
Use camelCase for naming variables and functions. Start with a lowercase
letter and capitalize the first letter of each subsequent word.
Constants:
Use UPPER_CASE with underscores for constant values that do not change.
let userName = "JohnDoe"; // Variable
function calculateTotal(price, quantity) { // Function
return price * quantity;
}
const MAX_USERS = 100; // Constant
Indentation and Spacing
Use consistent indentation, typically 2 or 4 spaces per level. Avoid using tabs.
Add spaces around operators (=, +, -, etc.) and after commas to improve
readability.
let a = 5;
let b = 10;
let sum = a + b;
Semicolons
Use semicolons to terminate statements.
let greeting = "Hello, World!";
console.log(greeting);
Curly Braces and Blocks
Place the opening curly brace { on the same line as the statement and the
closing brace } on a new line.
Always use curly braces for blocks, even for single-line statements, to avoid
errors during maintenance.
if (isAuthenticated) {
console.log("User is authenticated");
} else {
console.log("User is not authenticated");
}
Commenting
Use single-line comments (//) for short explanations and multi-line comments
(/* ... */) for detailed descriptions. Comment on complex logic and important
sections to clarify the code's purpose.
// Calculate the area of a circle
function calculateArea(radius) {
/*
The formula for the area of a circle is:
area = π * radius^2
*/
return Math.PI * radius * radius;
}
Consistent Function Expressions
Use arrow functions (=>) for anonymous functions and callbacks when
appropriate, especially for simple functions.
"use strict";
function myFunction() {
let x = 10;
// Code here
Example
<script src="main.js"></script>
JavaScript can be embedded direct within HTML using the <script> tag.
It's a common practice to place script tags at the end of the <body> tag to
ensure that the DOM is fully loaded before the script runs.
<script>
NoScript Tag
The <noscript> tag defines alternative content for users who have disabled
JavaScript in their browsers.
It ensures that important information is still accessible.
The <noscript> element can be used in both <head> and <body>.
When used inside the <head> element: <noscript> must contain only <link>,
<style>, and <meta> elements.
<noscript>
</noscript>
Operators
let x = 5;
let y = 10;
Control Structures
Control structures like if, for, while, and switch are used to control the flow of
execution in JavaScript.
They allow developers to make decisions, execute code conditionally, and
repeat tasks efficiently.
The primary control structures in JavaScript include conditional statements,
loops, and branching statements.
Conditional statements execute code based on specific conditions.
} else {
1. If statement
if (condition) {
Example
}
2. if...else Statement
The if...else statement executes one block of code if the condition is true, and
another block if the condition is false.
Syntax
if (condition) {
} else {
Example
if (condition) {
} else {
if (condition1) {
} else if (condition2) {
// Code to execute if condition2 is true
} else {
Example
console.log("Grade: A");
console.log("Grade: B");
console.log("Grade: C");
} else {
console.log("Grade: F");
4. switch Statement
The switch statement executes one block of code among many options, based
on the value of an expression.
It uses case labels to define possible values and default for the fallback
option.
Syntax
switch (expression) {
case value1:
break;
case value2:
break;
// More cases...
default:
Example
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
case 4:
console.log("Thursday");
break;
case 5:
console.log("Friday");
break;
default:
console.log("Weekend");
Loops
1. for loop
The for loop is commonly used to execute a block of code a specific number
of times.
It consists of three parts: initialization, condition, and increment/decrement.
Syntax
Example
for (let i = 0; i < 5; i++) {
2. While loop
The while loop executes a block of code as long as the specified condition is
true.
It is useful when the number of iterations is not known in advance.
Syntax
while (condition) {
// Code to execute repeatedly
Example
let count = 0;
count++;
3. do...while Loop
The do...while loop is similar to the while loop, but it ensures that the code
block is executed at least once, even if the condition is false from the
beginning.
Syntax
do {
// Code to execute repeatedly
} while (condition);
Example
let n = 0;
do {
n++;
4. for…in loop
Example
5. for…of loop
The for...of loop iterates over iterable objects like arrays, strings, maps, etc. It
provides a simpler and more readable syntax for iterating over elements.
Syntax
Example
console.log(number);
Array elements can be accessed using their index, which is the position of the
element in the array.
Example
You can modify an array element by accessing it via its index and assigning a
new value.
Example
console.log(numbers.length); // Outputs: 4
‘push()’: Adds one or more elements to the end of an array and returns the
new length
‘pop()’: Removes the last element from an array and returns that element.
‘shift()’: Removes the first element from an array and returns that element.
console.log(firstNumber); // Outputs: 1
animals.unshift("Elephant");
});
Example
numbers.forEach(function(number) {
});
Function Expression
// Function body
// Code to be executed
};
Example
return a + b;
};
console.log(sum); // Outputs: 5
In this example:
Allow functions
Invoking Functions
function add(a, b) {
return a + b;
function greet(name) {
function isEven(number) {
}
// Calling the functions and logging the return values
Returning an Object
A function can return an object, which can be used to return multiple values as
properties.
Example
return {
name: name,
age: age
};
console.log(person.age); // Output: 25
Returning an Array
A function can return an array, which can be useful for returning multiple
values in a list.
Example
function getScores() {
console.log(scores[0]); // Output: 85
console.log(scores[3]); // Output: 99
Returning a Function
A function can return another function, which can then be called later.
This is a common pattern in functional programming.
Example
return function(number) {
};
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
Returning Undefined
function sayHello() {
console.log("Hello!");
}
// Calling the function
Default Parameters
The rest parameter syntax consists of three dots (...) followed by a parameter
name.
It must be the last parameter in the function's parameter list, as it collects all
remaining arguments passed to the function.
Syntax
function functionName(...restParameter) {
// Function body
Example
function sum(...numbers) {
In this example, the sum function uses rest parameters to collect all arguments
passed to it into an array called numbers. The function then uses the reduce method
to sum up all the numbers.
Date Objects
The ‘Date’ object in JavaScript is used to work with dates and times.
It provides various methods to manipulate and format date and time values.
Such as
To create a Date object with a specific date and time, pass the year, month,
day, hour, minute, second, and millisecond (all optional) as arguments:
Example
console.log(specificDate);
Note
The ‘Date’ object has a variety of methods for getting and setting date and
time values.
a. Getting Date and Time Components
getFullYear(): Returns the four-digit year.
getMonth(): Returns the month (0-11).
getDate(): Returns the day of the month (1-31).
getDay(): Returns the day of the week (0-6), where 0 represents Sunday.
getHours(): Returns the hour (0-23).
getMinutes(): Returns the minutes (0-59).
getSeconds(): Returns the seconds (0-59).
getMilliseconds(): Returns the milliseconds (0-999).
getTime(): Returns the number of milliseconds since January 1, 1970.
Example
const now = new Date();
console.log(now.getFullYear()); // Outputs: 2024
console.log(now.getMonth()); // Outputs: 7 (August)
console.log(now.getDate()); // Outputs: 4
console.log(now.getDay()); // Outputs: 0 (Sunday)
console.log(now.getHours()); // Outputs: 15 (3 PM)
console.log(now.getMinutes()); // Outputs: 30
console.log(now.getSeconds()); // Outputs: 0
console.log(now.getMilliseconds()); // Outputs: 0
console.log(now.getTime()); // Outputs the milliseconds since epoch
Example
Interacting with the browser in JavaScript involves using the Web APIs
provided by the browser.
These APIs allow you to manipulate the DOM (Document Object Model),
handle events, communicate with servers, store data, and more.
Here's an overview of some common interactions.
Java script can change all the HTML elements and attribute in the page
Java script can change all the CSS styles in the page
Java script can remove existing HTML elements and attributes
Java script can add new HTML events in the page
Java script can react to all existing HTML events in the page
Java script can create new HTML events in the page
1. DOM Manipulation
The DOM represents the HTML structure of a webpage.
JavaScript can be used to modify elements, create new ones, or remove them.
Example: Changing the text of an element
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>
<p id="demo">Hello, World!</p>
<button onclick="changeText()">Click me</button>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "You clicked the
button!";
}
</script>
</body>
</html>
2. Local Storage
You can store data locally in the browser using ‘localStorage’ or
‘sessionStorage’.
Example: Using localStorage
<!DOCTYPE html>
<html>
<head>
<title>Local Storage Example</title>
</head>
<body>
<input type="text" id="name" placeholder="Enter your name">
<button onclick="saveName()">Save Name</button>
<p id="greeting"></p>
<script>
function saveName() {
var name = document.getElementById("name").value;
localStorage.setItem("name", name);
document.getElementById("greeting").innerHTML = "Hello, " + name;
}
window.onload = function() {
var name = localStorage.getItem("name");
if (name) {
document.getElementById("greeting").innerHTML = "Hello, " + name;
}
}
</script>
</body>
</html>
3. Window Object
The ‘window’ object represents the browser window.
It has methods for opening new windows, navigating, and controlling the
window.
Example: Opening a new window
<!DOCTYPE html>
<html>
<head>
<title>Window Object Example</title>
</head>
<body>
<button onclick="openWindow()">Open youtube</button>
<script>
function openWindow() {
window.open("https://www.youtube.com", "_blank",
"width=500,height=500");
}
</script>
</body>
</html>
4. Event Handling
JavaScript allows you to handle events like clicks, form submissions,
keypresses, etc.
Example: Handling a button click
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
5. Fetching Data (AJAX)
You can use the fetch API to make HTTP requests to servers and get data
without reloading the page.
Example: Fetching data from an API
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<button id="fetchData">Fetch Data</button>
<div id="output"></div>
<script>
document.getElementById("fetchData").addEventListener("click",
function() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
document.getElementById("output").innerHTML =
JSON.stringify(data);
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
6. Navigator Object
The ‘navigator’ object contains information about the browser and the user's
device.
Example: Getting browser information
<!DOCTYPE html>
<html>
<head>
<title>Navigator Object Example</title>
</head>
<body>
<button onclick="getBrowserInfo()">Get Browser Info</button>
<p id="browserInfo"></p>
<script>
function getBrowserInfo() {
var info = "Browser: " + navigator.appName + "<br>" +
"Version: " + navigator.appVersion + "<br>" +
"Platform: " + navigator.platform + "<br>" +
"User Agent: " + navigator.userAgent;
document.getElementById("browserInfo").innerHTML = info;
}
</script>
</body>
</html>