Js-Notes
Js-Notes
What is JavaScript?
Javascript is a high-level , object based ,programming language. Javascript is a interpreted, user friendly
,client-side scripting language.
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 is object
Uses of JavaScript:
JAVASCRIPT BY SARVESH
<body>
<h1>hello world</h1>
<script>
// javascript code……….
</script>
</body>
2. External Way
1. To write javascript externally to html file, we need to create an external javascript file with
extension as .js (ex: index.js)
2. After that link that javascript file to the html by using script tag.
Example:
<body>
<script src = “./index.js “></script>
</body>
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
JAVASCRIPT BY SARVESH
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. .
JAVASCRIPT BY SARVESH
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
ii. Phase I (Variable Phase): All the memory is allocated for the declaration in
top to bottom order and assignment with the default value undefined in
variable area of global execution context.
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).
JAVASCRIPT BY SARVESH
Example:
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
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.
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
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.
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 };
JAVASCRIPT BY SARVESH
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:
third(second);
STRING CONCEPT IN JAVASCRIPT
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/>");
JAVASCRIPT BY SARVESH
}
</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
}
JAVASCRIPT BY SARVESH
const person = {
name: 'John',
age: 20
};
objectname.key
Example:
const person = {
name: 'John',
age: 20,
};
// accessing property
console.log(person.name); // John
objectName[“key”]
JAVASCRIPT BY SARVESH
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
JAVASCRIPT BY SARVESH
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);
Syntax :
arr.filter((ele,index,arr)=>{
return condition
})
Example :
let numbers = [1, 2, 3, 4, 5];
let evenNo = numbers.filter((x) => x % 2 === 0);
console.log(evenNo); //[2, 4]
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.
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]
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
JAVASCRIPT BY SARVESH
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=
JAVASCRIPT BY SARVESH
{
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
JAVASCRIPT BY SARVESH
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
JAVASCRIPT BY SARVESH
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
JAVASCRIPT BY SARVESH
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“
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:
JAVASCRIPT BY SARVESH
DOM Methods: -
Methods used to target HTML elements in JavaScript file
getElementById(id): This method allows you to retrieve an element
from the document by its unique id.
getElementsByClassName(className): This method returns a
collection of all elements in the document with a specified class
name.
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.