JavaScript V0.3
JavaScript V0.3
Scripting languages
• Scripting languages are programming languages that a program called an interpreter translates into a
• Scripts contain a series of commands that a software, application or scripting engine interprets one at a
JavaScript : Introduction
• JavaScript often abbreviated as JS, is a programming language and core technology of the World Wide
• As of 2024, 98.9% of websites use JavaScript on the client side for webpage behavior, often
• All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.
4 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
JavaScript: Introduction
• JavaScript is a multi-paradigm, dynamic language with types and operators, standard built-in objects, and
methods.
• Its syntax is based on the Java and C languages — many structures from those languages apply to
JavaScript as well.
JavaScript: Introduction
• Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects;
For Example,
• Client-side JavaScript extends the core language by supplying objects to control a browser and its
• Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript
on a server.
Javascript : Introduction
• Client-side JavaScript:
• To be interpreted by the browser, the script must be included in or linked from an HTML document.
• It means that a web page can now incorporate programs that interact with the user, control the browser,
and dynamically create HTML content, rather than just static HTML.
• For ex. Use JavaScript to verify that a user has provided a valid email address in a form field.
• When the user submits the form, the Script code gets executed, and the form is submitted to the Web
Javascript : Advantages
• Less server interaction − Before transmitting the page to the server, we can validate the user's input.
• Immediate feedback to the visitors − They don't have to wait for the page to reload to see if they lost
something.
• Increased interactivity − We can make interfaces that respond when the user moves their mouse over
• Richer interfaces − To provide a Rich Interface to your site users, we can utilize JavaScript to
Javascript : Advantages
• Interoperability - We can embed it into any webpage or inside the script of another
programming language.
• Versatility - JavaScript can now be used for both front-end and back-end development.
• Less Overhead
• By reducing the code length, JavaScript enhances the efficiency of websites and web apps.
• The usage of numerous built-in methods reduces the amount of overhead in the code.
Javascript : Advantages
• Popularity - Since all modern browsers support JavaScript, it is seen almost everywhere.
• Extended Functionality - Third-party add-ons allow the developers to add snippets of predefined code
• Asynchronous Programming – This model facilitates non-blocking operations, making it well-suited for
tasks that involve fetching data from servers, handling user input, and managing concurrent processes.
The actual content of The look of the page Easily control and alter
the page like color, style the HTML
Javascript : A heed
• File reading and writing on the client side are not supported by JavaScript.
• A single code error can cause the entire JavaScript code on the page to stop rendering.
• The <script> element, which contains JavaScript, can be placed anywhere on the page, however it is
advised to put it within the <head> tags.
• The <script> tag alerts the browser program to begin interpreting all the text between these tags as a
script.
• Syntax of JavaScript will be as follows:
<script>
Javascript Code
</script>
• language:
• The use of this feature has been phased out in current versions of HTML (and its successor,
XHTML).
• type:
• The value of this attribute should be set to "application/javascript" or “text/javascript" in order
to identify the scripting language in use.
<!DOCTYPE html>
<html>
<head>
<script type="application/javascript">
alert('Hello, World!');
</script>
</head>
<body>
</body>
</html>
• There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are
• Script in <head>...</head> section: If you want to have a script run on some event, such as when a
user clicks somewhere, then you will place that script in the head.
• Script in <body>...</body> section: If you need a script to run as the page loads so that the script
generates content in the page, the script goes in the <body> portion of the document.
• The script tag provides a mechanism to allow you to store JavaScript in an external file and then
include it in your HTML files.
• To use JavaScript from an external file source, you need to write all JavaScript source code in a simple
text file with the extension ".js".
//filename.js
alert('Hello, World!');
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Basic Elements
JavaScript is case-sensitive
• Everything in JavaScript is case-sensitive, including variables, function names, class names, and
operators.
• It indicates that the counter and Counter variables are not the same.
Identifiers
• The first character must be a letter (a-z, or A-Z), an underscore(_), or a dollar sign ($).
• The other characters can be letters (a-z, A-Z), numbers (0-9), underscores (_), and dollar signs ($).
• A block comment starts with forward-slash(/) and asterisk(*) characters and ends with asterisk(*) and
forward-slash(/) characters.
/*
*/
Statements
var a = 10;
var b = 20;
Expressions
• An expression is a piece of code that evaluates to a value.
For example:
c=2 + 1
• JavaScript defines a list of keywords and reserved words that have special uses.
• var
• let
• const
var message;
message = "Hello";
• You can also assign a value to the variable when you declare it:
Note:
• The general rules for constructing names for variables (unique identifiers) are:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var x = "Sachin";
var x = 0;
document.write(x);
</script> Output:
</body>
0
</html>
{
var x = 2;
}
// x can be used here
<html>
<body>
<script type="text/javascript">
const PI = 3.141592653589793;
document.write(PI);
</script>
</body>
Output:
</html> 3.141592653589793
<html>
<body>
<script type="text/javascript">
const PI ;
PI = 3.141592653589793;
document.write(PI);
</script>
</body> Output:
• Declaring a variable with const is similar to let when it comes to Block Scope.
• For Example: The x declared in the block is not the same as the x declared outside the block
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
== equal to
!= not equal
? ternary operator
38 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Operator Description
|| logical or
! logical not
(?:) Conditional Operator returns value based on the condition. It is like if-else.
x = 5; // Now x is a Number
• Strings are written with quotes. single or double quotes can be used.
• We can use quotes inside a string, as long as they don't match the quotes surrounding the string:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
let Name1 = "Sachin"; // Using double quotes
let Name2 = 'Sachin'; // Using single quotes
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
let x1 = 34.50; // Written with decimals
let x2 = 34; // Written without decimals
</body>
</html>
<body>
<script type="text/javascript">
let x = 5;
let y = 5;
let z = 6;
document.write("(x == y) : "+(x == y) +"<br/>");
document.write("(x == z) : "+(x == z) );
</script>
</body>
</html>
• Array indexes are zero-based, which means the first item is [0], the second is [1], and so on.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
const cars = ["Saab", "Volvo", "BMW"];
document.write("Cars : "+cars +"<br/><br/>");
for (let i = 0; i < cars.length; i++) {
document.write("Car at index " + i + ": " + cars[i] + "<br/>"); }
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
• The window object is the global scope object, that means that variables, properties, and methods by
default belong to the window object.
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
52 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript : Fundamentals
• For debugging purposes, you can call the console.log() method in the browser to display data.
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
if (condition) {
// block of code to be executed if the condition is true
}
<script type="application/javascript">
</script>
<script type="application/javascript">
var age = 15;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}else{
document.write("<b>Does not qualify for driving</b>");
}
</script>
if (condition1) {
} else if (condition2) {
} else {
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
<script type="application/javascript">
var grade='A';
switch (grade) {
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
break;
break;
</script>
<script type="application/javascript">
var count = 0;
count++; }
</script>
do{
Statement(s) to be executed;
} while (expression);
<script type="application/javascript">
var count = 0;
document.write("Starting Loop…." + "<br /><br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 10);
document.write("<br />Loop stopped!");
</script>
<script type="application/javascript">
</script>
63 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Basic Elements : Control Flow Statements
break Statement
<script type="application/javascript">
var x = 1;
document.write("Entering the loop<br /> <br />");
while (x < 20){
if (x == 5){
break; // breaks out of the loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write(" <br /> Exiting the loop!<br /> ");
</script>
<script type="application/javascript">
</script>
var x = 1;
</script>
<script type="application/javascript">
if (j == 3){
continue outerloop;
</script>
70 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Syntax:
function functionName(parameter-list){
statements
}
• 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, ...)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sayHello() {
alert("Hello there");
</script>
</head>
<body>
<script type="text/javascript">
sayHello();
</script>
</body>
</html>
• A confirmation dialog box is mostly used to take the user’s consent on any option. It displays a dialog box
with two buttons: OK and Cancel.
• If the user clicks on the OK button the window method confirm() will return true.
<html>
<head>
<script>
function myConfirmbox(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
alert("User wants to continue!");
}
else{
alert("User does not want to continue!");
}
}
</script>
</head>
75 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Basics
Basic Elements : DialogBoxes
Confirmation Dialog Box:
<body>
<script>
myConfirmbox();
</script>
</body>
</html>
• The window method prompt() returns the entered value when the user clicks on OK button.
<html>
<head>
<script>
function myPrompt(){
var retVal = prompt("Enter your name : ", "your name here");
alert("You have entered : " + retVal );
}
</script>
</head>
<body>
<script>
myPrompt();
</script>
</body></html>
• "Everything" in JavaScript is an Object. Even primitive data types (except null and undefined) can be
treated as objects.
Object Properties
Syntax:
• objectName.propertyName
• objectName["propertyName"]
Object Properties:
Property Property Value
firstName Sachin
lastName Tendulkar
age 50
Example:
person.lastName; // Tendulkar
Or
person["lastName"];
83 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
Introduction
Object Methods
objectName.methodName()
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
person.fullName=function(){
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
person.fullName=function(){
</script>
</body>
</html>
Arrays
• In JavaScript, arrays aren't primitives but are instead Array objects with the following core
characteristics:
• JavaScript arrays are resizable and can contain a mix of different data types.
• JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary
Arrays
Creating an array
• Using literal
• Using Constructor
Arrays: Iteration
• Using forEach:
const arrayItems = ['item1', 'item2', 'item3'];
const copyItems = [];
arrayItems.forEach(function(item){
copyItems.push(item);
})
console.log(copyItems);
• Using for…of:
const students = ['John', 'Sara', 'Jack'];
// using for...of
for ( let element of students ) {
console.log(element);
}
Methods Description
push() Adds new elements to the end of an array, and returns the new length
pop() Removes the last element of an array, and returns that element
shift() Removes the first element of an array, and returns that element
unshift() Adds new elements to the beginning of an array, and returns the new length
find() Returns the value of the first element in an array that pass a test
filter() Creates a new array with every element in an array that pass a test
keys() Returns a Array Iteration Object, containing the keys of the original array
map() Creates a new array with the result of calling a function for each array element
Methods Description
reduce() Reduce the values of an array to a single value (going left-to-right)
indexOf() Search the array for an element and returns its position
lastIndexOf() Search the array for an element, starting at the end, and returns its position
• But strings can also be defined as objects with the keyword new:
//checks both the values and the data types, and they are different (string vs. object)
document.write("Comparison using === operator: "+(x===z)+"<br/>");
//checking the two different string objects but they have the same string value
document.write("Comparison using == operator: "+(z==z1)+"<br/>");
//checks both values and data types but not with objects
document.write("Comparison using === operator: "+(z===z1)+"<br/>");
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
97 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods
Possible String Methods:
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of the specified value,
or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value,
or -1 if not found.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to replace the matched
substring with a new substring.
search() Executes the search for a match between a regular expression and a specified string.
split() Splits a String object into an array of strings by separating the string into substrings.
98 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods
Possible String Methods:
Method Description
substr() Returns the characters in a string beginning at the specified location through the
specified number of characters.
substring() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while respecting the
current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the
current locale.
• slice() extracts a part of a string and returns the extracted part in a new string.
• The method takes 2 parameters: the start position, and the end position (end not included).
• The positive starting index(from left to right) is 0 and the negative starting index(from right to left) is -1.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
</script>
</body>
</html>
102 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
String Methods: Example #3
• The difference is that the second parameter specifies the length of the extracted part.
• If you omit the second parameter, substr() will slice out the rest of the string.
Replacing String
• 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.
• To replace all matches, use a regular expression with a /g flag (global match).
<body>
<script type="text/javascript">
Method Description
constructor() Returns the function that created this object's instance. By default this is the Number
object.
toExponential() Forces a number to display in exponential notation, even if the number is in the range in
which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocaleString() Returns a string value version of the current number in a format that may vary according
to a browser's locale settings.
toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to
display of a number.
toString() Returns the string representation of the number's value.
• All number methods can be used on any type of number (literals, variables, or expressions).
<!DOCTYPE html>
<html>
<body>
<script>
let x = 123;
document.write("Number as a String: "+x.toString()+"<br/><br/>");
document.write("Number as a String: "+(123).toString()+"<br/><br/>");
document.write("Number as a String: "+(100 + 23).toString());
</script>
</body>
</html>
109 JavaScript | © SmartCliff | Internal | Version 1.1
JavaScript Objects
Global Methods
Converting Variables to Numbers
• There are 3 JavaScript methods that can be used to convert a variable to a number:
Method Description
Number() Returns a number converted from its argument.
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
document.write("Converting boolean variable to number: "+Number(true)+"<br/><br/>");
document.write("Converting boolean variable to number: "+Number(false)+"<br/><br/>");
document.write("Converting string variable to number: "+Number("50")+"<br/><br/>");
document.write("Converting string variable to number: "+Number("50.50")+"<br/><br/>");
document.write("Converting string variable to number: "+Number("Hi"));
</script>
</body>
</html>