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

Block I & II - Scripting Language

Uploaded by

Shiv Jani
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)
14 views

Block I & II - Scripting Language

Uploaded by

Shiv Jani
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
You are on page 1/ 36

Scripting Language

Block: I & II

Prepared By: Soniya Suthar


Block: IV - Agenda
- Introduction to Javascript

- Embedding JS to HTML

- Variables, Data types, Operators

- Conditional Statements, Looping

- Strings, Array, Functions, Events

- Dialog Boxes, Objects

Prepared By: Soniya Suthar


Introduction to Javascript
● JavaScript (js) is a light-weight object-oriented programming language which is
used by several websites for scripting the webpages.

● It is full-fledged programming language that enables dynamic interactivity on


websites when applied to an HTML document.

● JavaScript is a lightweight, cross-platform, single-threaded, and interpreted


compiled programming language which is also known as the scripting language
for web pages.

● JavaScript is a weakly typed language(dynamically typed). JavaScript can be


used for Client-side developments as well as Server-side developments.

● In HTML, JavaScript code is inserted between <script> and </script> tags. You
can place any number of scripts in an HTML document.

● Scripts can be placed in the <body>, or in the <head> section of an HTML page,
or in both.

3
Prepared By: Soniya Suthar
Embedding JS to HTML
● JavaScript can be added to your HTML file in two
ways: <!DOCTYPE html>
<html lang="en">
● Internal JS: We can add JavaScript directly to our
HTML file by writing the code inside the <script> <head>
tag. The <script> tag can either be placed inside <title>
the <head> or the <body> tag according to the Basic Example to Describe JavaScript
requirement. </title>
</head>

● External JS: We can write JavaScript code in <body>


another files having an extension.js and then link
this file inside the <head> tag of the HTML file in <!-- JavaScript code can be embedded inside
which we want to add this code. head section or body section -->
<script>
● Syntax: console.log("Hi from Soniya Suthar");
</script>
</body>
<script>
// JavaScript Code </html>
</script>

4
Prepared By: Soniya Suthar
Comments in JS:
● JavaScript comments can be used to explain JavaScript code, and to make it more readable.

● JavaScript comments can also be used to prevent execution, when testing alternative code.

● Single line comments:


// Perform operation of addition of two numbers
let sum = 5 + 8
console.log(sum)

● Multiline comments:
/* It is multi line comment.
It will not be displayed upon
execution of this code */

console.log( "Multiline comment in javascript" );

5
Prepared By: Soniya Suthar
Variables, Data types
● JavaScript Variables can be declared in 4 ways:
○ Automatically
○ Using var
○ Using let
○ Using const

● Example:

let num;
let messsage;
let isValid;

num=5;
message="Hello";
isValid=true;

6
Prepared By: Soniya Suthar
Variables, Data types

● Boolean: logical entity having values as true or false.


● Numbers: Represents numeric values and can store integers and decimals.
● Strings: Represent a sequence of characters such as “Hello World”. Strings can store in single quotes or
double-quotes.
● Undefined: A variable that has an unassigned value will have an undefined default value.
● Null: In JavaScript, null means"nothing". It is something that doesn't exist.
● Object: It is an instance of a class that accesses the data and members encapsulated in the class.
● Arrays: It is a group of similar kinds of values.

7
Prepared By: Soniya Suthar
Variables, Data types
● Rules for defining JavaScript Variables:
● variable name must start with a letter, underscore(_), or a dollar sign($).
● After the first letter/underscore/dollar, we can use numbers.
● A variable name can't contain spaces.
● Variables in JavaScripts are case sensitives.
● One can't use Reserved words(e.g., abstract, final, etc.) as variables names.

// Valid variables
var test1 = 10; // Started with letter
var _test = “ Demo”; // Started with UnderScore(_)
var $test1 = true; // Started with dollar sign($)

// Invalid variables
var 1test = 10; // Started with letter 1

var *test = “value”; // Started with special characte(*)

● How to access JavaScript Variables? → using document.write() method.

var a = 10;
document.write(a); // print 10 (value of a)
8
Prepared By: Soniya Suthar
Operators:
● Rules for defining JavaScript Variables:
● variable name must start with a letter, underscore(_), or a dollar sign($).
● After the first letter/underscore/dollar, we can use numbers.
● A variable name can't contain spaces.
● Variables in JavaScripts are case sensitives.
● One can't use Reserved words(e.g., abstract, final, etc.) as variables names.

// Valid variables
var test1 = 10; // Started with letter
var _test = “ Demo”; // Started with UnderScore(_)
var $test1 = true; // Started with dollar sign($)

// Invalid variables
var 1test = 10; // Started with letter 1

var *test = “value”; // Started with special character (*)

● How to access JavaScript Variables? → using document.write() method.

var a = 10;
document.write(a); // print 10 (value of a)
9
Prepared By: Soniya Suthar
Arithmetic Operators:

10
Prepared By: Soniya Suthar
Comparison Operators:

11
Prepared By: Soniya Suthar
Bitwise Operators:

12
Prepared By: Soniya Suthar
Logical Operators:

Assignment Operators:

13
Prepared By: Soniya Suthar
Conditional Statements:if

14
Prepared By: Soniya Suthar
Conditional Statements:if-else

15
Prepared By: Soniya Suthar
Conditional Statements:if-else ladder

16
Prepared By: Soniya Suthar
Conditional Statements:switch

switch (new Date().getDay())


{
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}

17
Prepared By: Soniya Suthar
Looping:
for (let i = 0; i < 5; i++) {
while (i < 10) {
text += "The number is " + i + "<br>";
text += "The number is " + i;
}
i++;
}

18
Prepared By: Soniya Suthar
Looping:Break & Continue

19
Prepared By: Soniya Suthar
Strings
● A JavaScript string is zero or more characters written inside quotes.
● JavaScript strings are for storing and manipulating text.
● You can use single or double quotes.

let carName1 = "Hello"; // Double quotes


let carName2 = 'Hello'; // Single quotes

● To find the length of a string, use the built-in length property.


let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
let length = text.length;

● There are 3 methods for extracting a part of a string:


○ slice(start, end)
○ substring(start, end)
○ substr(start, length)
● slice() extracts a part of a string and returns the extracted part in a new string.
● The method takes 2 parameters: start position, and end position (end not included).

let text = "Apple, Banana, Kiwi";


let part = text.slice(7);

20
Prepared By: Soniya Suthar
Strings
● The replace() method replaces a specified value with another value in a string.
● The replace() method does not change the string it is called on, it returns a new string.
● A string is converted to uppercase with toUpperCase().
● A string is converted to lowercase with toLowerCase().
● concat() joins two or more strings.
● The concat() method can be used instead of the plus operator.
● The trim() method removes whitespace from both sides of a string.
● A string can be converted to an array with the split() method.

let str = "Apple, Banana, Kiwi" ;


let part = str.substring( 7, 13);
let text = "Please visit GU!" ;
let newText = text.replace( "GU", "Gujarat University" );
let upr= text.toUpperCase();
let lwr = text.toLowerCase();

21
Prepared By: Soniya Suthar
Array
● An array is a special variable, which can hold more than one value.
● If you have a list of items (a list of color names, for example), storing the color in single variables could
look like this,
let c1 = "Cyan";
let c2 = "Red";
let c3 = "Black";
● An array can hold many values under a single name, and you can access the values by referring to an index
number. It is a common practice to declare arrays with the const keyword.
● Syntax:
const array_name = [item1, item2, ...];
● Example:
const colors = ["Cyan", "Red", "Black"];
● Spaces and line breaks are not important. A declaration can span multiple lines.
const colors = [
"Cyan",
"Red",
"Black"
];
● You can also create an array, and then provide the elements.
const colors = [];
colors[0]= "Cyan";
colors[1]= "Red";
colors[2]= "Black";
22
Prepared By: Soniya Suthar
Array
● You access an array element by referring to the index number.
● Array indexes start with 0.

● You can change the value of particular element in array using index,
const colors = [ "Cyan", "Red", "Black"];
document.write(colors[0]); // Returns Cyan
colors[0] = Blue // Update Cyan with Blue
document.write(colors[0]); // Returns Blue

● The real strength of JavaScript arrays are the built-in array properties and methods.
colors.length // Returns the number of elements
colors.sort() // Sorts the array

● The push() method adds a new element to an array (at the end).
const fruits = [ "Banana" , "Orange" , "Apple"];
fruits.push( "Lemon"); // Adds a new element (Lemon) to fruits

● The pop() method removes the last element from an array. It will returns the value that was "popped out".
const fruits = [ "Banana" , "Orange" , "Apple", "Mango"];
let fruit = fruits.pop();

23
Prepared By: Soniya Suthar
Array
● Shifting is equivalent to popping, but working on the first element instead of the last.

● The shift() method removes the first array element and "shifts" all other elements to a lower index. It will
returns the value that was "shifted out".
const fruits = [ "Banana" , "Orange" , "Apple", "Mango"];
let fruit = fruits.shift();

● The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements. It
will returns the new array length.
const fruits = [ "Banana" , "Orange" , "Apple", "Mango"];
fruits.unshift( "Lemon");

● The concat() method creates a new array by merging (concatenating) existing arrays. It does not change the
existing arrays. It always returns a new array. It can also take strings as arguments.

● The reverse() method reverses the elements in an array. You can use it to sort an array in descending order.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

24
Prepared By: Soniya Suthar
Function
● A JavaScript function is a block of code designed to perform a particular task.
● A JavaScript function is executed when "something" invokes it (calls it).
● A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
● Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
● The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
● The code to be executed, by the function, is placed inside curly brackets: {}
● Function parameters are listed inside the parentheses () in the function definition.
● Function arguments are the values received by the function when it is invoked.
● Inside the function, the arguments (the parameters) behave as local variables.
● When JavaScript reaches a return statement, the function will stop executing.
● If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking
statement.
● Functions often compute a return value. The return value is "returned" back to the "caller".
● With functions you can reuse code.
● You can write code that can be used many times.
● You can use the same code with different arguments, to produce different results.

25
Prepared By: Soniya Suthar
Function

26
Prepared By: Soniya Suthar
Function Recursion
● Recursion is a process of calling itself. A function
that calls itself is called a recursive function.

● A recursive function must have a condition to


stop calling itself. Otherwise, the function is
called indefinitely.

● Once the condition is met, the function stops


calling itself. This is called a base condition.

● To prevent infinite recursion, you can use


if...else statement (or similar approach) where
one branch makes the recursive call, and the
other doesn't.

27
Prepared By: Soniya Suthar
Events
● An HTML event can be something the browser does, or something a user does.

● Here are some examples of HTML events:


○ An HTML web page has finished loading
○ An HTML input field was changed
○ An HTML button was clicked

● Often, when events happen, you may want to do something. Like When you click on button, somethings needs
to load or save.

● JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with
JavaScript code, to be added to HTML elements.

<element event='some JavaScript'>


<element event="some JavaScript">

28
Prepared By: Soniya Suthar
Events
● Example,
<button onclick ="document.getE lementById('demo').innerHTML = Date()"> The time is? </button>

● In above example, the JavaScript code changes the content of the element with id="demo".
● The code changes the content of its own element (using this.innerHTML).

29
Prepared By: Soniya Suthar
Events
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>


<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>

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

</body>
</html>

30
Prepared By: Soniya Suthar
Dialog Boxes
● Dialogue boxes are a kind of popup notification, this kind of informative functionality is used to show success,
failure, or any particular/important notification to the user.

● JavaScript uses 3 kinds of dialog boxes:


○ Alert
○ Prompt
○ Confirm

● Alert Box: An alert box is used on the website to show a warning message to the user that they have entered
the wrong value other than what is required to fill in that position. Nonetheless, an alert box can still be used
for friendlier messages. The alert box gives only one button “OK” to select and proceed.

alert("I am an alert box!" );

● Confirm Box: A confirm box is often used if you want the user to verify or accept something.When a confirm
box pops up, the user will have to click either "OK" or "Cancel" to proceed.If the user clicks "OK", the box
returns true. If the user clicks "Cancel", the box returns false.

if (confirm( "Press a button!" )) {


txt = "You pressed OK!" ;
} else {
txt = "You pressed Cancel!" ;
}
31
Prepared By: Soniya Suthar
Dialog Boxes
● Prompt Box: A prompt box is often used if you want the user to input a value before entering a page.When a
prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input
value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

let person = prompt( "Please enter your name" , "Harry Potter" );


let text;
if (person == null || person == "") {
text = "User cancelled the prompt." ;
} else {
text = "Hello " + person + "! How are you today?" ;
}

32
Prepared By: Soniya Suthar
Dialog Boxes
<!doctype html>
<html>
<head>
<script>
function focused() {
var e=document.getElementById('inp');
if(confirm('Got it?')) {
e.blur();
}
}
</script>
</head>
<body>
<p style="margin-left: 45%;" >
Take the focus into the input box below:
</p>
<input id="inp"
onfocus="focused()" "
style=" margin-left: 45%;" >
</body>
</html>

33
Prepared By: Soniya Suthar
Objects
● Objects, in JavaScript, are the most important data type and form the building blocks for modern JavaScript.
● These objects are quite different from JavaScript’s primitive data types (Number, String, Boolean, null,
undefined, and symbol). Here is an example of a JavaScript object. Using const or let keyword you can declare
an object.

// object
const student = {
firstName: 'ram',
class: 10
};

● Here, student is an object that stores values such as strings and numbers.
● Syntax to declare an object:
const object_name = {
key1: value1,
key2: value2
}
● Example:
// object creation
const person = {
name: 'John',
age: 20
};
34
Prepared By: Soniya Suthar
Objects
● You can access the value of a property by using its key or Using bracket Notation.
● Syntax:
objectName.key
objectName["propertyName"]

● Example:
const person = {
name: 'John',
age: 20,
};

// accessing property
document.write(person.name); // John
document.write(person[“age”]); // 20

35
Prepared By: Soniya Suthar
Good Luck!

Prepared By: Soniya Suthar

You might also like