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

JavaScript Day5

The document provides an overview of JavaScript variable scope, including local and global variables, and the implications of using strict mode. It explains the 'this' keyword, variable declaration using let and const, and the concept of hoisting. Additionally, it covers JavaScript classes, debugging techniques, and best practices for object creation.

Uploaded by

pranav
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

JavaScript Day5

The document provides an overview of JavaScript variable scope, including local and global variables, and the implications of using strict mode. It explains the 'this' keyword, variable declaration using let and const, and the concept of hoisting. Additionally, it covers JavaScript classes, debugging techniques, and best practices for object creation.

Uploaded by

pranav
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/ 51

Java script

Day 5
Scope of variable

JavaScript has function scope:


Each function creates a new scope.
Scope determines the accessibility (visibility) of these
variables.
Variables defined inside a function are not accessible
(visible) from outside the function.
In JavaScript there are two types of scope:
 Local scope
 Global scope
Local variable
<!DOCTYPE html>
document.getElementById("demo1"
<html>
).innerHTML = typeof carName + " "
<body> + carName;
<h2>JavaScript Scope</h2> }
<p>Outside myFunction() carName document.getElementById("demo2"
is undefined.</p> ).innerHTML = typeof carName;
<p id="demo1"></p> </script>
<p id="demo2"></p> </body>
<script> </html>
myFunction();
function myFunction() {
var carName = "Volvo";
Global variable
<!DOCTYPE html> document.getElementById("demo").i
nnerHTML = "I can display " +
<html>
carName;
<body>
}
<h2>JavaScript Scope</h2>
</script>
<p>A GLOBAL variable can be
</body>
accessed from any script or
function.</p> </html>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction() {
Strict Mode
 All modern browsers support running JavaScript in "Strict Mode".
 You will learn more about how to use strict mode in a later chapter of
this tutorial.
 In "Strict Mode", undeclared variables are not automatically global.

Warning
 Do NOT create global variables unless you intend to.
 Your global variables (or functions) can overwrite window variables (or
functions).
 Any function, including the window object, can overwrite your global
variables and functions.

The Lifetime of JavaScript Variables


 The lifetime of a JavaScript variable starts when it is declared.
 Local variables are deleted when the function is completed.
 In a web browser, global variables are deleted when you close the
browser window (or tab).
The JavaScript this Keyword
<!DOCTYPE html> lastName : "Doe",
<html> id : 5566,
<body> fullName : function() {
<h2>The JavaScript <i>this</i> return this.firstName + " " +
Keyword</h2> this.lastName;
<p>In this example, <b>this</b> }
represents the <b>person</b>
};
object.</p>
// Display data from the object:
<p>Because the person object
"owns" the fullName method.</p> document.getElementById("demo").in
nerHTML = person.fullName();
<p id="demo"></p>
</script>
<script>
</body>
// Create an object:
</html>
var person = {
firstName: "John",
What is this?
It has different values depending on where it is used:

In a method, this refers to the owner object.


In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
Inan event, this refers to the element that received the
event.
Methods like call(), and apply() can refer this to any object.
Example

<!DOCTYPE html>
<html> <script>
<body> var x = this;
document.getElementById("demo").i
nnerHTML = x;
<h2>The JavaScript <i>this</i>
Keyword</h2> </script>

<p>In this example, <b>this</b> </body>


refers to the window Object:</p>
</html>

<p id="demo"></p>
Example

<!DOCTYPE html>
<html> <script>
<body> "use strict";
var x = this;
<h2>The JavaScript <i>this</i> document.getElementById("demo").i
Keyword</h2> nnerHTML = x;
</script>
<p>In this example, <b>this</b>
refers to the window Object:</p>
</body>
</html>
<p id="demo"></p>
Example

<!DOCTYPE html> }
<html> document.getElementById("demo").
innerHTML = i;
<body>
</script>
<h2>JavaScript let</h2>
</body>
<p id="demo"></p>
</html>
<script>
let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
Rules for let

let x = 2; // Allowed
let x = 3; // Not allowed

Inside function
{
let x = 4; // Allowed
let x = 5; // Not allowed
}
Example

<!DOCTYPE html> let x = 3; // Allowed


<html> }
<body> {
<h2>JavaScript let</h2> let x = 4; // Allowed
<p>Redeclaring a variable with }
<b>let</b>, in another scope, or in
document.getElementById("demo").i
another block, is allowed:</p>
nnerHTML = x;
<p id="demo"></p>
</script>
<script>
</body>
let x = 2; // Allowed
</html>
{
Example

<!DOCTYPE html> innerHTML = carName;


<html> var carName;
<body> </script>
<h2>JavaScript Hoisting</h2> </body>
<p>With <b>var</b>, you can use </html>
a variable before it is declared:</p>
<p id="demo"></p>
<script>
carName = "Volvo";
document.getElementById("demo").
Const
Example
<!DOCTYPE html> PI = 3.14;
<html> }
<body> catch (err) {
<h2>JavaScript const</h2>
document.getElementById("demo").
<p>You cannot change a primitive
innerHTML = err;
value.</p>
}
<p id="demo"></p>
</script>
<script>
</body>
try {
</html>
const PI = 3.141592653589793;
Example

<!DOCTYPE html> const x = 2;


<html> // Here x is 2
<body> }
// Here x is 10
<h2>Declaring a Variable Using const</h2>document.getElementById("demo").innerHT
ML = x;
</script>
<p id="demo"></p>

</body>
<script>
</html>
var x = 10;
// Here x is 10
{
Example

<!DOCTYPE html> }
<html> catch (err) {
<body>
document.getElementById("demo").i
<h2>JavaScript const</h2>
nnerHTML = err;
<p>You cannot change a primitive
}
value.</p>
</script>
<p id="demo"></p>
</body>
<script>
</html>
try {
const PI = 3.141592653589793;
PI = 3.14;
Example
<!DOCTYPE html> // Add a property:
<html> car.owner = "Johnson";
<body> // Display the property:
<h2>JavaScript const</h2> document.getElementById("demo").i
nnerHTML = "Car owner is " +
<p>Declaring a constant object
car.owner;
does NOT make the objects
properties unchangeable:</p> </script>
<p id="demo"></p> </body>
<script> </html>
// Create an object:
const car = {type:"Fiat",
model:"500", color:"white"};
// Change a property:
car.color = "red";
Example
<!DOCTYPE html> catch (err) {
<html>
document.getElementById("demo").i
<body>
nnerHTML = err;
<h2>JavaScript const</h2>
}
<p>But you can NOT reassign a
</script>
constant object:</p>
</body>
<p id="demo"></p>
</html>
<script>
try {
const car = {type:"Fiat",
model:"500", color:"white"};
car = {type:"Volvo", model:"EX60",
color:"red"};
}
Example
<!DOCTYPE html> // Add an element:
<html> cars.push("Audi");
<body> // Display the Array:
<h2>JavaScript const</h2> document.getElementById("demo").in
nerHTML = cars;
<p>Declaring a constant array does
NOT make the elements </script>
unchangeble:</p>
</body>
<p id="demo"></p>
</html>
<script>
// Create an Array:
const cars = ["Saab", "Volvo",
"BMW"];
// Change an element:
cars[0] = "Toyota";
Example
<!DOCTYPE html> const cars = ["Saab", "Volvo",
"BMW"];
<html>
cars = ["Toyota", "Volvo", "Audi"];
<body>
}
catch (err) {
<h2>JavaScript const</h2>

document.getElementById("demo").
<p>You can NOT reassign a innerHTML = err;
constant array:</p>
}
</script>
<p id="demo"></p>

</body>
<script>
</html>
try {
Example
const x = 2; // Allowed allowed
const x = 3; // Not x = 3; // Not
allowed allowed
x = 3; // Not var x = 3; // Not
allowed allowed
var x = 3; // Not let x = 3; // Not
allowed allowed
let x = 3; // Not }
allowed

Inside function
{
const x = 2; // Allowed
const x = 3; // Not
Without arrow function

<!DOCTYPE html> var hello;


<html>
<body> hello = function() {
return "Hello World!";
<h2>JavaScript Function</h2> }

<p>This example shows the syntax of a document.getElementById("demo").innerHT


function, without the use of arrow function ML = hello();
syntax.</p>
</script>

<p id="demo"></p>
</body>
</html>
<script>
With arrow function
<!DOCTYPE html> var hello;
<html>
<body> hello = () => {
return "Hello World!";
<h2>JavaScript Arrow Function</h2> }

<p>This example shows the syntax of document.getElementById("demo").inn


an Arrow Function, and how to use erHTML = hello();
it.</p>
</script>

<p id="demo"></p>
</body>
</html>
<script>
JavaScript Classes

Class is a collection of data members and member function

Data members-variables
Member function- methods,functions

class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
}
Example

<!DOCTYPE html> this.name = name;


<html> this.year = year;
<body> }
}
<h2>JavaScript Class</h2>
myCar = new Car("Ford", 2014);
<p>How to use a JavaScript Class.</p> document.getElementById("demo").innerHTML
=
myCar.name + " " + myCar.year;
<p id="demo"></p>
</script>

<script>
</body>
class Car {
</html>
constructor(name, year) {
The Constructor Method

 The constructor method is a special method:


 It has to have the exact name "constructor"
 It is executed automatically when a new object is created
 It is used to initialize object properties
Example
<!DOCTYPE html> age() {
<html> let date = new Date();
<body> return date.getFullYear() - this.year;
<h2>JavaScript Class Method</h2> }
<p>How to define and use a Class }
method.</p>
let myCar = new Car("Ford", 2014);
<p id="demo"></p>
document.getElementById("demo").i
<script> nnerHTML =
class Car { "My car is " + myCar.age() + " years
old.";
constructor(name, year) {
</script>
this.name = name;
</body>
this.year = year;
</html>
}
JavaScript Debugging
The console.log()
Method <script>

<!DOCTYPE html> a = 5;

<html> b = 6;

<body> c = a + b;
console.log(c);

<h2>My First Web Page</h2> </script>

<p>Activate debugging in your </body>


browser (Chrome, IE, Firefox) with </html>
F12, and select "Console" in the
debugger menu.</p>
Debugger

<!DOCTYPE html> before it executes the third line.</p>


<html>
<head> <script>
</head> var x = 15 * 5;
debugger;
<body> document.getElementById("demo").inn
erHTML = x;
</script>
<p id="demo"></p>

</body>
<p>With the debugger turned on, the
code below should stop executing </html>
Major Browsers' Debugging Tools
Normally, you activate debugging in your From the menu, select "Developer Tools".
browser with F12, and select "Console" in Finally, select "Console".
the debugger menu.
Opera
Otherwise follow these steps:
Open the browser.
Chrome
From the menu, select "Developer".
Open the browser.
From "Developer", select "Developer tools".
From the menu, select "More tools".
Finally, select "Console".
From tools, choose "Developer tools".
Safari
Finally, select Console.
afari, Preferences, Advanced in the main
FirefoxGo to S
menu.
Open the browser. Check "Enable Show Develop menu in menu
From the menu, select "Web Developer". bar".
Finally, select "Web Console". When the new option "Develop" appears in
Edge the menu:

Open the browser. Choose "Show Error Console".


Don't Use new Object()

•Use {} instead of new Object()


•Use "" instead of new String()
•Use 0 instead of new Number()
•Use false instead of new Boolean()
•Use [] instead of new Array()
•Use /()/ instead of new RegExp()
•Use function (){} instead of new
Function()
Example
<!DOCTYPE html> "x1: " + typeof x1 + "<br>" +
<html> "x2: " + typeof x2 + "<br>" +
<body> "x3: " + typeof x3 + "<br>" +
<p id="demo"></p> "x4: " + typeof x4 + "<br>" +
<script> "x5: " + typeof x5 + "<br>" +
var x1 = {}; "x6: " + typeof x6 + "<br>" +
var x2 = ""; "x7: " + typeof x7 + "<br>";
var x3 = 0; </script>
var x4 = false; </body>
var x5 = []; </html>
var x6 = /()/;
var x7 = function(){};
document.getElementById("demo").innerHTM
L=
Auto type conversion

<!DOCTYPE html> document.getElementById("demo").


innerHTML = typeof x;
<html>
</script>
<body>

</body>
<p id="demo"></p>
</html>

<script>
var x = "Hello";
var x = 5;
Example
<!DOCTYPE html> </body>
<html> </html>
<body> //NaN
<p id="demo">My first
paragraph.</p>
<script>
document.getElementById(
"demo").innerHTML =
"Hello" - "Dolly";
</script>
Comparison
<!DOCTYPE html> //x = (1 == "1"); // true
<html> //x = (1 == true); // true
<body> //x = (0 === ""); // false
<p>Remove the comment //x = (1 === "1"); // false
(at the beginning of each //x = (1 === true); // false
line) to test each
case:</p> document.getElementById(
"demo").innerHTML = x;
<p id="demo"></p>
</script>
<script>
</body>
var x;
</html>
//x = (0 == ""); // true
Examples
<!DOCTYPE html> }
<html> document.getElementById("dem
o").innerHTML = myFunction(4);
<body>
<p>Setting a default value to a </script>
function parameter.</p> </body>
<p id="demo"></p> </html>
<script>
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
return x * y;
Example switch
<!DOCTYPE html> break;
<html><body><p id="demo"></p> case 4:
<script> day = "Thursday";
var day; break;
switch (new Date().getDay()) { case 5:
case 0: day = "Friday";
day = "Sunday"; break;
break; case 6:
case 1: day = "Saturday";
day = "Monday"; break;
break; default:
case 2: day = "unknown";
day = "Tuesday"; }
break; document.getElementById("demo").innerHTML
= "Today is " + day;
case 3:
</script></body></html>
day = "Wednesday";
Keywords in javascript
abstract arguments await* boolean
break byte case catch
char class* const continue
debugger default delete do
double else enum* eval
export* extends* false final
finally float for function
goto if implements import*
in instanceof int interface
let* long native new
null package private protected
public return short static
super* switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield
Example

<!DOCTYPE html> method is not supported in Internet Explorer


8 and earlier versions.</p>
<html>
<body>
<script>
function myFunction() {
<h2>JavaScript String.trim()</h2>
var str = " Hello World! ";
alert(str.trim());
<p>Click the button to alert the string with
removed whitespace.</p> }
</script>
<button onclick="myFunction()">Try
it</button>
</body>
</html>
<p><strong>Note:</strong> The trim()
Example

<!DOCTYPE html>
<html> <script>
<body> function myFunction() {
var fruits = ["Banana", "Orange", "Apple",
"Mango"];
<h2>JavaScript Array.isArray()</h2>
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
<p>Click the button to check if "fruits" is an
array.</p> }
</script>
<button onclick="myFunction()">Try
it</button>
</body>
</html>
<p id="demo"></p>
Example

<!DOCTYPE html> var numbers = [45, 4, 9, 16, 25];


<html> numbers.forEach(myFunction);
<body> document.getElementById("demo").innerHTM
L = txt;

<h2>JavaScript Array.forEach()</h2>
function myFunction(value) {
txt = txt + value + "<br>";
<p>Calls a function once for each array
element.</p> }
</script>
<p id="demo"></p>
</body>
<script> </html>
var txt = "";
Example

<!DOCTYPE html> var numbers2 = numbers1.map(myFunction);


<html>
<body> document.getElementById("demo").innerHTM
L = numbers2;

<h2>JavaScript Array.map()</h2>
function myFunction(value, index, array) {
return value * 2;
<p>Creates a new array by performing a
function on each array element.</p> }
</script>
<p id="demo"></p>
</body>
<script> </html>
var numbers1 = [45, 4, 9, 16, 25];
Example

<!DOCTYPE html> var over18 = numbers.filter(myFunction);


<html>
<body> document.getElementById("demo").innerHTM
L = over18;

<h2>JavaScript Array.filter()</h2>
function myFunction(value, index, array) {
return value > 18;
<p>Creates a new array with all array
elements that passes a test.</p> }
</script>
<p id="demo"></p>
</body>
<script> </html>
var numbers = [45, 4, 9, 16, 25];
Example

<!DOCTYPE html> var sum = numbers.reduce(myFunction);


<html>
<body> document.getElementById("demo").innerHTM
L = "The sum is " + sum;

<h2>JavaScript Array.reduce()</h2>
function myFunction(total, value, index, array)
{
<p>This example finds the sum of all
return total + value;
numbers in an array:</p>
}
</script>
<p id="demo"></p>

</body>
<script>
</html>
var numbers = [45, 4, 9, 16, 25];
Example

<!DOCTYPE html> var sum = numbers.reduceRight(myFunction);


<html>
<body> document.getElementById("demo").innerHTM
L = "The sum is " + sum;

<h2>JavaScript Array.reduceRight()</h2>
function myFunction(total, value) {
return total + value;
<p>This example finds the sum of all
numbers in an array:</p> }
</script>
<p id="demo"></p>
</body>
<script> </html>
var numbers = [45, 4, 9, 16, 25];
Example

<!DOCTYPE html> var a = fruits.indexOf("Apple");


<html> document.getElementById("demo").inner
HTML = "Apple is found in position " + a;
<body>
</script>

<h2>JavaScript Array.indexOf()</h2>
<p>The indexOf() does not work in
Internet Explorer 8 and earlier
versions.</p>
<p id="demo"></p>
</body>
<script> </html>
var fruits = ["Apple", "Orange", "Apple",
"Mango"];
Example

<!DOCTYPE html> var a = fruits.lastIndexOf("Apple");


<html> document.getElementById("demo").innerH
TML = "Apple is found in position " + (a +
<body>
1);
</script>
<h2>JavaScript Array.lastIndexOf()</h2>

<p>The lastIndexOf() does not work in


Internet Explorer 8 and earlier
<p id="demo"></p> versions.</p>

<script> </body>

var fruits = ["Apple", "Orange", "Apple", </html>


"Mango"];
Example
<!DOCTYPE html> var person = {
<html> firstName: "John",
<body> lastName : "Doe",
get fullName() {
<h2>JavaScript Getters and Setters</h2> return this.firstName + " " +
this.lastName;
}
<p>Getters and setters allow you to get
and set properties via methods.</p> };
// Display data from the object using a
getter:
<p>This example creates a getter for a
property called fullName.</p> document.getElementById("demo").innerH
TML = person.fullName;
</script>
<p id="demo"></p>

</body>
<script>
</html>
// Create an object:
Example
<html><head> "language", {
<meta content="text/html; value: "EN",
charset=iso-8859-2" http-
writable : true,
equiv="Content-Type">
enumerable : true,
</head><body>
configurable : true
<h2>JavaScript defineProperty()</h2>
});
<p id="demo"></p>
// Enumerate Properties
<script>
txt = "";
// Create an Object:
for (var x in person) {
var person = {
txt += person[x] + "<br>";
firstName: "John",
}
lastName : "Doe",
document.getElementById("demo").inn
language : "NO",
erHTML = txt;
};// Change a Property:
</script></body></html>
Object.defineProperty(person,
Example

<!DOCTYPE html> document.getElementById("demo").innerHT


ML = "First number over 18 has index " +
<html>
first;
<body>

function myFunction(value, index, array) {


<h2>JavaScript Array.findIndex()</h2>
return value > 18;
}
<p id="demo"></p>
</script>

<script>
</body>
var numbers = [4, 9, 16, 25, 29];
</html>
var first = numbers.findIndex(myFunction);

You might also like