JS Students Notes-1
JS Students Notes-1
History of javascript:
next--> JAVASCRIPT
FEATURES OF JAVASCRIPT:
1)Light Weight
2)interpreted language
6)Synchronous language
Javascript characteristics:
1. Client-side-Scripting language - no compiler and without help of server logic we can update the data
2. High-level language - user-friendly
3. Interpreted language – line by line execution
4. Loosely typed – no strong syntax
5. Dynamic language – can change the datatype during the runtime
6. Object-based language – In JavaScript everything was object
Uses of JavaScript:
1.document.write()
document.write() is a printing statement which is used to see the output in the web browser (client
purpose)
2.console.log()
Console.log() is a printing statement which is used to see the output in the console window
(developer view)
Here, console. is an object , dot is a period (or) access operator and log is a function and member of console.
that accepts argument as data to print in console.
TOKENS:
In JavaScript, a token is the smallest unit of a program that is meaningful to the interpreter.
JavaScript code is made up of various types of tokens, including
1. Keywords:
Reserved words that have special meanings in the language. Examples include var, if, else, for, while,
etc.
NOTE: Every keyword must be in the lower case and it is not used as Identifiers.
2. Identifiers:
These are names that are used to identify variables, functions, and other objects. For example, the
identifier myVariable could be used to identify a variable that stores the value 5.
Rulers: -an identifiers can't start with number. -We can’t use keywords as identifiers. -Except $, _ no
other Special Characteristics are allowed.
3.Literals:
Data which is used in the js programming is called as literals. For example, the literal 5 is a numeric
literal, and the literal "Hello, world!" is a string literal.
4. Operators:
These are symbols that are used to perform operations on operands. For example, the operator + is used to add
two numbers together.
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
i. .
There are five types of primitive data types in JavaScript. They are as follows:
Number
String
Undefined
Null
Boolean
bigint
Object
Array
Function
Javascript var,let,const
Phase II (Execution Phase): All the instruction get executed in top to bottom order in execution area of
global execution context
Window object
When a JS file is given to browser by default a global window object is created and the
reference is stored in window variable.
The global object consist of pre-defined members (functions and variables) which belong to browser
window.
Any member we declare var in JS file is added inside global window object by JS engine. So we can
use member with the help of window.
Any members(functions and variable) created in global scope will be added into the window object
implicitly by JS Engine
Hoisting: Utilizing the variable before declaration and initialization is called as Hoisting.
Hoisting can be achieved by var, because var is a global scope or global variable.
Hoisting cannot be achieved by let and const, because let and const are script scope.
Whenever we hoist var the result is undefined.
Whenever we try to hoist let and const the result is Uncaught ReferrenceError.
Temporal Dead Zone (TDZ): In the process of hoisting the time taken between Utilization of the
variable before declaration and initialization.
TDZ is achieved only in let and const.
Because, whenever we try to hoist let and const the result is Uncaught ReferrenceError.
TDZ cannot be achieved in var.
Because, whenever we hoist var the result is undefined.
JavaScript Functions:
A JavaScript function is a block of code designed to perform a particular task.
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
Example:
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
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.
Why Functions?
You can use the same code with different arguments, to produce different results.
1.Anonymous function
A function without name is known as Anonymous function
Syntax :
function(parameters) {
// function body
2.Named Function
4.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
Arrow function:
It was introduced in ES6 version of JS.
The main purpose of using arrow function is to reduce the syntax.
Example:
Let x= (a, b) =>console.log(a+b);
Let y=(a,b)=>{return a + b };
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:
String methods:-
String.length
String.slice()
String.substring()
String.substr()
String.replace()
String.replaceAll()
String.toUpperCase()
String. toLowerCase
String.concat()
String.trim()
String.trimStart()
trimEnd()
padStart()
padEnd()
String charAt()
String charCodeAt()
String split()
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).
• The .length property returns the length of an array.
Ex:-<script>
var emp=["Sonoo","Vimal","Ratan"]; for (i=0;i<emp.length;i++)
{ document.write(emp[i] + "<br/>");
}
</script>
JAVASCRIPT OBJECTS
JavaScript object is a non-primitive data-type that allows you to store
multiple collections of data.
const object_name = {
key1: value1,
key2: value2
}
Example:
// object creation
const person = {
name: 'John',
age: 20
};
console.log (typeof person); // object
objectname.key
Example:
const person = {
name: 'John',
age: 20,
};
// accessing property
console.log(person.name); // John
2. Using bracket Notation
objectName[“key”]
Example:
const person = {
name: 'John',
age: 20,
};
// accessing property
console.log(person["name"]); // John
// nested object
const student = {
name: 'John',
age: 20,
marks: {
science: 70,
math: 75
console.log(student.marks.science); // 70
Destructuring in js
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack
values from arrays, or properties from objects, into distinct variables.
let obj={
ename:"Raj",
company:"Google",
sal:60000,
games:{
outdoor:["cricket","volleyball","football"],
indoor:["ludo","chess"]
}
}
//Destructuring
let {ename,company,sal,games:{outdoor:[a,b,c],indoor:[x,y]}} = obj
console.log(ename);
console.log(a,x);
Reduce() : the reduce() is a HOF which will return a single value from the
original array. if no initial value is given, the accumulator will be assigned
with the first value of the array
SYNTAX:-
arr.reduce((acc,ele,index,arr)=>{
//statements
},init)
Example: -
let arr = [1, 2, 3, 4, 5];
let sum = arr.reduce(( accumulator,currentValue,index,arr) => {
console.log( accumulator, currentValue,index);
return accumulator+currentValue
},100);
console.log(sum);//115
Object: -
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 2 ways to create objects.
1.By object literal.
2.By creating instance of Object directly (using new keyword).
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>
In JavaScript, to access and manipulate object properties: dot notation
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); //
New York
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
Example:-
let obj4={
ename:"lavanya",
id:123,
sal:20000
};
let obj5={
ename1:"bujji", 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
Loops in js
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():-
Example:
const array1 = ['a', 'b', 'c’];
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“
“this” keyword
In JavaScript, the this keyword refers to an object.
Example:
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
this in a Method
When used in an object method, this refers to the object.
In the example on top of this page, this refers to the person object.
fullName : function() {
return this.firstName + " " + this.lastName;
}
this Alone
When used alone, this refers to the global object.
Example
let x = this;
this in a Function
In a function, the global object is the default binding for this.
Example
function myFunction() {
return this;
}
DOM
In JavaScript, the DOM (Document Object Model) is a programming
interface for web documents. It represents the structure of a
document as a tree-like model where each node is an object
representing a part of the document, such as elements, attributes,
and text.
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:
DOM Methods: -
Methods used to target HTML elements in JavaScript file
document.getElementById(id): This method allows you to retrieve
an element from the document by its unique id.
document.getElementsByClassName(className): This method
returns a collection of all elements in the document with a specified
class name.it will return HTMLCollection which is an impure array.
No array methods will work on HTMLCollection
document.getElementsByTagName(tagName): Returns a collection
of elements with the specified tag name.
document.querySelector(selector): Returns the first element that
matches a specified CSS selector.
document.querySelectorAll(selector): Returns a NodeList of all
elements that match a specified CSS selector.
NOTE: difference between HTMLCollection and NodeList
NodeList and HTMLCollection both are impure array, but the
difference is we can apply forEach() in NodeList but we cannot apply
any of the array methods on HTMLCollection.
To check whether the array is pure or not we have a method called
Array.isArray(), if array is pure it will return true else false.
To convert impure array to pure array we have a method called
Array.from()
DOM EVENTS
Event: An action performed by the user on the webpage is
known as an event
A JavaScript can be executed when an event occurs, like when
a user clicks on an HTML element.
onclick
onmouseover
onmouseout
ondblclick
onkeydown
onkeyup
addEventListener
Event Propagation
Event propagation refers to the way events travel through the
DOM tree. When an event occurs on an element, it can trigger
event handlers not only on that element but also on its parent
elements, all the way up to the root of the document. There
are two phases of event propagation:
1. Capturing Phase: The event travels from the root of the DOM
tree down to the target element.
2. Bubbling Phase: The event then bubbles up from the target
element back to the root.
event.stopPropagation(): This method prevents further
propagation of the current event. It stops the event from
bubbling up the DOM tree or from capturing down the tree
event.stopPropagation() in bubbling phase, it will block the
progation to reach to the outer most element from the
targetted element
event.stopPropagation() in capturing phase, it will block the
propagation to reach to the targetted element
event.stopImmediatePropagation() :- this method of the Event
interface prevents other listeners of the same event from being
called.
JAVASCRIPT OBJECT NOTATION (JSON)
It is format of storing and transporting data.
It is used when the data is sent form the server to web page
It is a popular data format for developers because of its human
readable text, light weight which requires less coding and faster
process
Example: [
{“fname”:”Ram”,”lname”:”Patil”},
{“fname”:”Raj”,”lname”:”smith”},
{“fname”:”Ashish”,”lname”:”gouda”}
]
SYNTAX:
Data is in Key value pairs
Data is separated by ‘,’
Curly braces holds objects
[ ]---holds array
In JavaScript, there are two main methods used to work with JSON
(JavaScript Object Notation):
1.JSON.Stringify() : used to convert normal object to JSON format
2.JSON.parse(): Used to convert JSON format of data to normal
object
TIME DELAYS
setTimeOut() and setInterval() are two functions in js allows to
schedule tasks to be executed at later time. Used for
animations, pulling data from server and other asynchronous
tasks.
setTimeOut() :
Runs the code with time delay
Syntax : setTimeOut( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function
is executed
setInterval() :
The function similar to setTimeOut, but it schedules a function
to be executed repeatedly at specified interval.
Syntax : window.setInterval( function , delay ) ;
• function: The function you want to execute.
• delay: The amount of time (in milliseconds) before the function
is executed
cancel a setTimeout, you use clearTimeout
Promises
In JavaScript, promises are a mechanism for handling
asynchronous operations. They provide a way to work with
asynchronous code in a more structured and readable manner.
Promises represent a value that may not be available yet but
will be resolved at some point in the future, either successfully
with a result or with an error.
A promise represents the eventual result of an asynchronous
operation. It can be in one of three states:
• Pending: Initial state, neither fulfilled nor rejected.
• Fulfilled: Meaning the operation completed successfully.
• Rejected: Meaning the operation failed.
SYNTAX TO CREATE A PROMISE:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation, e.g., fetching data from a server.
CONSUMING A PROMISE:
Then() : It will executed when the promise will be in resolved
state
Catch() : It will get executed when the promise is in rejected
state
Finally() : It will execute always means promise is in resolve ,
reject or in pending state
Fetch API
* fetch() is used to send a request to backend, it accepts a
URL/API as an argument. This url should be in String
* The fetch method returns a promise object, This object need
to be handled using then() and catch()
* We need to first handle the response object and parse it to
get normal object using json()
* In the next then method we will be able to consume the data
(using data from backed is called consuming data)
EXAMPLE:-
fetch("https://api.github.com/users")
.then((response) => response.json())
.then((data) => {
console.log(data[0].login);
})
.catch((error) => {
console.log(error);
});
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element