Java script
Javascript:
JavaScript is a powerful programming language that can add
interactively to a website.
A scripting language is a computer programming language that
provides instructions, called scripts, for software in apps and
websites.
Why we need js:
Its an event based programming lanagauge.
Click, double click, right click ,left click, drag and drop, key
press ,load etc..
Java is very versatile as it is used for programming
applications on the web, mobile, desktop, etc.
Use of js in web development:
Drop down menu
Animated slider
Maps
Charts graphs
Audio
Video player
Zoom effect
Form validation
Java script
Requirement of software in js:
Html editor : note pad, notepad++,vs code, etc
Web browser: google chrome ,Mozilla
firebox,internet explorer…
2 ways to implement the js:
In page JavaScript
External js
In page or internal page:
<html>
<head>
<script>
document. Write(“hello”);
</script>
</head>
<body>
<h1>hello</h1>
<script>
</script>
</body>
</html>
Java script
External js:
Make a separate file and give the name as .js
Example: myfile.js
<head>
<script src=“myfile.js”></script>
</head>
OUTPUT DISPLAY:
Document.write(“hello”); :its used to display some
string in the output of the html page .document.write
in js is methods or functions in js
Alter(“hii”) : this method is used to alter the message
.
Comsole.log(“welcome”); its build in function that
allows you to output message to console .
Its commomnly used in browder to debugging your
code.
JavaScript Statements:
A computer program is a list of "instructions" to be
"executed" by a computer.
In a programming language, these programming
instructions are called statements.
EXAMPLES:
"Hello Dolly."
Java script
JavaScript Comments:
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:
Multi-line 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).
This example uses a single-line comment before
each code line:
EXAMPLE:
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>
Multi-line Comments:
Java script
It is represented by forward slash with asterisk then
asterisk with forward slash. For example:
/* your code here */
EXAMPLE :
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comm
ent");
</script>
JavaScript Variables:
Variables are Containers for Storing Data
JavaScript Variables can be declared in 3 ways:
• Using var
• Using let
• Using const
Rules for declaring the variable:
Must begin with a letter, or $, or _
Names are case sensitive (y and Y are different)
Reserved JavaScript words cannot be used as
names like
Double , finally ,goto,else, arguments
Java script
We cant start with number donot use space between
two variable.
Using var:
Variables are containers for storing information.
Creating a variable in JavaScript is called "declaring"
a variable:
Syntax: var name = value;
Example : var carName;
o assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you
declare it:
var carName = "Volvo";
Example:
var x= 5;
var y= 6;
var z = x + y;
LET VARIABLE:
let is a keyword that is used to declare a block
scoped variable.
A block-scoped variable is a variable that can only be
accessed within the block where it was declared.
Syntax of let:
let variable_name;
example :
Java script
<script>
{
let num = 30;
document.write("Inside the function num = " + nu
m);
}
document.write("<br> Outside the function num =
" + num);
</script>
CONSTANT VARIABLES:
Java script key word const is used tho declared the
constant values and cannot be reassigned the
values .once it declare the value it cant be change.
Example:
Pi = 3.14159;
JavaScript Operators:
There are different types of JavaScript operators:
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
Java script
• Logical Operators
• Bitwise Operators
• Ternary Operators
JavaScript Arithmetic Operators:
Arithmetic Operators :are used to perform
arithmetic on numbers.
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
JavaScript Assignment Operators:
The = Operator
Java script
The Simple Assignment Operator assigns a value
to a variable.
Example:
let x = 10;
The += Operator compound operator
The Addition Assignment Operator adds a value
to a variable.
Example:
A+=b
A=a+b;
The -= Operator
The Subtraction Assignment Operator subtracts a
value from a variable.
Example:
a-=b
The *= Operator
The Multiplication Assignment
Operator multiplies a variable.
Example:
let x = 10;
x *= 5;
The **= Operator
The Exponentiation Assignment Operator raises
a variable to the power of the operand.
Java script
Example:
let x = 10;
x **= 5;
The /= Operator
The Division Assignment Operator divides a
variable.
Example:
let x = 10;
x /= 5;
The *= Operator
The Multiplication Assignment
Operator multiplies a variable.
Example:
let x = 10;
x *= 5;
The **= Operator
The Exponentiation Assignment Operator raises
a variable to the power of the operand.
Example:
let x = 10;
x **= 5;
The /= Operator
The Division Assignment Operator divides a
variable.
Example:
Java script
let x = 10;
x /= 5;
Bitwise Assignment Operators:
Bitwise operator works on bit that’s 0 and 1
Bitwise AND(&) a&b
Bitwise OR(|) a|b
Biwise XOR(^) a^b
Bitwise NOT(~) a~b
Bitwise Left Shift(<<) a << b
Bitwise Right Shift(>>) a >> b
Java script
Zero Fill Right Shift(>>>) a >>> b
Comparison Operators:
Comparison operators are used in logical statements
to determine equality or difference between variables
or values.
Examples:
if (age < 18) text = "Too young to buy alcohol";
== equal to
!= not equal
> greater than
< less than
>= greater than or equal to
<= less than or equal to
Java script
? ternary operator
Logical Operators:
Logical operators are used to determine the logic
between variables or values.
Example :
Operator Description Example
&& And (x < 10 && y > 1) is true
|| Or (x == 5 || y == 5) is false
! Not !(x == y) is true
Java script
Conditional (Ternary) Operator:
JavaScript also contains a conditional operator that
assigns a value to a variable based on some
condition.
Short cut way to write if statement
Syntax
variablename = (condition) ? value1:value2
Example:
let voteable = (age < 18) ? "Too young":"Old
enough";
Java string operation:
JavaScript String Operators are used to manipulate
and perform operations on strings.
String Concatenate Operator
Concatenate Operator in JavaScript combines
strings using the ‘+’ operator and creates a new
string that includes the contents of the original strings
in which Concatenate string1 and string2,.
Example:
var str1 = "Geeks";
var str2 = "forGeeks";
var result = (str1 + str2);
console.log(result);
Java script
String Concatenate Assignment Operator:
In this, we perform a concatenation assignment by
using the ‘+=’ operator to add the value of a variable
or string to an existing string variable.
Syntax:
str1 += str2
Example:
var str1 = "Geeks";
Var str2 = "forGeeks";
// Concatenation assignment
str1 += str2;
console.log(str1)
JAVASCRIPT DATA TYPES:
JavaScript data types are divided into primitive and
non-primitive types.
Primitive Data Types: They can hold a single simple
value. String , Number , BigInt , Boolean , undefined , null , and Symbol are primitive
data types.
Non-Primitive Data Types: They can hold multiple values. Objects are
non-primitive data types.
There are altogether 7 basic data types in JavaScript.
Data Type Description Example
String Textual data. 'hello' , "hello world!" , etc.
Java script
Number An integer or a floating-point number. 3 , 3.234 , 3e-2 , etc.
BigInt An integer with arbitrary precision. 900719925124740999n , 1n , et
Boolean Any of two values: true or false . true and false
undefined A data type whose variable is not initialized. let a;
null Denotes a null value. let a = null;
Object Key-value pairs of collection of data. let student = {name: "John"};
JavaScript String
A string represents textual data. It contains a sequence of characters. For
example, "hello" , "JavaScript" , etc.
In JavaScript, strings are surrounded by quotes:
Single quotes: 'Hello'
Double quotes: "Hello"
For example:
// string enclosed within single quotes
let fruit = 'apple';
console.log(fruit)
For example:
// string enclosed within double quotes
let country = "USA";
Java script
console.log(country);
JavaScript Number:
In JavaScript, the number type represents numeric values (both integers
and floating-point numbers).
Integers - Numeric values without any decimal parts. Example: 3, -74,
etc.
Floating-Point - Numeric values with decimal parts. Example: 3.15, -
1.3, etc.
Examples:
// integer value
let integer_number = -3;
console.log(integer_number);
// floating-point value
let float_number = 3.15;
console.log(float_number);
JavaScript BigInt :
BigInt is a type of number that can represent very large or very small
integers beyond the range of the regular number data type.
A BigInt number is created by appending n to the end of an integer.
For example:
// BigInt value
let value1 = 900719925124740998n;
Java script
JavaScript Boolean
A Boolean data can only have one of two
values: true or false
let dataChecked = true;
console.log(dataChecked); // true
let valueCounted = false;
console.log(valueCounted); // false
JavaScript undefined:
In JavaScript, undefined represents the absence of a value.
If a variable is declared but the value is not assigned, then the
value of that variable will be undefined.
For example:
let name;
console.log(name); // undefined
JavaScript null:
In JavaScript, null represents "no value" or "nothing."
For example:
Java script
let number = null;
console.log(number); // null
JavaScript Object
An Object holds data in the form of key-value pairs.
For example,
let student = {
firstName: "John",
lastName: null,
class: 10
};
JS Control Flow Or Condition
JavaScript if Statement
We use the if keyword to execute code based on some specific
condition.
The syntax of if statement is:
if (condition) {
// block of code
}
Java script
The if keyword checks the condition inside the parentheses ().
If the condition is evaluated to true, the code inside { } is
executed.
If the condition is evaluated to false, the code inside { } is
skipped.
Example:
// Program to check if the number is positive
const number = 6;
// check if number is greater than 0
if (number > 0) {
// the body of the if statement
console.log("positive number");
}
console.log("nice number");
JavaScript else Statement
We use the else keyword to execute code when the condition
specified in the preceding if statement evaluates to false.
The syntax of the else statement is:
if (condition) {
// block of code
// execute this if condition is true
}
else {
// block of code
// execute this if condition is false
Java script
}
The if...else statement checks the condition and executes code
in two ways:
If condition is true, the code inside if is executed. And, the
code inside else is skipped.
If condition is false, the code inside if is skipped. Instead,
the code inside else is executed.
Example :
let age = 17;
// if age is 18 or above, you are an adult
// otherwise, you are a minor
if (age >= 18) {
console.log("You are an adult");
}
else {
console.log("You are a minor");
}
// Output: You are a minor
JavaScript else if Statement
We can use the else if keyword to check for multiple conditions.
The syntax of the else if statement is:
Java script
// check for first condition
if (condition1) {
// if body
}
// check for second condition
else if (condition2){
// else if body
}
// if no condition matches
else {
// else body
}
// rating of 2 or below is bad
// rating of 4 or above is good
// else, the rating is average
if (rating <= 2) {
console.log("Bad rating");
}
else if (rating >= 4) {
console.log("Good rating!");
}
else {
console.log("Average rating");
}
// Output: Good rating!
Java script
Nested if...else Statement:
When we use an if...else statement inside another if...else statement, we
create a nested if...else statement.
For example:
let marks = 60;
// outer if...else statement
// student passed if marks 40 or above
// otherwise, student failed
if (marks >= 40) {
// inner if...else statement
// Distinction if marks is 80 or above
if (marks >= 80) {
console.log("Distinction");
}
else {
console.log("Passed");
}
}
else {
console.log("Failed");
}
// Output: Passed
JavaScript for loop :
Java script
In JavaScript, the for loop is used for iterating over a block of code
a certain number of times.
for (initialsation; condition;increament) {
// for loop body
}
Example 1: Print Numbers From 1 to 5
for (let i = 1; i < 6; i++) {
console.log(i);
}
Output
1
2
3
4
5
Iteration Variable Condition: i < 6 Action
1 is pri
1st i=1 true
i is increased to 2.
2 is pri
2nd i=2 true
i is increased to 3.
3 is pri
3rd i=3 true
i is increased to 4.
4 is pri
4th i=4 true
i is increased to 5.
Java script
5 is pri
5th i=5 true
i is increased to 6.
6th i=6 false The loop is terminated.
JavaScript while and do...while
Loop:
JavaScript while Loop
The while loop repeatedly executes a block of code as long as a specified
condition is true .
The syntax of the while loop is:
while (condition) {
// body of loop
}
1. The while loop first evaluates the condition inside ( ).
2. If the condition evaluates to true , the code inside {} is executed.
3. Then, the condition is evaluated again.
4. This process continues as long as the condition evaluates to true .
5. If the condition evaluates to false , the loop stops.
Example 1: Display Numbers From 1 to 3
// initialize variable i
let i = 1;
// loop runs until i is less than 4
while (i < 4) {
console.log(i);
i += 1;
Java script
}
Run Code
Output
1
2
3
Here is how the above program works in each iteration of the loop:
Variable Condition: i < 4 Action
i=1 true 1 is printed. i is increased to 2.
i=2 true 2 is printed. i is increased to 3.
i=3 true 3 is printed. i is increased to 4.
i=4 false The loop is terminated.
JavaScript do...while Loop
The do...while loop executes a block of code once, then repeatedly executes it
as long as the specified condition is true .
The syntax of the do...while loop is:
do {
// body of loop
} while(condition);
Example 3: Display Numbers from 3 to 1
Java script
let i = 3;
// do...while loop
do {
console.log(i);
i--;
} while (i > 0);
Output
3
2
1
JavaScript break Statement
The break statement terminates the loop immediately when it's encountered
if (i == 3) {
break;
}
console.log(i);
}
Run Code
Output
1
2
JavaScript continue Statement:
Java script
The continue statement skips the current iteration of the loop and
proceeds to the next iteration.
/ display odd numbers
for (let i = 1; i <= 5; i++) {
// skip the iteration if i is even
if (i % 2 == 0) {
continue;
}
console.log(i);
}
// Output:
// 1
// 3
// 5
JavaScript switch...case
Statement:
Java script
The JavaScript switch...case statement executes different blocks of code
based on the value of a given expression.
Syntax of the switch...case Statement
switch (expression) {
case value1:
// code block to be executed
// if expression matches value1
break;
case value2:
// code block to be executed
// if expression matches value2
break;
...
default:
// code block to be executed
// if expression doesn't match any case
}
let day = 3;
let activity;
switch (day) {
case 1:
console.log("Sunday");
Java script
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
case 4:
console.log("Wednesday");
break;
case 5:
console.log("Thursday");
break;
case 6:
console.log("Friday");
break;
case 7:
console.log("Saturday");
break;
default:
console.log("Invalid Day");
}
Output
Tuesday
Difference between While and Do-While Loop
Parameter While Do-While
Loop body is executed after the given condition is Loop body is executed, and then the given
Definition evaluated. condition is checked.
Java script
Variable Variables are initialized before the execution of
Variables may initialize after the loop.
Initialization the loop.
Loop Type Entry Control Loop Exit Control Loop.
Semicolon Semicolon is not used as a part of the syntax. Semicolon is used as a part of the syntax.
while(condition){ do{
Syntax // loop body // loop body
} } while (condition);
JavaScript Objects:
JavaScript object is a variable that can store multiple data in key-
value pair.
Create JavaScript Objects
The syntax of JavaScript object is:
const objectName = {
key1: value1,
key2: value2,
...,
keyN: valueN
};
Here,
objectName - Name of the object.
key1: value1 - The first key-value pair.
key2: value2 - The second key-value pair.
Java script
keyN: valueN - The Nth key-value pair.
Each key-value pair has a colon : between them and is separated by a
comma , .
Access Object Properties
You can access the value of a property by using its key.
const dog = {
name: "Rocky",
};
// access property
console.log(dog.name);
JavaScript Array
An array is an object that can store multiple values at once.
const age = [17, 18, 15, 19, 14];
In the above example, we created an array to record the age of five students.
Why Use Arrays?
Arrays allow us to organize related data by grouping them within a single
variable.
Java script
Suppose you want to store a list of fruits. Using only variables, this process
might look like this:
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Orange";
Here, we've only listed a few fruits. But what if we need to store 100 fruits?
For such a case, the easiest solution is to store them in an array.
let fruits = ["Apple", "Banana", "Orange", ...];
Create an Array
We can create an array by placing elements inside an array literal [] ,
separated by commas. For example,
const numbers = [10, 30, 40, 60, 80];
Here,
numbers - Name of the array.
[10, 30, 40, 60, 80] - Elements of the array.
JavaScript Date and Time
Java script
In JavaScript, date and time are represented by the Date object.
The Date object provides the date and time information and also provides
various methods.
Creating Date Objects
There are four ways to create a date object.
new Date()
new Date(milliseconds)
new Date(Date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date()
You can create a date object using the new Date() constructor. For example,
const timeNow = new Date();
console.log(timeNow); // shows current date and time
Output
Mon Jul 06 2020
Here, new Date() creates a new date object with the current date and local time.
JavaScript Date Methods
There are various methods available in JavaScript Date object.
Java script
Method Description
Returns the numeric value corresponding to the current time (the number of milliseconds
now()
elapsed since January 1, 1970 00:00:00 UTC)
getFullYear() Gets the year according to local time
getMonth() Gets the month, from 0 to 11 according to local time
getDate() Gets the day of the month (1–31) according to local time
getDay() Gets the day of the week (0-6) according to local time
getHours() Gets the hour from 0 to 23 according to local time
getMinutes Gets the minute from 0 to 59 according to local time
getUTCDate() Gets the day of the month (1–31) according to universal time
setFullYear() Sets the full year according to local time
setMonth() Sets the month according to local time
Java script
Characteristics of JavaScript:
Scripting Language
JavaScript is an incredibly powerful scripting language, designed specifically for
powering immersive web applications. With its lightweight, browser-side execution
capabilities and tailored libraries aimed at providing the best possible experience in a
variety of scenarios – this versatile programming tool packs quite the punch!
Validation of User’s Input
Form validation is an integral part of the user experience on web pages, allowing
clients to ensure accuracy when users are entering data into forms. By offering this
service, both parties can be sure that all relevant details have been correctly filled out
– a key step in any successful interaction!
Ability to Perform In-build Function
Java Script boasts a wide repertoire of helpful In-Built Functions like Number(),
parseFloat(), and parseInt(). These functions come in handy for verifying numbers,
converting objects into numerical values, and analyzing strings – making it easier than
ever to work with data!
Case Sensitive Format
When programming in JavaScript, it’s best to be mindful of the case – capitalization
matters! That means if a code is written with one letter UPPER-cased and another
lower-cased, chances are you’ll get different results.
Light Weight and Delicate
JavaScript is an incredibly lightweight and dynamic programming language, allowing
for efficient code creation without the need to declare variables. Instead, only objects
are required in order to carry out all operations.
Java script
Statements Looping
Looping is a powerful tool used to execute the same code multiple times, allowing
developers to automate tedious and time-consuming tasks easily. This technique can
be employed with specified or indefinite repetition – giving software engineers more
control over their workflow!.
Control Statements
JavaScript is a powerful programming language that allows developers to conquer
tasks of any complexity, by leveraging control statements such as if-else-if and switch-
case or loops like for, while, and do-while. With JavaScript at their side, the possibilities
are endless!
Prototype-based
The way code is written has been revolutionized with JavaScript’s prototype-based
scripting language, which allows for quicker development cycles and efficient use of
memory. Rather than using classes to determine object types, it makes use of a
prototypal inheritance model – much like an Object factory method.
This pattern can be found throughout JavaScript code, optimizing the speed and
reliability of coding projects.
Java script
JavaScript keyboard events
The JavaScript provided keyboard events for the selection, type, and use
of particular forms of information. The event occurs when the key presses
the key up and the key down as per action.
Types of the keyboard event
The JavaScript provides the following types of events to use keyboard
functionality.
o Keydown event: Keydown occurs when the key is depressed and
continuously repeats if the key is depressed for an extended time.
o Keyup event: When a punctuation, numeric, or alphabetic key is
pushed, then the keyup event is triggered and starts functionality.
o Keypress event: When the key is released from the user, the keyup
event occurs and starts functionality. Some browsers no longer
support Keypress Event.