0% found this document useful (0 votes)
3 views60 pages

Java ScriptNotes

JavaScript is a widely-used programming language for creating interactive web pages, developed by Brendan Eich in 1995 and standardized as ECMAScript. It is a client-side, interpreted, dynamically-typed, and weakly-typed language, with features like variables, functions, and various data types. JavaScript supports multiple programming paradigms, including functional and object-oriented programming, and offers a variety of built-in methods for manipulating arrays and objects.

Uploaded by

movie user
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views60 pages

Java ScriptNotes

JavaScript is a widely-used programming language for creating interactive web pages, developed by Brendan Eich in 1995 and standardized as ECMAScript. It is a client-side, interpreted, dynamically-typed, and weakly-typed language, with features like variables, functions, and various data types. JavaScript supports multiple programming paradigms, including functional and object-oriented programming, and offers a variety of built-in methods for manipulating arrays and objects.

Uploaded by

movie user
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Java Script

// JS
Javascript
 JavaScript is the most popular programming language which is
used to create interactive webpages
 JavaScript is the client-server side scripting language which is
used to create dynamic web pages
 JavaScript was invented by Brendan Eich in 1995, and became an
ECMA(European computer manufacturing association) standard
in 1997.
 ECMA-262 is the official name of the standard. ECMAScript is the
official name of the language.
 Current version of JS is ES6 (introduced after 2015)
Characteristics of JavaScript
 Client-side scripting language : The code is readable
analyzable and executable by browser itself.
 Interpreted Language : JavaScript is an interpreted language,
meaning it is executed line by line at runtime.
 Dynamically types Language : JavaScript is dynamically-
typed, which means you don't need to specify the data type of a
variable when declaring it. The type is determined at runtime.
 Weakly Typed Language : Semicolon is not mandatory at all
the time
 Synchronous in nature : It will executes line by line , we can
make it as asynchronous
Advantages of JS

 Easy to learn and implement


 Reduces server load
 Efficient performance
 Regular updates
 Platform independent
 It has more frameworks and libraries
Environmental Setup
 We can run JavaScript code in two environments.
 Browser
 Node.js
 Every browser consists of JavaScript engine which helps to run JS
code

Browser JS engine
Chrome V8
Mozilla Firefox Spider monkey
Microsoft Edge Chakra
Safari JavaScript Core Webkit
How to include JS in HTML

 Wecan insert JS code to HTML in two


ways

1.Internal JS
2.External JS
Output Methods

 Console.log(“hello”)
 It will print the output in console window
 Document.write(“Hello”)
 It will print the output in user interface
Tokens

 Building blocks of every programming language

1. Keywords : Predefined words whose task is already predefined

2. Identifiers : The name given for the variables ,arrays , objects


etc..
3. Literals : The values written by developer
Variables
 In JavaScript We have 3 keywords to declare variables(var , let , const)
 Syntax To declare variable:
var/let/const identifier;//declaration
var/let/const identifier=value;//declaration along with
initialization
Var , let and const

var Let Const

Declaration yes yes Declaration with


initialization

Initialization Yes Yes No

Reinitialization Yes Yes No

Redeclaration Yes No No

Scope Global scope Script scope Script scope

Hoisting Yes No no
Hoisting
 Hoisting is JavaScript's default behavior of moving all
declarations to the top of the current scope (to the top of the
current script or the current function).
 In JavaScript, a variable can be declared after it has been used.

Example:

console.log(myVar); // Outputs: undefined


var myVar = 42;
The let and const Keywords

 Variables defined with let and const are hoisted to the top of
the block, but not initialized.
 Meaning: The block of code is aware of the variable, but it cannot
be used until it has been declared.
 Using a let variable before it is declared will result in
a ReferenceError.
 The variable is in a "temporal dead zone" from the start of the
block until it is declared:
 A temporal dead zone (TDZ) is the area of a block where a
variable is inaccessible until the moment the computer
completely initializes it with a value.
Datatypes in JS
 Datatype defines the type of data to be stored in a particular
memory allocation
JavaScript has 8 Datatypes(primitive)
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol

 Non primitive
A function
An object
An array
Datatypes
 String : We can declare the string in js in 3 ways
 Example : ‘hello’ ,”hello” ,`Hello everyone`
 Number : Integer and floating point numbers
 Boolean : True or false
 Bigint : large amount of data
 Undefined : It represents the value of an uninitialized values
 Null : It is empty variable and for future use
 Symbol : It will create function
Operators in JS
 Predefined symbols used to perform particular task
 Types of operators
• Arithmetic Operators : +,-,*,/,%,++,--
• Assignment Operators : +=,-=,*=,/=,%=,=
• Comparison Operators : >,<, !=,>=,<=,==,===
• Logical Operators : && , || , !
• Ternary Operators : ( condition ) ? True stmt : false stmt
Conditional Statements
 Conditional statements are used to perform different actions
based on different conditions.
•Use if to specify a block of code to be executed, if a specified
condition is true
•Use else to specify a block of code to be executed, if the same
condition is false
•Use else if to specify a new condition to test, if the first condition
is false
•Use switch to specify many alternative blocks of code to be
executed
Loops in JS

 Loops can execute a block of code a number of times

while loop : Repeats a statement or group of statements while a


given condition is true. It tests the condition before executing the
loop body

Do while loop : It is more like a while statement, except that it


tests the condition at the end of the loop body.

For loop : Executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable
Functions In JS
 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).
 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.

 Syntax :
 function myFunction(p1, p2) {
return p1 * p2;
}
JavaScript Function Syntax

 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: {}
Types of Functions in JS

1. Anonymous function
2. Named function
3. Function with expression
4. Nested function
5. Immediate invoking function
6. Arrow function
7. Higher order function
8. Callback function
9. Generator function
1.Anonymous function

 A function without name is known as Anonymous function

 Syntax :
 function(parameters) {
// function
body
}
2. Named Function

 A function with name is called as named function

 Syntax :
 function functionName(parameters) {

// function body

}
3 . Function with expression

 It is the way to execute the anonymous function


 Passing whole anonymous function as a value to a variable is
known as function with expression.
 The function which is passed as a value is known as first class
function

EX : let x=function(){
//block of code
}
x();
Nested function
 A function which is declared inside another function is known as nested
function.
 Nested functions are unidirectional i.e., We can access parent function
properties in child function but vice-versa is not possible.
 The ability of js engine to search a variable in the outer scope when it is
not available in the local scope is known as lexical scoping or scope
chaining.
 Whenever the child function needs a property from parent function the
closure will be formed and it consists of only required properties.
 A closure is a feature of JavaScript that allows inner functions to access
the outer scope of a function. Closure helps in binding a function to its
outer boundary and is created automatically whenever a function is
created. A block is also treated as a scope since ES6. Since JavaScript is
event-driven so closures are useful as it helps to maintain the state
between events.
Nested function
Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
Child();
}
Parent();
JavaScript currying
 Calling a child function along with parent by using one more
parenthesis is known as java script currying
 Example:
Function parent(){
let a=10;
function child(){
let b=20;
console.log(a+b);
}
return child;
}
parent()(); ==JavaScript currying
Immediate invoking function(IIF)

 A function which is called immediately as soon as the function


declaration is known as IIF
 We can invoke anonymous function by using IIF
 Example:

(function(){
console.log(“Hello”);
})();
Arrow function

 It was introduced in ES6 version of JS.


 The main purpose of using arrow function is to reduce the syntax.
 If function has only one statement then block is optional.
 It is mandatory to use block if function consists of multiple lines
of code or if we use return keyword in function.
 Example:
Let x=(a,b)=>console.log(a+b);
Let y=(a,b)=>{return a + b };
Higher order function(HOF)
 A function which accepts a function as a parameter is known as HOF
 It is used to perform multiple operations with different values.
 Example:
Function hof(a , b , task ){
Let res=task(a,b);
return res;
};
Let add=hof(10,20,function(x , y){
return x + y;
}
Let mul = hof(10,20,function(x , y){
return x*y;
}
Console.log(add());
Console.log(mul());
Callback function
 A function which is passed as an argument to another function is known as
callback function.
 The function is invoked in the outer function to complete an action
 Example :
function first(){
Console.log(“first”);
}
function second(){
Console.log(“third”);
}
function third(callback){
Console.log(“second”);
Callback()
}
first();
third(second);
Generator function
 A generator-function is defined like a normal function, but
whenever it needs to generate a value, it does so with the yield
keyword rather than return.
 Example:
Function* gen(){
Yield 1;
Yield 2;
…….
………
}
Let res=gen();
Console.log(res.next().value);
Console.log(res.next().value);
JAVASCRIPT ARRAYS
ARRAYS:- Array is collection of different elements.Array is heterogrnous in nature.

• In javascript we can create array in 3 ways.

1. By array literal
2.By using an Array constructor (using new keyword)

1) JavaScript array literal:-


• The syntax of creating array using array literal is: var
arrayname=[value1,value2.....valueN];
• As you can see, values are contained inside [ ] and separated by ,
(comma).
Ex:-<script>
• The .length property returns the length of an array.
var emp=["Sonoo","Vimal","Ratan"]; Output
for (i=0;i<emp.length;i++) Sonoo
{ document.write(emp[i] + "<br/>"); Vimal
}
</script> Ratan
2) JavaScript array constructor (new keyword):-
Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.

Ex:-
<script>
var emp=new
Array("Jai","Vijay","Smith"); for
(i=0;i<emp.length;i++)
{ document.write(emp[i] +
"<br>");
}
</script>

Output:-
Jai
Vijay
Smith
Java script Array methods
 push() : It will insert an element of an array at the end
 unshift() : It will insert an element of an array at the first
 pop() : It will remove elements of array from the end
 shift() : It will remove elements of array from the start
 indexOf() :It will return a index of particular element
 Includes() : It will check whether the particular element is present
in array or not.
 At() : It will return the element which is present in particular
index.
 Slice() : It will give slice of an array and it will not affect the
original array.
 Splice() : It is used to add or remove elements from an array
Java script Array methods

 Join() : It is used to join all elements of an array into a string.


 Concat() : It is used to join/concat two or more arrays.
 Split() : It is used to split a string into an array.
 Reverse() : It is used to reverse an array.
Filter() , map() , reduce()
 Filter() :
 The filter() method in JavaScript is used to create a new array with all elements
that pass a test specified by a provided function. It does not modify the original
array.
 Example :
 let newArray = array. Filter(callback(element[, index, array]){
thisArg;
}

•callback: This is the function that is used to test each element in the array. It takes three
arguments:
•element: The current element being processed in the array.
•index (optional): The index of the current element being processed.
•array (optional): The array filter was called upon.
•thisArg (optional): Value to use as this when executing callback.
Filter() , map() , reduce()
 Map() :
The map() method in JavaScript is used to create a new array by
applying a function to every element in an existing array. It does not
modify the original array. Instead, it returns a new array with the modified
elements.
EX:

const numbers = [1, 2, 3, 4, 5];


const doubledNumbers = numbers. Map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Filter() , map() , reduce()

 Reduce() :
The reduce() method in JavaScript is used to apply a function to an accumulator
and each element in an array, in order to reduce it to a single value. It iterates
over each element in the array and accumulates a value based on the provided
function.
 Ex :
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Objects in JS
 Object is nothing but the thing which has existence in the world.
 A JavaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
 In java script object is used to store the data in key value pairs.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 Objects are mutable.

 We can access , update, add and delete the properties from an object.
OBJECTS IN JAVASCRIPT
• A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

• JavaScript is an object-based language. Everything is an object in JavaScript.

Creating Objects in JavaScript:

There are 3 ways to create

objects. 1.By object literal.

2.By creating instance of Object directly (using new

keyword).
OBJECTS IN JAVASCRIPT

• A JavaScript object is an entity having state and behavior (properties and


method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

• JavaScript is an object-based language. Everything is an object in JavaScript.


Creating Objects in JavaScript:

There are 3 ways to create objects. 1.By object

literal.

2.By creating instance of Object directly (using new keyword).


3.By using constructor function
1)JavaScript Object by object literal:

The syntax of creating object using object literal is given below:


VariableName object=
{
property1:value1,
property2:value2,
propertyN:valueN
}
As you can see, property and value is separated by : (colon).

Example of creating object in JavaScript.


<script>
Let emp={
id:102,
name:"Kumar", salary:40000
}
document.write(emp.id+" "+emp.name+"
"+emp.salary);
</script>
2) By creating instance of Object:

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Example of creating object directly.

<script>
var emp=new Object(); emp.id=101;
emp.name="Ravi"; emp.salary=50000;
document.write(emp.id+" "+emp.name+"
"+emp.salary);
</script>
3) By using an constructor function:

• Here, you need to create function with arguments. Each argument value can
be assigned in the current object by using this keyword.
• The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
Var e=new
emp(103,"Vimal
Jaiswal",30000);
In JavaScript, there are two main ways to access and manipulate object properties: dot
notation and bracket notation.
1. Dot notation
Dot notation is the most common way to access object properties. It uses a period (.) to access the value of a property by its key.
Here’s an example:
const person = {
name: 'John',
age: 30,
address: {
street: '123
Main St',
city: 'New York'
}
};
console.log(person.name); // John
console.log(person.address.city);
Bracket notation, on the other // Newhand,
York uses square brackets [] to access the
value of a property by its key.
Here’s an example:
console.log(person['name']); // John
console.log(person['address']['city']); // New
York
OBJECT METHODS
• Objects can also have methods.
• Methods are actions that can be performed on objects.

OBJECT METHODS:

1.keys : It will return array of keys


2.Values : It will return array of values
3.Entries : It will return array of keys and values
4.Assign : It is used to merge two objects
5.Seal : We can only update the properties
6.isSealed : It is used to check whether the particular object is sealed or not
7.Freeze : We cannot do any modifications in an object
8.Isfrozen : It is used to check whether the particular object is frozen or not
9.hasOwnProperty : It is used to check whether the particular property is present in
an object or not.
let obj4={
ename:"lavanya",
id:123,
sal:20000
};
let obj5={
ename1:"bujj
i", id1:12,
sal1:40000
};
console.log(Object.keys(obj4));//array of keys
console.log(Object.values(obj4))//array of values
console.log(Object.entries(obj4))//array of keys and values
console.log(Object.assign({},obj4,obj5))//merge multiple
objects console.log(obj4)//stroring all properites of obj5
into obj4 Object.seal(obj4);//In seal method i can update
can’t add,i cant remove,can
fetch
console.log(Object.isSealed(obj4));//true
delete obj4.ename;
console.log(obj
4)

obj4.sal=12000;
console.log(obj4);
console.log(obj4.sal
);

Object.freeze(obj4);
console.log(Object.isFrozen(obj4))//
true obj4.skills="html";
obj4.sal=300;
console.log(obj
4)
console.log(obj4)//freeze object we cant add,we cant
update,we cant delete,we can fetch
delete obj4.id
console.log(obj4);
console.log(obj4.hasOwnProperty("ename"));//if the property is
present means it will return true else false
LOOPS IN JAVASCRIPT

• Loops can execute a block of code a number of times.


• foreach - loops through a block of code a number of times
• for/in - loops through the properties of an object
• for/of - loops through the values of an iterable object

Foreach():-
The forEach() method calls a function for each element in an array.
The forEach() method is not executed for empty elements.

Example:

const array1 = ['a', 'b', 'c’];

array1.forEach((element) => console.log(element));


Output:- 1
2
3
4
5

For of loop:-
Iterable objects are objects that can be iterated over with
for..of. <script> Ex:-const name = "W3Schools";
let text = ""
for (const x of
name){ text += x +
"<br>";
}
For in loop:-
The JavaScript for in loop iterates over the keys of an object
Ex:-

const object = { a: 1, b: 2, c: 3 }; for


(const property in object) {
console.log(`${property}: $
{object[property]}`);
}

// Expected output:
// "a: 1“
// "b: 2“
// "c: 3“

DATE OBJECT:-

• When a date object is created,


a number of methods allow
you to operate on it.
Creating Date Objects
Date objects are created with the new Date() constructor. There are 9 ways to
create a new date object:

new Date()
new Date(date string)
new Date(year,month)
new Date(year,month,day)
new Date(year,month,day,hours)
new Date(year,month,day,hours,minutes)
new Date(year,month,day,hours,minutes,seconds)
new Date(year,month,day,hours,minutes,seconds,ms)
new Date(milliseconds)

JavaScript new Date():-


new Date() creates a date object with the current date and time:
Const d= new Date( );
console.log(d);
Output:-
Sun Aug 27 2023 18:42:42 GMT+0530 (India Standard Time)
MATH OBJECT

• The JavaScript Math object allows you to perform mathematical tasks on numbers.

• Unlike other objects, the Math object has no constructor.


• The Math object is static.
• All methods and properties can be used without creating a Math object first.
• The syntax for any Math property is : Math. method(number)
Math.round(x) Returns x rounded to its nearest integer

Math.ceil(x) Returns x rounded up to its nearest integer

Math.floor(x) Returns x rounded down to its nearest integer

Math.trunc(x) Returns the integer part of x (new in ES6)


1.Math.round(4.6
); 4.Math.trunc(4.9
OUTPUT:-5 );
Math.round(4.5); Math.trunc(4.7);
OUTPUT:4
Math.trunc(4.4);
Math.round(4.4); Math.trunc(4.2);
OUTPUT:4 Math.trunc(-
Output:
4.2);
2.Math.ceil(4.9) 4
;
Math.ceil(4.7);
Math.ceil(4.4);
Math.ceil(4.2);
output:-5

3.Math.floor(4.9
);
Math.floor(4.7);
Math.floor(4.4);
Math.floor(4.2);

Output:4
STRING CONCEPT IN JAVASCRIPT

STRING:-Collection of characters (or) bunch of characters we called it as


string
String methods:-

String length String trim()


String slice() String charAt()
String substring() String charCodeAt()
String substr() String split()
String replace()
String toUpperCase()
String toLowerCase()
String concat()
1. The length property returns the length of a string:

Ex:-
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.log(text.length)//26

2.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).
Ex:-
let text = "Apple, Banana,
Kiwi"; let part =
text.slice(7,13);//banana

3.substring( ):- it is similar to


slice( ) Syntax:-
substring(start,end)
The difference is that substring( ) cannot accept negative
indexes. Ex:-
let text = "Apple, Banana, Kiwi";
let part = text.substring(7,13);//banana
4.substr( ):-
Substr( ) is similar to slice( )
The difference is that the second parameter specifies the length of the extracted
part.
Ex:-
let text = "Apple, Banana, Kiwi";
let part = text.substr(7,6);//banana

5.replace( ):-The replace method replaces a specified value with another value in a
string By default,the replace( ) method replaces only the first match.
Ex:-
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", “js");//”please visit js

6.trim( ):-
The trim( ) method removes whitespace from both sides of a
string. Ex:-
let text1 = " Hello World! ";
let text2 = text1.trim();//hello world!
7.indexOf( ):-
The indexOf( ) method returns the index of the position of the first occurrence of a
specified text in a string.
indexOf( ) return -1 if the text is not found.
Ex:-
Let str=“please locate where ‘locate’ occurs!”;
str.indexOf(“locate”);//7
Str.indexOf(“locate”);//-1
8.lastIndexOf( ):-
The lastIndexOf() method of String values searches this string and returns the index of
the last occurrence of the specified substring. It takes an optional starting position and
returns the last occurrence of the specified substring at an index less than or equal to
the specified number.
Ex:-
Let str=“please locate where ‘locate’ occurs!”;
str.indexOf(“locate”);//21
Str.indexOf(“locate”);//-1
9.Includes( ):-

The includes() method returns true if a string contains a specified


string.
Otherwise it returns false.
The includes() method is case sensitive.

Syntax:-string.includes(searchvalue, start)

Ex:-
let text = "Hello world, welcome to the universe.";
let result = text.includes("world");//true

10.repeat( ):-
The repeat() method returns a string with a number of copies of a
string. The repeat() method returns a new string.
The repeat() method does not change the original string
let text = "Hi";
let result = text.repeat(2);//hi hi

11.charAt( ):-

it will return the character of the specified position

Ex:-
var str=“hi guys”
Console.log(str.charAt(3));//g

12.charCodeAt( ):-

It will return the ASCII value of specified index value of that


character. Ex:-
Ex:-var str=“javascript”
Console.log(str.charCodeAt(1));//97
Split( ):-covert string to array.
Join( ):-convert array to string

You might also like