Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Javascript Tutorial

This document is a comprehensive tutorial on JavaScript, covering its definition, variables, data types, functions, objects, events, and more. It explains how to manipulate HTML content, handle user input, and utilize various JavaScript methods and operators. Additionally, it includes examples of loops, conditionals, and the use of external JavaScript files.

Uploaded by

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

Javascript Tutorial

This document is a comprehensive tutorial on JavaScript, covering its definition, variables, data types, functions, objects, events, and more. It explains how to manipulate HTML content, handle user input, and utilize various JavaScript methods and operators. Additionally, it includes examples of loops, conditionals, and the use of external JavaScript files.

Uploaded by

Arindam saha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Javascript Tutorial

Arindam Saha
What is Javascript?

JavaScript is a client-side scripting language, which means it runs in the browser.


A lightweight programming language ("scripting language") used to make web
pages interactive insert dynamic text into HTML (ex: a date) react to events (ex:
user clicks on a button) get information about a user's computer (ex: browser type)
perform calculations on user's computer (ex: form validation).

JavaScript was developed by Brendan Eich in May 1995 while he was working at
Netscape Communications Corporation.
Javascript Variables
JavaScript Variables can be declared in 4 ways:

● Automatically
● Using var
● Using let
● Using const

Automatic Variables : x, y, and z are undeclared variables. They are automatically declared.

X = 5;

Y = 6;

Z = X+Y
Javascript Variables
With let you can not do this:

let x = "John Doe";

let x = 0;

const variables can not be changed or modify it.


const x = 5;
const y = 6;
const z = x + y;
JavaScript Output
Display Possibilities
JavaScript can "display" data in different ways:

● Writing into an HTML element, using innerHTML or innerText.


● Writing into the HTML output using document.write().
● Writing into an alert box, using window.alert().
● Writing into the browser console, using console.log().
● To get user input in JavaScript, using prompt().
Data Types
JavaScript has 8 Data-types
● String
● Number
● Bigint
● Boolean
● Undefined
● Null
● Symbol
● Object

The Object Data-type


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, float, arrays, promises, and more.
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById() . The example below "finds" an
HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello
JavaScript":

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML =


"Hello JavaScript!"'>Click Me!</button>
Document Object Model (DOM)

To access an HTML element, you can use DOM feature such as the document.getElementById(id)
method. Use the id attribute to identify the HTML element. Then use the innerHTML property to
change the HTML content of the HTML element:

<h1>My Web Page</h1>

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

<script>

document.getElementById("demo").innerHTML =

"<h2>Hello World</h2>";

</script>
JavaScript Comments
● Single Line Comments
Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

● Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.


JavaScript Operators
Javascript Assignment Operators
JavaScript Functions
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).
function name(parameter1, parameter2, parameter3) {
// code to be executed
}

Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

● When an event occurs (when a user clicks a button)


● When it is invoked (called) from JavaScript code
● Automatically (self invoked)
Javascript Function
Function Return
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":

// Function is called, the return value will end up in x


let x = myFunction( 4, 3);
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Javascript Function
Celsius to Fahrenheit Converter
function toCelsius(fahrenheit) {

return (5/9) * (fahrenheit- 32);

let value = toCelsius( 77);

let text = "The temperature is " + x + " Celsius" ;

Note: As you see from the examples above, toCelsius refers to the function object,
and toCelsius() refers to the function result.
JavaScript Objects
In real life, objects are things like: houses, cars, people, animals, or any other subjects. Here is a car
object example:
JavaScript Objects
Objects are variables too. But objects can contain many values. This code assigns
many values (Fiat, 500, white) to an object named car:
<h2>Creating an Object</h2>
<p id="demo"></p>
<script>
// Create an Object:
const car = {type:"Fiat", model:"500", color:"white"};
// Display Data from the Object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>
JavaScript Objects
This example creates an empty JavaScript object, and then adds 4 properties:

// Create an Object

const person = {};

// Add Properties

person.firstName = "John";

person.lastName = "Doe";

person.age = 50;

person.eyeColor = "blue";
JavaScript Object Methods
Object methods are actions that can be performed on objects. A method is a function
definition stored as a property value.
JavaScript Object Constructors
Sometimes we need to create many objects of the same type. To create an object type we
use an object constructor function. It is considered good practice to name constructor
functions with an upper-case first letter.
Constructor Function Methods

Adding a Method to an Object


JavaScript 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.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
JavaScript Events
In the following example, an onclick attribute (with code), is added to a <button> element:
Common HTML Events
Onchange Event
<h1>JavaScript HTML Events</h1>

<label for="color">Choose a color:</label>

<select id="color" onchange="alert('Color changed!')">

<option value="red">Red</option>

<option value="green">Green</option>

<option value="blue">Blue</option>

</select>
Onclick Event
<button onclick="alert('Button clicked!')">Click Me</button>

Onmouseover Event
<div onmouseover="this.style.backgroundColor='yellow'">Hover over me!</div>
Onmouseout
<div onmouseout="this.style.backgroundColor='transparent'">Move mouse away from me!</div>

Onmouseout
<div onmouseout="this.style.backgroundColor='transparent'">Move mouse away from me!</div>
Onload Event
<!DOCTYPE html>

<html>

<body onload="alert('Page has finished loading!')">

<h1>Welcome to the page!</h1>

</body>

</html>
JavaScript Strings
Strings are for storing text, Strings are written with quotes.

let carName1 = "Volvo XC60" ; // Double quotes

let carName2 = 'Volvo XC60' ; // Single quotes

Common Methods used in Strings : Javascript strings are primitive and immutable: All string
methods produce a new string without altering the original string.

toUpperCase(), toLowerCase(), concat(), repeat(), replace(), replaceAll(), split(),


trim(), slice(), length etc.
String toUpperCase()
This function helps to make the string to Uppercase.

Result:
String toLowerCase()
This function helps to make the string to Lowercase.

Results:
String concat()
The concat() method can be used instead of the plus operator. concat() joins two or more
strings.

Results:
String repeat()
The repeat() method returns a string with a number of copies of a string.The repeat()
method returns a new string. This method does not change the original string.

Results:
Replacing String Content
The replace() method replaces a specified value with another value in a string.

Results:
String ReplaceAll()
This function allows the user to replace all the regular expression to be replaced instead of
replacing a whole string.

Results:
String split()
A string can be converted to an array with the split() method.

Results:
String trim()
The trim() method removes whitespace from both sides of a string.

Results:
String slice()
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).

Results:
String Length
The length property returns the length of a string.

Results:
String Search Methods
String search methods refer to techniques used to find or locate a substring within a larger string.
These methods are widely used in programming for tasks like pattern matching, searching for
specific words, or finding occurrences of substrings in text data. Some of the common techniques
are: indexOf(), search(), match(), matchAll() etc.

indexOf(): The indexOf() method returns the index (position) of the first occurrence
of a string in a string, or it returns -1 if the string is not found.
String Search Methods
search(): The search() method searches a string for a string (or a regular expression) and
returns the position of the match.

match(): The match() method returns an array containing the results of matching a string
against a string (or a regular expression).
JavaScript Arrays
In JavaScript, an array is a special type of object used to store multiple values in a single variable.
Arrays can hold elements of any data type, such as numbers, strings, objects, or even other
arrays. They are ordered collections, meaning that the elements inside the array have an index
(position) that can be used to access or modify the elements.

Accessing Array Elements


Array Methods
In JavaScript, array methods are built-in functions that help you perform common tasks on arrays, such
as adding, removing, finding, sorting, filtering, and transforming elements. These methods make it easier
to manipulate arrays without writing custom loops. Some of the most used methods are: push(), pop(),
splice(), slice(), sort(), reverse(), concat(), etc.

push(): The push() method adds a new element to an array (at the end).

pop(): The pop() method remove a element of an array (at the end).
Array Methods
splice(): The splice() method can be used to add new items to an array.

The first parameter (2) defines the position where new elements should be added (spliced
in). The second parameter (0) defines how many elements should be removed. The rest of
the parameters ("Lemon" , "Kiwi") define the new elements to be added.

slice(): The slice() method slices out a piece of an array into a new array.
Array Methods
sort(): The sort() methods is used to sort the array.

reverse(): The reverse() methods is used to reverse the array.

concat(): The reverse() methods is used to reverse the array.


Random in Javascript
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive).
Boolean in Javascript
JavaScript has a Boolean data type. It can only take the values true or false.

The Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true.
If-else in Javascript
The if...else statement in JavaScript is used for decision-making.

#Syntax

if (condition) {
// Code to run if condition is true
} else {
// Code to run if condition is false
}

Example:
let age = 18;

if (age >= 18) {


windows.alert("You are eligible to vote.");
} else {
windows.alert("You are not eligible to vote.");
}
If-else in Javascript
Example:
let score = 75;
if (score >= 90) {
windows.alert("Grade: A");
} else if (score >= 75) {
windows.alert("Grade: B");
} else if (score >= 60) {
windows.alert("Grade: C");
} else {
windows.alert("Grade: F");
}
Switch Case
Using the switch statement to select one of many code blocks to be executed.

Note: The switch expression is evaluated once. The value of the expression is compared with the values of
each case. If there is a match, the associated block of code is executed. If there is no match, the default
code block is executed.
Switch Case
The getDay() method returns the weekday as a number between 0 and 6 (Sunday=0, Monday=1, Tuesday=2
..). This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
External JS
Linking an external JavaScript file to an HTML file is a common and clean way to organize
code.

<script src="script.js"></script> //Linking the external javascript file


script.js

function showMessage() {
alert("Hello from external JavaScript!");
}

class Greeter {
constructor(name) {
this.name = name;
}

greet() {
console.log(`Hello, ${this.name}!`);
}
}
External JS
Linking an external JavaScript file to an HTML file is a common and clean way to organize
code.

<script src="script.js"></script> //Linking the external javascript file


<body>
<h1>External JS File Demo</h1>

<!-- Button to trigger JS function -->


<button onclick="showMessage()">Click Me</button>

<script src="script.js"></script> <!-- Link the external JS file -->


<script>
// Accessing class from external JS
const user = new Greeter("Arindam");
user.greet(); // Outputs: Hello, Arindam!
</script>
</body>
JavaScript For Loop
Loops are handy, if you want to run the same code over and over again, each time with a different
value.

for (expression 1; expression 2; expression 3) {

// code block to be executed

Example:
JavaScript For-In
The JavaScript for in statement loops through the properties of an Object:

#Syntax
JavaScript For Of
The JavaScript for of statement loops through the values of an iterable object.
JavaScript While Loop
Loops can execute a block of code as long as a specified condition is true.

#Syntax

Example:
Do While Loop in Javascript
The do while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

#Syntax

Example:
JavaScript Break and Continue
The Break Statement
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a
switch() statement.

The Continue Statement


The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
JavaScript Sets
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set. The values can be
of any type, primitive values or objects.
JavaScript Set Methods
Set() Method:

add() Method:

has() Method:
Date & Time in Javascript
In JavaScript, date objects are created with new Date(), new Date() returns a date
object with the current date and time.

Get Methods in Javascript

The get methods return information from existing date objects. In a date object,
the time is static. The "clock" is not "running". The time in a date object is NOT the
same as current time.
Date & Time in Javascript
Get Methods
Date & Time in Javascript
getFullYear()

getMonth()

getDate()
Date & Time in Javascript
getDay(): get weekends.

getHours():

getMinutes()
JavaScript Maps
The map() method is used with arrays to create a new array by applying a function to each element of
the original array. It does not modify the original array.
const numbers = [1, 2, 3, 4, 5];

// Multiply each element by 2


const doubled = numbers.map(num => num * 2);

console.log(doubled);

Here:

● map() goes through each number in the array.

● It applies the arrow function num => num * 2.

● A new array is returned with each number doubled.


typeof Operator
The typeof operator returns the data type of a JavaScript variable.
Destructure in Javascript
Destructuring in JavaScript is a super useful feature that lets you unpack values from
arrays or objects into distinct variables.
JavaScript Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. The search
pattern can be used for text search and text replace operations.

Using String Methods


In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.
String Formatting
Modern Style
let name = "John Doe";
let age = 25;

var message = `Hello, my name is ${name} and I am ${age} years old.`;


console.log(message);

Old Style

var message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);
Error Handling in Javascript

When executing JavaScript code, different errors can occur. Errors can be coding errors
made by the programmer, errors due to wrong input, and other unforeseeable things.

Throw, and Try...Catch...Finally


The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.


Error Handling in Javascript

#Syntax
Error Handling in Javascript
Example:
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero.");
}

let result = a / b;
console.log(`Result: ${result}`);
} catch (error) {
console.error(`Error occurred: ${error.message}`);
} finally {
console.log("Division attempt completed.");
}
}

// Test cases
divideNumbers(10, 2); // Result: 5
divideNumbers(10, 0); // Error: Cannot divide by zero
Error Handling in Javascript
Types of error
Javascript Classes
classes are a template for creating objects. They are introduced in ES6 (ECMAScript 2015) and provide a
cleaner, more structured way to create objects and deal with inheritance compared to traditional prototype-based
syntax.
Javascript Classes

You might also like