0% found this document useful (0 votes)
22 views23 pages

JavaScript Document

JavaScript is a lightweight, cross-platform scripting language used to build dynamic webpages and web applications. It allows for client-side and server-side development. JavaScript contains objects like Array and Math and core elements like operators and statements. The DOM represents an HTML document as nodes and objects that JavaScript can manipulate. Functions and events allow JavaScript code to run when events occur. Common data types include String, Number, Boolean, and Object.

Uploaded by

speedfood
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
22 views23 pages

JavaScript Document

JavaScript is a lightweight, cross-platform scripting language used to build dynamic webpages and web applications. It allows for client-side and server-side development. JavaScript contains objects like Array and Math and core elements like operators and statements. The DOM represents an HTML document as nodes and objects that JavaScript can manipulate. Functions and events allow JavaScript code to run when events occur. Common data types include String, Number, Boolean, and Object.

Uploaded by

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

What is JavaScript?

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


interpreted compiled programming language. It is also known as the
scripting language for webpages. It is well-known for the development
of web pages, and many non-browser environments also use it.

JavaScript is a weakly typed language (dynamically typed).


JavaScript can be used for Client-side developments as well as Server-
side developments. JavaScript contains a standard library of objects,
like Array, Date, and Math, and a core set of language elements like
operators, control structures, and statements.

 Client-side: It supplies objects to control a browser and its


Document Object Model (DOM). Like if client-side extensions
allow an application to place elements on an HTML form and
respond to user events such as mouse clicks, form input, and page
navigation. Useful libraries for the client side are AngularJS,
ReactJS, VueJS, and so many others.

 Server-side: It supplies objects relevant to running JavaScript on a


server. For if the server-side extensions allow an application to
communicate with a database, and provide continuity of
information from one invocation to another of the application, or
perform file manipulations on a server. The useful framework
which is the most famous these days is node.js.
 Mobile Applications: JavaScript can also be used to build an
application for non-web contexts. The features and uses of
JavaScript make it a powerful tool for creating mobile
applications. This is a Framework for building web and mobile
apps using JavaScript. Using React Native, we can build mobile
applications for different operating systems. We do not require to
write code for different systems. Write once use it anywhere!

 Games: Not only in websites, but JavaScript also helps in creating


games for leisure. The combination of JavaScript and HTML 5
makes JavaScript popular in game development as well. It
provides the EaseJS library which provides solutions for working
with rich graphics.

JavaScript HTML DOM


The Document Object Model (DOM) is a programming interface for
HTML (HyperText Markup Language) and XML(Extensible markup
language) documents. It defines the logical structure of documents and
the way a document is accessed and manipulated.
When a web page is loaded, the browser creates a Document Object
Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:

 JavaScript can change all the HTML elements in the page


 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page
How to Link JavaScript in HTML?
JavaScript can be added to HTML file in two ways:
 Internal JS: We can add JavaScript directly to our HTML file by
writing the code inside the <script> tag. The <script> tag can
either be placed inside the <head> or the <body> tag according to
the requirement.
Note: Placing scripts at the bottom of the <body> element
improves the display speed, because script interpretation slows
down the display.
<script>// JavaScript Code</script>

 External JS: We can write JavaScript code in another files having


an extension.js and then link this file inside the <head> tag of the
HTML file in which we want to add this code.

<script src="myScript.js"></script>

JavaScript Functions and Events


A JavaScript function is a block of JavaScript code, that can be
executed when "called" for.

For example, a function can be called when an event occurs, like


when the user clicks a button.
JavaScript Data types:
JavaScript has 8 Datatypes

1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype


The object data type can contain:
1. An object
2. An array
3. A date

Console log():
The log() method writes (logs) a message to the console.
The log() method is useful for testing purposes.
console.log("Hello world!");
HTML DOM Document write():
The write() method writes directly to an open (HTML) document
stream.
The write() method deletes all existing HTML when used on a loaded
document.
document.write("Hello World!");

Window alert():
The alert() method displays an alert box with a message and an OK
button.
The alert() method is used when you want information to come
through to the user.
alert("Hello! I am an alert box!!");

JavaScript Variables:
 Using var
 Using let
 Using const
 Automatically
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and
Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.

What is Good?
1. let and const have block scope.
2. let and const can not be redeclared.
3. let and const must be declared before use.
4. let and const does not bind to this.
5. let and const are not hoisted.

What is not Good?


1. var does not have to be declared.
2. var is hoisted.
3. var binds to this.

When to use JavaScript const?


Always declare a variable with const when you know that the value
should not be changed.
Use const when you declare:
 A new Array
 A new Object
 A new Function
 A new RegExp
Declaring a variable:
Variables are containers for storing information.
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword.
A variable declared without a value have the value undefined.
var name = value; or let name = value;

JavaScript String:
A JavaScript string stores a series of characters like "Sample Text".
A string can be any text inside double or single quotes.
The first character is in position 0, the second in 1, and so on.
var name = "Volvo XC60";

JavaScript Number:
JavaScript has only one type of number.
Numbers can be written with, or without, decimals:
let x = 3.14; // A number with decimals
let y = 34; // A number without decimals
JavaScript Booleans:
JavaScript Booleans can have one of two values: true or false.
let x = false;

JavaScript BigInt:
JavaScript BigInt variables are used to store big integer values that are
too big to be represented by a normal JavaScript Number.
var x = BigInt("123456789012345678901234567890");

To create a BigInt, append n to the end of an integer or call BigInt():


var x = 9999999999999999n;

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.
EXERCISE: Check if the value entered through prompt is even number
or not
JavaScript Arithmetic Operators:

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation

/ Division

% Modulus (Remainder)

++ Increment

-- Decrement
JavaScript Assignment Operators:

Operator Example Same As

= 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

The += Operator
The Addition Assignment Operator adds a value to a variable.
let text = "Hello"; text += " World";
The -= Operator
The Subtraction Assignment Operator subtracts a value from a variable.
let x = 10; x -= 5;

The *= Operator
The Multiplication Assignment Operator multiplies a variable.
let x = 10; x *= 5;

The **= Operator


The Exponentiation Assignment Operator raises a variable to the power
of the operand.
let x = 10; x **= 5;

The /= Operator
The Division Assignment Operator divides a variable.
let x = 10; x /= 5;

The %= Operator
The Remainder Assignment Operator assigns a remainder to a variable.
let x = 10; x %= 5;
JavaScript Comparison Operators:

Operator Description Comparing

== equal to a == b

=== equal value and equal type a === b

!= not equal a != b

!== not equal value or not equal type a !== b

> greater than a>b

< less than a<b

>= greater than or equal to a >= b

<= less than or equal to a <= b

JavaScript Logical Operators:


Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x == 5 || y == 5) is false

! not !(x == y) is true

EXERCISE: Write a JavaScript expression to calculate the average of


three numbers, a, b, and c.
EXERCISE: Create a JavaScript function that takes two parameters,
num1 and num2, and returns the larger of the two numbers.

Math methods:
 Math.random()
 Math.floor()
 Math.sqrt()
 Math.min(23,88,01)
 Math.max(839,347,99,2)
 Math.pow(x,y) x raise to y

Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive). Math.random() always returns a number lower than 1.
Math.random();

Math.floor()
The Math.floor() method rounds a number DOWN to the nearest
integer.
Math.floor(1.6);

Math.sqrt()
The Math.sqrt() method returns the square root of a number.
Math.sqrt(64);

Math.min()
The Math.min() method returns the number with the lowest value.
Math.min(0, 150, 30, 20, 38);

Math.max()
The Math.max() method returns the number with the highest value.
Math.max(0, 150, 30, 20, 38);

Math.pow()
The Math.pow() method returns the value of x to the power of y.
Math.pow(4, 3);

EXERCISE: Write a JavaScript function called "convertFeetToInches" that


takes a number of feet as a parameter and converts it to inches. Use
the multiplication operator (*) to perform the conversion. The function
should return the converted value in inches.

JavaScript String Methods:


1. JavaScript String length()
The length property returns the length of a string. The length property
of an empty string is 0.
text.length;

2. JavaScript String replace():


The replace() method searches a string for a value or a regular
expression.
The replace() method returns a new string with the value(s) replaced.
The replace() method does not change the original string.
string.replace(searchValue, newValue);

3. JavaScript String toUpperCase():


The toUpperCase() method converts a string to uppercase letters.
The toUpperCase() method does not change the original string.
text.toUpperCase();

4. JavaScript String toLowerCase():


The toLowerCase() method converts a string to lowercase letters.
The toLowerCase() method does not change the original string.
text.toLowerCase ();

5. JavaScript String concat():


The concat() method joins two or more strings.
The concat() method does not change the existing strings.
The concat() method returns a new string.
text1.concat(text2);

6. JavaScript String trim():


The trim() method removes whitespace from both sides of a string.
The trim() method does not change the original string.
text.trim();

7. JavaScript String indexOf():


The indexOf() method returns the position of the first occurrence of a
value in a string.
The indexOf() method returns -1 if the value is not found.
The indexOf() method is case sensitive.
string.indexOf(searchvalue, start);

8. JavaScript String lastIndexOf():


The lastIndexOf() method returns the index (position) of the last
occurrence of a specified value in a string.
The lastIndexOf() method searches the string from the end to the
beginning.
The lastIndexOf() method returns the index from the beginning
(position 0).
The lastIndexOf() method returns -1 if the value is not found.
The lastIndexOf() method is case sensitive.
string.lastIndexOf (searchvalue, start);

9. JavaScript String search():


The search() method matches a string against a regular expression **
The search() method returns the index (position) of the first match.
The search() method returns -1 if no match is found. The search()
method is case sensitive.
string.search(searchValue);

10. JavaScript String slice():


The slice() method extracts a part of a string.
The slice() method returns the extracted part in a new string.
The slice() method does not change the original string.
string.slice(start, end);

11. JavaScript String match():


The match() method matches a string against a regular expression **
The match() method returns an array with the matches.
The match() method returns null if no match is found.
string.match(match);

JavaScript parseInt():
The parseInt method parses a value as a string and returns the first
integer.
parseInt("10");

JavaScript inNaN():
In JavaScript NaN is short for "Not-a-Number".
The isNaN() method returns true if a value is NaN.
The isNaN() method converts the value to a number before testing it.
isNaN('Hello');

JavaScript toString():
The toString() method returns a string as a string.
The toString() method does not change the original string.
method can be used to convert a string object into a string.
toString('Hello');

JavaScript HTML DOM Elements


Document getElementsByClassName():
The getElementsByClassName() method returns a collection of
elements with a specified class name(s).
The getElementsByClassName() method returns an HTML Collection.
The getElementsByClassName() property is read-only.
document.getElementsByClassName(classname);

Document getElementsByTagName():
The getElementsByTagName() method returns a collection of all
elements with a specified tag name.
The getElementsByTagName() method returns an HTMLCollection.
The getElementsByTagName() property is read-only.
getElementsByTagName("*") returns all elements in the document.
document.getElementsByTagName(tagname);

Input Text value Property


The value property sets or returns the value of the value attribute of a
text field.
The value property contains the default value OR the value a user types
in (or a value set by a script).
document.getElementById("fname").value;

Modifying attribute
1. src:
The src property sets or returns the value of the src attribute of a script.
The src attribute specifies the URL of an external script file.
document.getElementById("myScript").src;

2. setAttribute:
The setAttribute() method sets a new value to an attribute.
If the attribute does not exist, it is created first.
element.setAttribute(name, value);

3. getAttribute:
The getAttribute() method returns the value of an element's attribute.
element.getAttribute(name);

4. removeAttribute:
The removeAttribute() method remove the attribute from an element.
element.removeAttribute(name);
EXERCISE : Check whether the number is even or odd
EXERCISE : Check whether input is a number or not
EXERCISE : Find the largest of the 2 numbers
EXERCISE : Find the largest of the 3 numbers
EXERCISE : Check if a year is a leap year or not

You might also like