0% found this document useful (0 votes)
4 views

1724083732-Chapter 3 - JavaScript for Frontend and Backend

This document provides an overview of JavaScript, covering its fundamentals, DOM manipulation, event handling, and ES6/ES7 features. It includes learning objectives, classroom activities, and quizzes to reinforce understanding of key concepts. The content is intended for educational purposes and is sourced from various online resources.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

1724083732-Chapter 3 - JavaScript for Frontend and Backend

This document provides an overview of JavaScript, covering its fundamentals, DOM manipulation, event handling, and ES6/ES7 features. It includes learning objectives, classroom activities, and quizzes to reinforce understanding of key concepts. The content is intended for educational purposes and is sourced from various online resources.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter: 3

JavaScript For Frontend and


Backend
Disclaimer
The content is curated from online/offline resources
and used for educational purpose only.
Learning Objectives
You will learn in this lesson:
• Learn the fundamental of JavaScript
• Create DOM Manipulation using JavaScript
• Understand JavaScript Events
• Implement ES6 features & ES7 features
• Build Interactive Web Applications with API’s.
What is JavaScript
• JavaScript is a high-level, versatile, and widely-used
programming language primarily used for web
development.
• It allows developers to add interactivity, dynamic
content, and various functionalities to websites and
web applications.
• JavaScript is a client-side scripting language, which
means it runs directly in the user's web browser and
interacts with the HTML and CSS of a web page.
• It is the third layer of the layer cake of standard web
technologies, two of which are HTML and CSS

Source : https://www.guru99.com/images/JavaScript/javascript1_1.png
Role of JavaScript in web development
• JavaScript offers lots of flexibility.
• Mobile app development, desktop app development, and game development.
• With JavaScript you can find tons of frameworks and libraries already developed, which can be used directly in
web development.

Source : https://www.guru99.com/images/JavaScript/javascript1_1.png
DOM Manipulation
What is DOM ?

• The DOM is a W3C (World Wide Web Consortium)


standard.
• The DOM defines a standard for accessing
documents:
• "The W3C Document Object Model (DOM) is a
platform and language-neutral interface that allows
programs and scripts to dynamically access and
update the content, structure, and style of a
document."

Source : https://www.w3schools.com/js/js_htmldom.asp
Classroom Activity

Create a DOM structure for Static Portfolio Website Home Page

GitHub Link
DOM Manipulation
Accessing Elements

• To manipulate the DOM, we need to access its


elements. This is commonly done using
the document object
• we can use
getElementById,
getElementsByClassName, Document
getElementsByTagName
• to retrieve specific elements. The returned values
can then be stored in variables for further
manipulation.

Source : https://blog.csdn.net/unruly02/article/details/125408954
DOM Manipulation
Modifying Elements

• Changing HTML Content: Using innerHTML or


textContent properties
• Modifying the style property or using classes to
change the element's appearance.
• Adding or Removing Elements: Using methods like
appendChild(), removeChild(), insertBefore(),
replaceChild().

Source : https://www.freecodecamp.org/news/dom-manipulation-in-javascript/
Introduction to Events, Events Handling
Events
• JavaScript’s interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
• When the page loads, it is called an event.
Introduction to Events, Events Handling
Events continued
• Event-driven programming is when parts of the programming are executed in an unpredictable sequence in
response to specific events.
• Events are objects in JavaScript with case-sensitive names, all of which are lower-case.
Introduction to Events, Events Handling
JavaScript Events

• Onclick - occurs when the user clicks on a link or form element


• Onload - occurs when a page is loaded into the browser (i.E., Opened)
• Onsubmit - occurs when a form's submit button is clicked
• Onfocus - occurs when a user gives input or focus to a form element
Classroom Activity

• Write a function that changes the background color of a <div> element to a


random color when it is clicked.
• Write a function that displays an alert saying "Page Loaded!" when the page is
fully loaded.
• Write a function that changes the border color of an input field to blue when it
receives focus.
• Write a function that validates a form to ensure the input field is not empty
before submitting.

GitHub Link
Introduction to Events, Events Handling
JavaScript Events Listener
• The addEventListener() method of the EventTarget interface sets up a function that will be called whenever
the specified event is delivered to the target.
• You can add many event handlers to one element.
• You can easily remove an event listener by using the removeEventListener() method.11

Source : https://www.scaler.com/topics/javascript/event-handling-in-javascript/
ES6 Features in JavaScript
What is ES6? ES6 stands for ECMAScript 6. ECMAScript was created to standardize JavaScript, and ES6 is
the 6th version of ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

Arrow function
// Traditional or normal function ES5
• Arrow functions allows a short syntax for writing function add(a, b) {
function expressions. return a + b;
• You don't need the function keyword, the return }
keyword, and the curly brackets.
// Arrow function in ES6
const addArrow = (a, b) => a + b;

console.log(add(2, 3)); // 5
console.log(addArrow(2, 3)); // 5
ES6 features in JavaScript
Let & const keyword
function checkScope( )
let and const are used for block-scoped {
variables. let message = "Inside function scope";
if (true) {
let message = "Inside block scope";
let x = 10;
console.log(message); // "Inside block scope"
x = 20; // Allowed
}
console.log(message); // "Inside function scope"
}
checkScope();
//console.log(message); Error here we can't access
outside
ES6 Features in JavaScript
Let & const keyword
function checkScope() {
const keyword same as let keyword. But only one
const message = "Inside function scope";
difference with let keyword is const variables cannot be
if (true) {
reassigned.
const message = "Inside block scope";
const y = 30; console.log(message); // "Inside block scope"
y = 40; // Error: Assignment to constant variable. }
console.log(message); // "Inside function scope"
}
checkScope();
//console.log(message); Error here we can't access
outside
ES6 Features in JavaScript
Object Destructuring with Object Properties //Object destructering with object properties
const person = {
• Object Destructuring in ES6 allows you to extract
properties from objects and assign them to variables fullname: 'Ajay Reddy',
in a more concise and readable way. age: 30,
• Destructuring assignment makes it easy to assign address: {
array values and object properties to variables street: 'Defence Colony',
city: 'Hyderabad',
country: 'INDIA'
}
};
// Basic object destructuring
const { fullname, age, address} = person;
console.log(fullname);
console.log(age);
console.log(address);
ES6 Features in JavaScript
Array Destructuring
Destructuring assignment makes it easy to assign array values and object properties to variables.

// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];

// Destructuring Assignment
let [fruit1, fruit2, fruit3, fruit4] = fruits;

console.log(fruit4);
ES6 Features in JavaScript
Spread Operator
const arr1 = [1, 2, 3];
Spread Operator on Array const arr2 = [4, 5, 6];
const combinedArray = [...arr1, ...arr2];
The spread operator (...) allows an iterable such as an
array or string to be expanded in places where zero or console.log(combinedArray); // [1, 2, 3, 4,
more arguments (for function calls) or elements (for 5, 6]
array literals) are expected. It can also be used to
spread an object’s properties into another object // Copying arrays
const arr3 = [...arr1];
console.log(arr3); // [1, 2, 3]
ES6 Features in JavaScript
Rest Operator
const sum=(...args)=>{
• The rest parameter is an improved way to handle result=0;
function parameters, allowing us to more easily for(let arg of args)
handle various inputs as parameters in a function. {
The rest parameter syntax allows us to represent an result+=arg;
indefinite number of arguments as an array. }
• With the help of a rest parameter, a function can be return result;
called with any number of arguments, no matter how }
it was defined. Rest parameter is added in ES2015 or console.log(sum(10,20,30,40,50));
ES6 which improved the ability to handle parameter.
ES6 Features in JavaScript
Template Literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string
interpolation features with them. Template literals are enclosed by backticks (` `), rather than single or double
quotes.

// example program String interpolation using string literals


const fullname = 'AjayReddy';
const age = 30;
const greeting = `Hello, my name is ${fullname} and I am ${age} years old.`;
console.log(greeting);

//example program on multi-line strings using string literals


const multiLineString = `This is a string
that spans across
multiple lines.`;
console.log(multiLineString);
ES6 Features in JavaScript
Default parameters
function displayInfo(name = 'Guest') {
• Default parameters allow you to initialize function return `Hello, ${name}!`;
parameters with default values if no value or }
undefined is passed.
• This feature simplifies the handling of optional console.log(displayInfo()); //
parameters in functions. Hello, Guest!
console.log(displayInfo('Sachin
Tendulkar'));
ES7 Features in JavaScript
Asynchronous JavaScript
Key Concepts:
Asynchronous JavaScript is a way of handling tasks that
1. Callbacks
take time to complete, such as fetching data from an API,
without blocking the execution of other code. This is 2. Async/Await
crucial for creating smooth and responsive web 3. Promises
applications.

Advantages of Asynchronous Programming


1. Non-blocking: Allows other code to run while waiting for the asynchronous operation to complete.
2. Responsive UI: Keeps the application responsive, especially in a browser environment.
3. Efficient: Makes better use of system resources.
ES7 Features in JavaScript
Difference between Synchronous & Asynchronous

//example on Synchronous //example program on asynchronous with time interval.

console.log(1); console.log(1);
console.log(2); console.log(2);
console.log(3); setTimeout(()=>{
console.log(4); console.log(3);
console.log(5); },3000)
console.log(4);
//output: 1,2,3,4,5 console.log(5);

//output: 1,2, 4,5, 3(after 3sec)


ES7 Features in JavaScript
Callbacks
A callback is a function passed into another function as
an argument, which is then invoked inside the outer
function to complete some kind of routine or action.

Source: https://tutorial.techaltum.com/images/event-loop.webp
Classroom Activity

Write a function that adds a click event listener to a button and executes a
callback function when the button is clicked
GitHub Link
ES7 features in JavaScript
Promises
A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and
its resulting value

Using Promises:
To handle the result of a promise, you use the .then(), .catch(), and .finally() methods.
then(): Used to handle the fulfillment of the promise.
catch(): Used to handle the rejection of the promise.
finally(): Used to execute code regardless of the promise's outcome (fulfilled or rejected).
Classroom Activity

Write a program to find the given string are equals or not using promise
GitHub Link
ES7 features in JavaScript
Async/Await
• Async/Await is a modern way to handle asynchronous operations in JavaScript. It allows you to write
asynchronous code that looks and behaves more like synchronous code, making it easier to read and
understand. It is built on top of promises, and provides a cleaner and more concise syntax.
• An async function is a function declared with the async keyword. Inside an async function, you can use the
await keyword to pause the execution of the function until a Promise is resolved or rejected.

• The await keyword can only be used inside an async function. It pauses the execution of the function until
the Promise is settled (resolved or rejected).
Classroom Activity

Write a program for fetching data from fake json data from using Await/Async

GitHub Link
Summary
Well done! You have completed this course and now you
have understand about:
▪ JavaScript Overview & Basics
▪ DOM elements & Events
▪ Es6 Features
▪ Es7 Features
Quiz
1. What is the difference between let and var in JavaScript?

a) let is function-scoped, var is block-scoped


b) let and var are both function-scoped
c) let is block-scoped, var is function-scoped
d) let and var are both block-scoped

Answer: c
let is block-scoped, var is function-scoped
Quiz
2. What does the === operator do in JavaScript?

a) It assigns a value to a variable


b) It compares values and types
c) It compares only values
d) It is used for concatenation

Answer: b
It compares values and types
Quiz
3. Which method can be used to select an element by its ID in JavaScript?

a) getElementByClass()
b) getElementById( )
c) querySelectorId( )
d) getElementByName()

Answer: b
getElementById( )
Quiz
4. What is the correct way to write a single line comment in JavaScript?

a) <!-- This is a comment -->


b) # This is a comment
c) // This is a comment
d) /& This is a comment &/

Answer: c
// This is a comment
Quiz
5. Which of the following is used to attach an event handler to an element in
the DOM?

a) addEventListener()
b) attachEvent()
c) bind()
d) onEventListener()

Answer: a
addEventListener()
Reference
• https://www.geeksforgeeks.org/javascript/
• https://www.w3schools.com/
• https://www.freecodecamp.org
Thank you!

You might also like