0% found this document useful (0 votes)
3 views

unit 1

JavaScript is a lightweight, object-oriented programming language used for scripting web pages, with scripts embedded in HTML. Key features include variable declaration with let and const, ES6 updates introducing new functionalities, and the use of classes and functions for code organization. The document also covers array methods, destructuring, and the Map collection type, providing examples and syntax for each concept.

Uploaded by

level2464
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 views

unit 1

JavaScript is a lightweight, object-oriented programming language used for scripting web pages, with scripts embedded in HTML. Key features include variable declaration with let and const, ES6 updates introducing new functionalities, and the use of classes and functions for code organization. The document also covers array methods, destructuring, and the Map collection type, providing examples and syntax for each concept.

Uploaded by

level2464
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/ 59

JavaScript

JavaScript
• JavaScript (js) is a light-weight object-oriented
programming language which is used by several websites
for scripting the webpages
• The programs in this language are called scripts.
They can be written right in a web page’s HTML
and run automatically as the page loads.
JAVASCRIPT SYNTAX
JavaScript programs can be inserted almost anywhere into an HTML document
(HEAD & BODY)using the <script> tag.
A script in an external file can be inserted with <script
src="path/to/script.js"></script>.
EXAMPLE:
<!DOCTYPE HTML>
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
JavaScript Output
• JavaScript can "display" data in different ways:
– Writing into an HTML element, using innerHTML.
– Writing into the HTML output using document.write().
– Writing into an alert box, using alert().
– Writing into the browser console, using console.log().
Comment
• Single-line Comment:-
<script>
// It is single line comment
document.write("hello");
</script>
• Multi-line Comment:-
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
Variable
• A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}
</script>
• Variables are used to store information.
• A variable is a “named storage” for data. We can
use variables to store goodies, visitors, and other
data.
• To create a variable in JavaScript, use the let
keyword.
• The statement below creates (in other words:
declares) a variable with the name “message”:
let message;
Constants:
• To declare a constant (unchanging) variable, use const
instead of let:
const myBirthday = '18.04.1982';
• Variables declared using const are called “constants”.
They cannot be reassigned. An attempt to do so would
cause an error:
const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // error, can't
reassign the constant!
• When a programmer is sure that a variable will never
change, they can declare it with const to guarantee and
ES6
• ES6, or ECMAScript 2015, is a significant update to the
JavaScript language that brought several new features.
• Use of ES6 features we write less and do more
Features
• Variables
• Functions
• Arrow function
• Spread operator
• loop
• classes
• collection
• Modules
• Symbol
• Array
• Promises
Variable
• A variable is a named container in the memory, that stores
the values.
• The ES6 Variable names are called identifiers.
Implementation
import logo from './logo.svg';
import './App.css';
function App() {

var b=2;
var b=3;

return (
<>
<p>the value of a is {a}</p>
<p>the value of b is {b}</p>
</>
);
}
export default App;
Variable Scope
• Global Scope: A variable that can be accessed from
any part of the JavaScript code.
• Local Scope: A variable that can be accessed within a
function where it is declared.
import logo from './logo.svg';
import './App.css';
var c=30; global variable
function App() {

var b=2; local variable


var b=3;
return (
<>
<p>the value of a is {a}</p>
<p>the value of b is {b}</p>
<p>the value of c is {c}</p>
</>
);
}

export default App;


let keyword
• The let keyword in JavaScript is used to declare variables
that are block-scoped, meaning they are only accessible
within the block of code.
• Block Scope: Variables declared with let are limited to the
block, statement, or expression where they are used. This
is different from var, which is scoped to the entire function
or globally.
Example block scope
function exampleFunction() {
if (true) {
let blockScopedVar = 'I am inside a block';
console.log(blockScopedVar); // Output: 'I am inside a block'
}
console.log(blockScopedVar); // ReferenceError: blockScopedVar is not defined
}

exampleFunction();
Example of No hoisting
• No Hoisting: While let declarations are hoisted to the top
of their block, they are not initialized. Accessing a let
variable before its declaration results in a ReferenceError
(often referred to as the "temporal dead zone").
function temporalDeadZone() {
console.log(a); // ReferenceError: Cannot access 'a' before
initialization
let a = 3;
}
temporalDeadZone();
• No Duplicate Declarations: Within the same block scope,
you cannot declare the same variable name more than
once with let. This helps avoid issues with variable
shadowing.
let x = 1;
let x = 2; // SyntaxError: Identifier 'x' has already been
declared
Example of Reassignment
• Reassignment: Variables declared with let can be
reassigned new values, unlike const which prevents
reassignment.
let count = 10;
count = 20; // No problem; count is now 20
console.log(count); // Output: 20
const
The const keyword is used to declare constant variables whose values can’t be changed
import logo from './logo.svg';
import './App.css';
var c=30;
function App() {
let a=1;
const b=2;
var b=3;
return (
<>
<p>the value of a is {a}</p>
</>
);
}
export default App;
Classes
• Classes are used to define the blueprint for real-world
object modeling and organize the code into reusable and
logical parts.
• A class is a type of function
• Instead of using the keyword function to initiate it, we use
the keyword class
• A class definition can only include constructors and
functions
• The classes contain constructors that allocates the
memory to the objects of a class.
• Classes contain functions that are responsible for
performing the actions to the objects.
class Student {
constructor(name, age) {
this.n = name;
this.a = age;
}
stu() {
console.log("The Name of the student is: ", this.n)
console.log("The Age of the student is: ",this. a)
}
}

var stuObj = new Student('Peter',20);


stuObj.stu();
class Car {
constructor(name) {
this.brand = name;
}

present() {
return 'I have a ' + this.brand;
}
}

const mycar = new Car("Ford");


mycar.present();
Class Inheritance
class Car {
constructor(name) {
this.brand = name;
}

present() {
return 'I have a ' + this.brand;
}
}

class Model extends Car {


constructor(name, mod) {
super(name);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model
}
}
const mycar = new Model("Ford", "Mustang");
mycar.show();
Functions
• A function is a set of instruction that takes some inputs,
do some specific task and produce output
• A function is a set of codes that can be reused in the
program at any time.
function func-name() {
// body
}

func-name(); // Calling
Arrow function or lambda function
• Arrow functions are anonymous functions
• functions without a name and are not bound by an identifier.
• Arrow functions return any value in implicit function and can be declared
without the function keyword.
• In explicit we can return the value.
• Arrow functions do not have the prototype property like this, arguments, or
super.
• Arrow functions cannot be used with the new keyword.
• Arrow functions cannot be used as constructors.
Syntax

For Single Argument:


let function_name = argument1 => expression
For Multiple Arguments:
let function_name = (argument1, argument2 , ...) =>
expression
Example
function multiply(a, b) {
return a * b; // simple function
}
console.log(multiply(3, 5));
value = (a, b) => a * b;
console.log(value(3, 5));// arrow function
Array
• Array in JavaScript is an object which is used to represent
a collection of similar type of elements
• It allows you to store more than one value or a group of
values in a single variable name.
• We can store any valid values such as objects, numbers,
strings, functions, and also other arrays
Syntax

var array_name = new Array(); // By using the new keyword

var array_name = [value1, value2,....valueN]; //By using


Array literals
or,
var array_name; //Declaration
array_name=[value1, value2,…..valueN]; //Initialization
Initialize Array
var JS = ["ES1", "ES2", "ES3", "ES4", "ES5", "ES6"];

// Initializing after declaring


JS[0] = "ES6";
JS[1] = "ES6";
JS[2] = "ES6";
JS[3] = "ES6";
console.log(JS[4])
console.log(JS[5])
Example - Single Numeric Value

var num = new Array(5); // This single numeric value


indicates the size of array.
var i;
for(i=0;i<num.length;i++){
num[i]=i*5;
console.log(num[i]);
}
Array method in ES6
• concat()
• every()
• forEach()
• filter()
• Array.from()
• Array.of()
• Array.prototype.copyWithin()
• Array.prototype.find()
• Array.prototype.entries()
• Array.prototype.keys()
concat()
• This method is used to merge two or more arrays
together.

var arr1=["A","B","C"];
var arr2=["D","E","F"];
var result=arr2.concat(arr1);
document.writeln(result);
Array.from()

The from() method creates a new array that holds the


shallow copy from an array or iterable object. When applied
to a string, each word gets converted to an array element in
the new array.
SYNTAX: Array.from(object,map_fun,thisArg);

let name = Array.from('class')

console.log(name)
var arr=Array.from("You are viewing an example of
string"); //The string will get converted to an array.
document.write("The resultant is: <br>" +arr);
Array.of()
• In ES5, when a single numeric value gets passed in the
array constructor, then it will create an array of that size.
Array.of() is a new way of creating an array which fixes
this behavior of ES5.

• By using this method, if you are creating an array only


with a single numeric value, then it will create an array
only with that value instead of creating the array of that
size.
let name = Array.of("a","b","c","d")
console.log(name)
console.log(name.length)
Array.copyWithin()
• It is an interesting method that is added to the library of
array methods in ES6. This method copies the part of an
array to a different location within the same array.
array.copyWithin(target, start, end)
target is required start and end is optional.
• It returns the modified array without any modification in its
length.
const num = [1,2,3,4,5,6,7,8,9,10];
console.log(num.copyWithin(1,3,5));
console.log(num1.copyWithin(1,3)); //omitting the parameter
end
Array.prototype.entries()
• This method returns an array iterator object, which can be
used to loop through keys and values of arrays.
var colours = ["Red", "Yellow", "Blue", "Black"];
var show = colours.entries();

for (i of show) {
console.log(i);
}
Array Destructuring
• Array destructuring is a concise syntax in JavaScript that
allows you to unpack values from arrays (or properties
from objects) into distinct variables.
in ES5

let myfavlang=['HTML','JS','JAVA','C','PYTHON']
let var1=myfavlang[0];
let var2=myfavlang[0];
let var3=myfavlang[0];
let var4=myfavlang[0];
let var5=myfavlang[0];
document.write(var1);
In ES6

let myfavlang=['HTML ','JS ','JAVA ','C ','PYTHON ']


let [var1,var2,var3] =myfavlang;
document.write(var1);
document.write(var2);
document.write(var3);
//if I want to access 5th element
let[,,,,var5]=myfavlang;
ES6 Map
• ES6 provides us a new collection type called Map, which
holds the key-value pairs in which values of any type can
be used as either keys or values
• Maps are ordered, so they traverse the elements in their
insertion order.
• syntax var map = new Map([iterable]);
Map properties
• Map.prototype.size:-This property returns the
number of key-value pairs in the Map object.
• Map.prototype.clear():-It removes all the keys and
values pairs from the Map object.
• Map.prototype.delete(key):-It is used to delete an
entry.
• Map.prototype.has(value):-It checks whether or
not the corresponding key is in the Map object.
• Map.prototype.keys():-It returns an iterator for all
keys in the Map.
• Map.prototype.values():-It returns an iterator for
every value in the Map.
const m=map.values();
for (const value of m) {
document.write("<br>");
document.write(value);
}
Example
<script>
var map = new Map();
map.set('John', 'author');
map.set('arry', 'publisher');
map.set('Mary', 'subscriber');
map.set('James', 'Distributor');
document.write(map.size);
const a=map.keys();
for (const key of a) {
document.write("<br>");
document.write(key);

}
document.write("<br>");
document.write(map.has('publisher'));
const w=map.delete('john');
const b=map.keys();
for (const key of b) {
document.write("<br>");
document.write(key);
}
Array map method
• It creates a new array populated with the results of calling a provided
function on every element in the calling array.

array.map(callback(currentValue[, index[, array]])[, thisArg])


callback: A function that is executed for each element in the array. It takes up
to three arguments:

currentValue: The current element being processed in the array.


index (optional): The index of the current element being processed in the
array.
array (optional): The array map was called upon.
thisArg (optional): A value to use as this when executing the callback
function.
const oldarr=['ashish ','vikash ','mohit '];
document.write(oldarr[0]);
document.write(oldarr[1]);
document.write(oldarr[2]);

const newarr=oldarr.map(function(cval)
{
return cval;
});
document.write(newarr);
const student =[ {id:1, name:'ashish', degree:'Btech'},
{ id:2, name:'mohit', degree:'Mtech'}
]

document.write(student[1].name);
const st=student.map((cval)=>{
return `My name is ${cval.name}`;
})
document.write(st);
how to write in html

const student =[ {id:1, name:'ashish', degree:'Btech'},


{ id:2, name:'mohit', degree:'Mtech'}
]

document.write(student[1].name);
const st=student.map((cval)=>{
return `My name is ${cval.name}`;
})
document.getElementById('a').innerHTML=st;
Rest parameter
• In ES6 (ECMAScript 2015), the rest parameter syntax
allows you to represent an indefinite number of arguments
as an array. This is particularly useful when you don't
know beforehand how many arguments will be passed to
a function.
• The syntax for the rest parameter is three dots (...)
followed by a name.
// ES5
function sum(a,b){
document.write(a+b);
}
sum(1,2,3,4,5,6);
// ES6
// this c return array
function sum(...c) {
console.log(c);
let total=0;
for(let i of c)
{
total +=i;
}
document.write(total);
}
sum(1,2,3,4,5,6,7);
What is the output from this program
function fun(a,b,...c)
{
document.write(`${a} ${b}`);
document.write('<br>');
document.write(c);
document.write('<br>');
document.write(c[0]);
document.write('<br>');
document.write(c.length);
document.write('<br>');
document.write(c.indexOf('ashish'));
}
Spread Operator

The spread operator in ES6 (ECMAScript 2015) is a


powerful and versatile feature that allows you to expand or
spread elements of an iterable (like an array) into individual
elements.
function sum(a,b)
{
document.write(a+b);
}
// sum(4,5);
let arr=[2,3];
// sum.apply(null,arr);
// replace apply
sum(...arr);

// replace concat
let arr1=[5,6]
arr=[...arr,...arr1];
document.write(arr);
Part B

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy