Block I & II - Scripting Language
Block I & II - Scripting Language
Block: I & II
- Embedding JS to HTML
● 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>
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.
● Multiline comments:
/* It is multi line comment.
It will not be displayed upon
execution of this code */
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
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 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 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
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.
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.
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.
27
Prepared By: Soniya Suthar
Events
● An HTML event can be something the browser does, or something a user does.
● 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.
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>
<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.
● 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.
● 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.
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!