unit 1
unit 1
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() {
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)
}
}
present() {
return 'I have a ' + this.brand;
}
}
present() {
return 'I have a ' + this.brand;
}
}
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
var arr1=["A","B","C"];
var arr2=["D","E","F"];
var result=arr2.concat(arr1);
document.writeln(result);
Array.from()
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.
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
}
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.
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
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
// replace concat
let arr1=[5,6]
arr=[...arr,...arr1];
document.write(arr);
Part B