0% found this document useful (0 votes)
3 views74 pages

Chapter 1 Overview of Javascript 2

The document provides an overview of client-side scripting using JavaScript, covering its definition, features, and the need for JavaScript in web development. It includes topics such as variables, data types, control structures, and methods for outputting data. Additionally, it discusses the differences between server-side and client-side processes, as well as the importance of JavaScript in creating interactive and dynamic web applications.

Uploaded by

indiandj432
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views74 pages

Chapter 1 Overview of Javascript 2

The document provides an overview of client-side scripting using JavaScript, covering its definition, features, and the need for JavaScript in web development. It includes topics such as variables, data types, control structures, and methods for outputting data. Additionally, it discusses the differences between server-side and client-side processes, as well as the importance of JavaScript in creating interactive and dynamic web applications.

Uploaded by

indiandj432
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 74

TY BCA

Client-side Scripting
using JavaScript

Dr. Savita Mohurle


Prof. Mayuri Bhandari

Client-side scripting using JavaScript 1


1. Overview of JavaScript
Dr. Savita Mohurle
Prof. Mayuri Bhandari

Client-side scripting using JavaScript 2


Topics covered

1.1. What is JavaScript or JS?


1.2. Need of JavaScript
1.3. Features of JavaScript
1.4. JS Variables
1.5. JS keywords, JS Comments
1.6. JS Data types
1.7. JS Output
1.8. JS Operators
1.9. Control Structures – Conditional statements, Loops

Client-side scripting using JavaScript 3


Prerequisites

A basic knowledge of the following:


➢HTML and Cascading Style Sheets (CSS)
➢Text editors - VS Code, Sublime, Notepad++
➢Web browsers

Client-side scripting using JavaScript 4


Recommended Browsers

Recommended one of the browsers to test your JavaScript code:


➢Microsoft Internet Explorer version 9.0 or later (or 8 if you are not able to upgrade on
your operating system, for example, Windows XP)
➢Mozilla Firefox version 14.0 or later
➢Google Chrome version 20.0 or later
➢Opera version 12.0 or later

Client-side scripting using JavaScript 5


Why learn JS

1. Most popular programming language in the world


2. Low barrier entry in the field
3. It is the language of the web and now goes well beyond the web -Raspberry can all
be programmed with JavaScript, Robots JavaScript exists, Unity games
4. It is a scripting language for the web browser and it is native to the web browser

Client-side scripting using JavaScript 6


Introduction

• JavaScript came about as a joint effort between Netscape Communications


Corporation and Sun Microsystems, Inc.
• JavaScript is a prototype-based, client-side scripting language that can be used in
numerous environments.
• JavaScript is a high-level, dynamic programming language that is one of the core
technologies of the World Wide Web, alongside HTML and CSS.
• It is a scripting language that enables you to create dynamically updating content,
control multimedia, animate images etc.
• JavaScript is versatile and runs on the client side (in the browser) as well as on the
server side (with environments like Node.js).

Client-side scripting using JavaScript 7


Need of JavaScript

• JavaScript enhances the functionality of websites, making them interactive and user-
friendly.
• It allows developers to:
• Manipulate HTML and CSS to update the user interface dynamically.
• Validate user input before sending data to the server.
• Create interactive features such as image sliders, pop-ups, and form validations.
• Fetch data from servers using APIs (e.g., AJAX) without reloading the page.
• Build complex applications like single-page applications (SPAs) and progressive web
apps (PWAs).

Client-side scripting using JavaScript 8


What is server-side and client-side?

• Server-side and client-side refer to the location where certain tasks or processes are carried
out in a web application.
• Server-side processes are executed on the web server, while client-side processes are executed
on the user's device.
• Server-side processes have access to the server's resources, such as its CPU, memory, and
storage, as well as any databases or other servers that the web application uses.
• Client-side processes, on the other hand, have access only to the resources of the user's
device, such as its CPU, memory, and storage.
• Because server-side processes are executed on the web server, they are typically more secure
and less vulnerable to tampering or malicious attacks.
• Client-side processes, on the other hand, are executed on the user's device, which means that
they are potentially less secure and more susceptible to tampering or attacks.

Client-side scripting using JavaScript 9


What is server-side and client-side?

• Server-side and client-side refer to the location where certain tasks or processes are
carried out in a web application.
• Server-side processes are executed on the web server before the web application is
delivered to the user's device.
• Client-side processes are executed on the user's device after the web application is
delivered.
• Server-side processes have more access to resources and are more secure, while
client-side processes have less access to resources and are potentially less secure.

Client-side scripting using JavaScript 10


What is scripting language?

• All scripting languages are programming languages.


• A scripting language is a programming language that is interpreted.
• It is translated into machine code when the code is run, rather than beforehand.
• A scripting language doesn’t require a program to be compiled before it is run. All the
interpretation is done on-the-fly by the client.

Client-side scripting using JavaScript 11


Features of JavaScript

• Interpreted Language: JavaScript code is executed directly by the browser's JavaScript


engine, without the need for prior compilation.
• Client-Side Scripting: JavaScript is primarily used for client-side scripting, meaning it
runs on the user's browser, allowing web pages to be dynamic and interactive.
• Object-Oriented: JavaScript supports object-oriented programming
• Event-Driven Programming: JavaScript is designed to respond to user events such as
clicks, key presses, and mouse movements.
• Dynamic Typing: JavaScript uses dynamic typing, meaning variables do not need to be
declared with a type and can change type during execution.

Client-side scripting using JavaScript 12


JavaScript Versions

• JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
• ECMAScript is the official name of the language.
• ECMA is European Computer Manufacturers Association
• ECMAScript versions have been abbreviated to ES1, ES2, ES3, ES5, and ES6.
• Since 2016, versions are named by year (ECMAScript 2016, 2017, 2018, 2019, 2020).
• https://www.w3schools.com/js/js_versions.asp

Client-side scripting using JavaScript 13


How JavaScript
works? The <script> Tag

• The primary way browsers identify JavaScript is through


the <script> tag.
• This tag can be used to embed JavaScript code directly
within an HTML document or link to an external
JavaScript file.
• The <script> tag has six possible attributes: type,
language (deprecated), charset, src, defer, and async.
• These attributes give the browser additional
information about when the script should load, the
scripting language, and the location of an external
JavaScript file (if any).
Client-side scripting using JavaScript 14
How JavaScript
works? External JavaScript

External File (script.js)

Client-side scripting using JavaScript 15


How JavaScript
works? Script Type Attribute

• Although the type attribute is optional for


JavaScript (default is text/javascript), it can be
used to specify the scripting language.
• Modern HTML5 assumes JavaScript by default
when the <script> tag is used.

Client-side scripting using JavaScript 16


Using the HTML Script Tags – Attribute (defer)

• This attribute allow you to specify when an external script should be loaded.
• Ensures that the script is executed after the HTML document has been fully parsed.
This is used only for external scripts.

Client-side scripting using JavaScript 17


Using the HTML Script Tags – Attribute (async)

• Allows the script to be downloaded asynchronously and executed as soon as it’s


downloaded, without blocking HTML parsing.
• The page can continue to load without waiting for the script to load, and the script
will execute before the document completes loading
• This is also used only for external scripts.

Client-side scripting using JavaScript 18


Using <noscript> tag

• The <noscript> tag in HTML is used to provide alternative content for users whose
browsers do not support JavaScript or have JavaScript disabled.
• This ensures that the website remains accessible and usable even when JavaScript is
not available.

• How <noscript> Works:


o Functionality: The content inside the <noscript> tag is displayed only if JavaScript
is disabled or not supported by the browser.
o Usage: Typically, it is used to inform users that certain features of the website
require JavaScript or to provide basic fallback content.

Client-side scripting using JavaScript 19


Using <noscript> tag

Client-side scripting using JavaScript 20


First JavaScript -1

Client-side scripting using JavaScript 21


First JavaScript -2

Client-side scripting using JavaScript 22


Insert a Script into an HTML Document- Step by Step

Step 1: Set Up Your HTML Document - First, create a basic HTML document. This
document will serve as the structure for where you will insert your JavaScript.

Step 2: Add the <script> Tag - JavaScript is inserted into an HTML document using the
<script> tag. This can be done in three main ways:
1. Inline
2. Internal
3. External

Client-side scripting using JavaScript 23


Inline JavaScript

Insert JavaScript directly within an HTML element's attribute, such as onclick.

Client-side scripting using JavaScript 24


Internal JavaScript

Place JavaScript code within the <script> tag in the HTML document's head or body section.

Client-side scripting using JavaScript 25


External JavaScript

Link an external
JavaScript file using the
<script> tag's src
attribute. This keeps your
JavaScript code separate
from your HTML, making
it easier to manage.

script.js

Client-side scripting using JavaScript 26


Understanding Variables - Declaration

• Variables are like containers that hold something temporarily.


• In JavaScript, variables are case-sensitive.
• A variable name starts with a letter, we can't start with a number.
• Declaring Variables in JavaScript

var x = ""; //This creates a variable called x and assigns empty string to it

var cheese = "yummy"; //This creates a variable called cheese and assigns it a value "yummy"

var age = 25; //This creates a variable called age and assigns it a value of 25

Client-side scripting using JavaScript 27


Understanding Variables

//Invalid variables
var 1cat = ""; //can not start with number
var $cat = ""; //$ is used by libraries
var my-cat = ""; // - is not allowed
var my cat = ""; //space between variable name
var new = ""; //new is a keyword

//Following three variables are different with three different values


var cat = "this cat"
var CAT = "that cat"
var Cat = "another cat"

Client-side scripting using JavaScript 28


Understanding Variables

//Types of variables
//JavaScript is loosely typed. var myNumAsString = "5";
var mynum = 10;
var notNum = "5"; typeof(mynum) //'number'
typeof(myNumAsString) //'string'
var newNum = 10; var undefined; //undefined
typeof(undefined) //'undefined'
newNum + notNum //'105' var nothing = null; //undefined
typeof(nothing) //'object'
var emptyString = "";
typeof(emptyString); //'string'

Client-side scripting using JavaScript 29


Keywords

• JavaScript keywords are reserved


words that have special
meanings in the language.
• These keywords are part of the
syntax and cannot be used as
identifiers (names for variables,
functions, etc.).
• https://www.w3schools.com/js/j
s_reserved.asp

Client-side scripting using JavaScript 30


JavaScript Comments

• Single-line Comments
• Single-line comments start with //. Any text following // on the same line is
considered a comment and is ignored by JavaScript.

• Multi-line Comments
• Multi-line comments start with /* and end with */. Everything between /* and */ is
considered a comment and is ignored by JavaScript.

Client-side scripting using JavaScript 31


JavaScript 'let' : Block Scope

• The let keyword was introduced in ES6 (2015)


• Variables declared with let have Block Scope
• Variables declared with let must be Declared before use
• Variables declared with let cannot be Redeclared in the same scope
• Variables declared inside a { } block cannot be accessed from outside the block

{
let x = 2;
}
// x can NOT be used here
Client-side scripting using JavaScript 32
JavaScript 'var' : Function Scope

• Variables declared with the var always have Global Scope.


• Variables declared with the var keyword can NOT have block scope
• Variables declared with varinside a { } block can be accessed from outside the block

{
var x = 2;
}
// x CAN be used here

Client-side scripting using JavaScript 33


JavaScript 'const'

• The const keyword was introduced in ES6 (2015)


• Variables defined with const cannot be Redeclared
• Variables defined with const cannot be Reassigned
• Variables defined with const have Block Scope
• JavaScript const variables must be assigned a value when they are declared

const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

Client-side scripting using JavaScript 34


Data Types: Primitive

• JavaScript has following Primitive Datatypes


• String: Textual data.
• Number: Numeric values.
• Boolean: Logical values (true or false).
• Undefined: Variable declared but not assigned.
• Null: Intentional absence of any object value.
• Symbol: Unique and immutable identifier.
• BigInt: Large integers.

Client-side scripting using JavaScript 35


Data Types: Object Datatype

• The object data type can contain both built-in objects, and user defined objects:
• Built-in object types can be:
• objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.

Client-side scripting using JavaScript 36


Data Types: Example

let stringExample = "Hello, World!";


let numberExample = 42;
let booleanExample = true;
let nullExample = null;
let undefinedExample;
let symbolExample = Symbol("unique");
let bigintExample = BigInt(9007199254740991);

Type of variable can be checked using typeof() function.


Example: console.log(typeof(stringExample));
Client-side scripting using JavaScript 37
Data Types: Symbols

• JavaScript Symbols are a new type of primitive data type introduced


in the ES6 version of the language.
• They are used to represent unique values that can be used as
identifiers or keys in objects.
• They are also used to create private properties and methods in
classes.

Client-side scripting using JavaScript 38


Output

• In JavaScript, output refers to the process of displaying data to the user or to another
system.
• There are several ways to produce output in JavaScript, and the method you choose
depends on the context and the desired output destination.

Client-side scripting using JavaScript 39


Output: console.log()

• The console.log() method is used to print messages to the web console. This is
primarily used for debugging purposes.

console.log("Hello, World!");
let x = 10;
console.log("The value of x is:", x);

Client-side scripting using JavaScript 40


Output: alert()

• The alert() method displays an alert dialog with a specified message and an OK button.

alert("Hello, World!");
let x = 10;
alert("The value of x is: " + x);

Client-side scripting using JavaScript 41


Output: document.write()

• The document.write() method writes directly to the HTML document. It is often used for
testing purposes and should be avoided in modern web development.

document.write("Hello, World!");
let x = 10;
document.write("The value of x is: " + x);

Client-side scripting using JavaScript 42


Output: innerHTML

• The innerHTML property sets or returns the HTML content of an element. This method is
commonly used to update the content of a web page dynamically.

<p id="output"></p>
<script>
document.getElementById("output").innerHTML = "Hello, World!";
let x = 10;
document.getElementById("output").innerHTML += "<br>The value of x is: " + x;
</script>

Client-side scripting using JavaScript 43


Output: error, warning, information

• console.error(), console.warn(), console.info(): These methods are similar to


console.log(), but they are used to log errors, warnings, and informational messages,
respectively.

console.error("This is an error message");


console.warn("This is a warning message");
console.info("This is an informational message");

Client-side scripting using JavaScript 44


Output: prompt()

• The prompt() method displays a dialog box that prompts the user for input and returns the
input value.

let userInput = prompt("Please enter your name:");


console.log("User entered: " + userInput);

Client-side scripting using JavaScript 45


JavaScript Operators

• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators

Client-side scripting using JavaScript 46


Arithmetic Operators

Operator Description Example


+ Addition 5 + 2 // 7
- Subtraction 5 - 2 // 3
* Multiplication 5 * 2 // 10
/ Division 5 / 2 // 2.5
% Modulus (Remainder) 5 % 2 // 1
** Exponentiation 5 ** 2 // 25
++ Increment x++

Client-side scripting using JavaScript 47


Assignment operators

Operator Description Example


= Assignment x=5
+= Addition Assignment x += 2 // x = x + 2
-= Subtraction Assignment x -= 2 // x = x - 2
*= Multiplication Assignment x *= 2 // x = x * 2
/= Division Assignment x /= 2 // x = x / 2
%= Modulus Assignment x %= 2 // x = x % 2
**= Exponentiation Assignment x **= 2 // x = x ** 2
Client-side scripting using JavaScript 48
Comparison operators

Operator Description Example


== Equal 5 == '5' // true
!= Not Equal 5 != '5' // false
=== Strict Equal 5 === 5 // true
!== Strict Not Equal 5 !== '5' // true
> Greater Than 5 > 2 // true
< Less Than 5 < 2 // false
>= Greater Than or Equal 5 >= 5 // true
<= Less Than or Equal 5 <= 5 // true

Client-side scripting using JavaScript 49


Logical operators

Operator Description Example


&& AND true && true // true
` `
! NOT !true // false

Client-side scripting using JavaScript 50


Bitwise Operators

Operator Description Example

& AND 5 & 1 // 1

` ` OR

^ XOR 5 ^ 1 // 4

~ NOT ~5 // -6

<< Left Shift 5 << 1 // 10

>> Right Shift 5 >> 1 // 2

>>> Unsigned Right Shift 5 >>> 1 // 2

Client-side scripting using JavaScript 51


Type operator

Operator Description Example


typeof Type of typeof 5 // "number"
arr instanceof Array //
instanceof Instance of
true

Client-side scripting using JavaScript 52


Ternary operator

• The ternary operator, also known as the conditional operator, is a concise way to
perform conditional operations in JavaScript.
• It evaluates a condition and returns one of two values based on whether the
condition is true or false.

let age = 18;


let canVote = (age >= 18) ? "Yes, you can vote." : "No, you cannot vote.";
console.log(canVote);

Client-side scripting using JavaScript 53


Challenge #1

• Mark and John are trying to compare their BMI (Body Mass Index), which is calculated using the formula: BMI = mass
/ (height * height) (mass in kg and height in meters).
• Your task is to write some code to help them:
• Store Mark's and John's mass and height in variables called massMark, heightMark, massJohn and heightJohn.
• Calculate both their BMIs using the formula, and store the results in two variables called BMIMark and BMIJohn.
• Log the value of BMIMark and BMIJohn to the console.
• Create a boolean variable markHigherBMI containing information about whether Mark has a higher BMI than John.
Log it to the console too
• TEST DATA 1: Marks weighs 78 kg and is 1.69 m tall. John weighs 92 kg and is 1.95 m tall.
• TEST DATA 2: Marks weights 95 kg and is 1.88 m tall. John weights 85 kg and is 1.76 m tall.

Client-side scripting using JavaScript 54


Challenge #1: Solution

Client-side scripting using JavaScript 55


Conditional Statements

In JavaScript we have the following conditional statements:


1. Use if to specify a block of code to be executed, if a specified condition is true
2. Use else to specify a block of code to be executed, if the same condition is false
3. Use else if to specify a new condition to test, if the first condition is false
4. Use switch to specify many alternative blocks of code to be executed

Client-side scripting using JavaScript 56


if Statement

• The if statement executes a block of code if a specified condition evaluates to true.

let x = 10;

if (x > 5) {
console.log("x is greater than 5");
}

Client-side scripting using JavaScript 57


if...else Statement

• The if...else statement executes one block of code if a condition evaluates to true, and
another block of code if it evaluates to false.
let x = 3;

if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}

Client-side scripting using JavaScript 58


else if Statement

• The else if statement allows you to check multiple conditions by adding more
conditional blocks.

if (x > 10) {
console.log("x is greater than 10");
} else if (x > 5) {
console.log("x is greater than 5 but less than or equal to 10");
} else {
console.log("x is 5 or less");
}

Client-side scripting using JavaScript 59


switch Statement

let fruit = "apple";


• The switch statement evaluates an
expression and matches its value switch (fruit) {
against multiple case clauses. case "banana":
console.log("Banana is selected.");
• When a match is found, the break;
corresponding block of code is case "apple":
executed. console.log("Apple is selected.");
break;
• If no match is found, the default case "orange":
block is executed. console.log("Orange is selected.");
break;
default:
console.log("No fruit is selected.");
}
Client-side scripting using JavaScript 60
Challenge #2

• Use the BMI example from Challenge #1, and the code you already wrote, and
improve it:
• 1. Print a nice output to the console, telling the user who has the higher BMI.
The message can be either:
• "Mark's BMI is higher than John's!" or "John's BMI is higher than
Mark's!".
• 2. Modify the outputs above to use template literals to include the BMI values
in the outputs.
• Example: "Mark's BMI (28.3) is higher than John's (23.9)!" or "John's
BMI (29.1) is higher than Mark's (27)!" .

Client-side scripting using JavaScript 61


Challenge #3

• Use prompt to ask the user for a whole number.


• If they type in a number less than 10, have the console log report, "You
entered a number smaller than 10",
• otherwise, send "You entered a big number" to the console
• if a user types something other than a number, the console displays a message
that says there was an error.

Client-side scripting using JavaScript 62


for Loop

• The for loop is used when you know in advance how many times you want to execute
a statement or a block of statements.
• It consists of three parts: initialization, condition, and increment/decrement.

for (let i = 0; i < 5; i++) { var colors = ['red', 'blue', 'yellow', 'green'];
console.log(i);
} for(var i=0; i<colors.length; i++){
console.log(colors[i]);
}

Client-side scripting using JavaScript 63


for...in Loop

• The for...in loop is used to iterate over the properties of an object.

const person = {
firstName: "John",
lastName: "Doe",
age: 25
};

for (let key in person) {


console.log(key + ":" + person[key])
}

Client-side scripting using JavaScript 64


for...of Loop

• The for...of loop is used to iterate over the values of an iterable object, such as an
array, string, or other collections.

const array = ['blue', 'red', 'yellow', 'orange', 'purple'];

for (let value of array) {


console.log(value);
}

Client-side scripting using JavaScript 65


while Loop

• The while loop is used when the number of iterations is not known beforehand and
the loop should continue running as long as the specified condition is true.

let i = 0;

while (i < 5) {
console.log(i);
i++;
}

Client-side scripting using JavaScript 66


do...while Loop

• The do...while loop is similar to the while loop, but it ensures that the loop body is
executed at least once before the condition is tested.

let i = 0;

do {
console.log(i);
i++;
} while (i < 5);

Client-side scripting using JavaScript 67


Challenge #4

• Use prompt to ask the user for a whole


number.
• if the user types a number less than 10,
use a loop to print out the numbers from
zero to 9 in the console and indicates the
number the user entered.
• otherwise, send "You entered a big
number" to the console
• if a user types something other than a
number, the console displays a message
that says there was an error.

Client-side scripting using JavaScript 68


Solution: Challenge #4

Client-side scripting using JavaScript 69


Practice Questions

1. Write a JavaScript program that converts a temperature in Celsius to Fahrenheit.


Allow the user to input the temperature in Celsius and display the equivalent
temperature in Fahrenheit.
2. Write a function that takes a positive number num and returns its multiplicative
persistence, which is the number of steps it takes to multiply all the digits of num by
each other, and repeating with the product until a single digit is obtained.
Example:
Persistence of 999 is 4 // because 9*9*9=729, 7*2*9=126, 1*2*6=12, and finally 1*2=2
Persistence of 5 is 0 because 5 is already a single-digit number

Client-side scripting using JavaScript 70


Solution #1

Client-side scripting using JavaScript 71


Solution #2

Client-side scripting using JavaScript 72


Important Links

1. A Simple CodePen Example: https://codepen.io/rcyou/pen/QEObEZ


2. https://www.jschallenger.com/javascript-basics/conditionals/introduction-
conditionals-javascript

Client-side scripting using JavaScript 73


Thank You

Client-side scripting using JavaScript 74

You might also like