0% found this document useful (0 votes)
43 views33 pages

Angular

This document provides an outline of topics covered in Angular Training Session -4 including variable scopes, objects & prototypes, modules, classes, promises & async/await, and the JavaScript DOM. It then discusses specific topics in more detail such as variable scope, global vs local scope, block scope introduced in ES6, and hoisting. It also covers functions, anonymous functions, default parameters, function type, and closures.

Uploaded by

shubhamsen.hzs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views33 pages

Angular

This document provides an outline of topics covered in Angular Training Session -4 including variable scopes, objects & prototypes, modules, classes, promises & async/await, and the JavaScript DOM. It then discusses specific topics in more detail such as variable scope, global vs local scope, block scope introduced in ES6, and hoisting. It also covers functions, anonymous functions, default parameters, function type, and closures.

Uploaded by

shubhamsen.hzs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Angular Training

Session -4
Outlines
let , var ,const Objects & Prototypes Modules

Variable Scopes Classes Error handling

Hoisting Promises & Async/Await JavaScript DOM

Functions Iterators & Generators JavaScript Runtime


Variable scope
Scope determines the visibility and accessibility of a variable.

•The global scope


•Local scope
•Block scope (started from ES6)
Global scope
When the JavaScript engine executes a script, it creates a global execution
context.

It also assigns variables that you declare outside of functions to the global execution
context. These variables are in the global scope. They are also known as global
variables

Local scope
The variables that you declare inside a function are local to the function.
They are called local variables.
When the JavaScript engine executes the say() function, it creates a function
execution context.
Block scope

ES6 provides the let and const keywords that allow you to declare variables
in block scope.

Generally, whenever you see curly brackets {}, it is a block. It can be the area
within the if, else, switch conditions or for, do while, and while loops.

Global variable leaks: the weird part of JavaScript

function getCounter() {
counter = 10;
return counter;
}
console.log(getCounter());
Earlier before 2015, the only keyword available to declare variables was the var keyword.

ES6 -> let ,const

Scope of var, let and const

var : Function in which the variable is declared


let: Block in which the variable is declared
const: Block in which the variable is declared

let is similar to var. It allows us to declare variables in our local scope.


The differences are that let is:
 not hoisted
 block-scoped
Rules of Thumb:

 Don’t use var, because let and const is more specific

 Default to const, because it cannot be re-assigned or re-declared

 Use let when you want to re-assign the variable in future

 Always prefer using let over var and const over let
Unchanging Values With const

Example 1
const taxRate = 0.1;
const total = 100 + (100 * taxRate);
// Skip 100 lines of code
console.log(`Your Order is ${total}`); total}`);

var taxRate = 0.1;


var total = 100 + (100 * taxRate);
// Skip 100 lines of code
console.log(`Your Order is ${total}`);
Example 2
const taxRate = 0.1;
const shipping = 5.00;
let total = 100 + (100 * taxRate) + shipping;
// Skip 100 lines of code
console.log(`Your Order is ${total}`);
Changing the value of a const variable
const discountable = [];
const cart = [
{
item: 'Book',
discountAvailable: false,
},
{
item: 'Magazine',
discountAvailable: true,
},
];
// Skip some lines
for (let i = 0; i < cart.length; i++) {
if (cart[i].discountAvailable) {
discountable.push(cart[i]);
}
}
console.log(discountable););
d
What is Javascript hoisting?
Hoisting is Javascript’s default behavior of moving all declarations to the top
of their functional scope.

Hoisting variables

JS hoists the declaration of a variable up and allows it to be used. This


way, a variable can be declared after it has been used.
Hoisting functions

func();

function func() {
var a = 1;
var b = 2;
var c = 3;
console.log(a + " " + b + " " + c);
}
Functions

Anonymous Functions

Default Parameters

Function type
Functions
Call() , Apply() , Bind()

Arrow functions

Rest parameter

Closure
Function in JS

1. Declare a function 10. Returning functions from functions

2. Calling a function
3. Parameters vs. Arguments
4. Returning a value
5. The arguments object

7. Function hoisting

8. Storing functions in variables


9. Passing a function to another function
Anonymous Functions
- An anonymous function is a function without a name

- Note : If you don’t place the anonymous function inside the ()

- An anonymous function is not accessible after its initial creation.


Therefore, you often need to assign it to a variable.

- Using anonymous functions as arguments

setTimeout (function() {
console.log('Execute later after 1 second')
}, 1000);
let taxiing = car.start.bind(aircraft);
taxiing();

car.start.call(aircraft);

The bind() method creates a new function that you can execute later while the
call() method executes the function immediately.

The bind(), call(), and apply() methods are also known as borrowing functions.
Default Parameters
Arrow Function in JS
An arrow function is a feature introduced in ECMAScript 6 (ES6) for writing shorter
and more concise function expressions in JavaScript.

Arrow functions provide a more streamlined syntax compared to traditional


function expressions and also have some differences in how they handle the this
keyword.

const functionName = (parameters) => { //


function body
return result;

};
Characteristics Arrow Function
Shorter Syntax:
Arrow functions are often shorter and more concise compared to traditional function
expressions, especially for simple functions.

Implicit Return:
If the function body consists of a single expression, you can omit the curly braces {} and
the return keyword. The result of the expression will be automatically returned.

No Binding of this:
Arrow functions do not have their own this value. Instead, they inherit the this value
from the enclosing context. This makes them useful when you want to maintain the
context of the surrounding code.
arrow functions are useful for certain scenarios, they might not be suitable for
all cases.

For example,

 arrow functions cannot be used as constructor functions (i.e., they cannot be


used with the new keyword)

 do not have their own arguments object.


this Keyword
The this keyword is a special identifier that refers to the current execution context,
specifically the object that "owns" the currently executing code.

The behavior of the this keyword depends on how and where it is used within a
function or method.
The behavior of this :

1. Global Context:
In the global context (outside of any function or object), this refers to the global
object, which is often the window object in browsers or the global context in
Node.js.
2. Function Context:
In a regular function (not an arrow function), the value of this depends on how
the function is called. If the function is called as a method of an object, this refers
to the object itself. If the function is called standalone, this might refer to the
global object (in non-strict mode) or be undefined (in strict mode).
The behavior of this :

3. Arrow Function Context :


In an arrow function, this retains the value of this from the enclosing lexical context
(the context where the arrow function is defined). It does not have its own binding
for this.
4. Method Context:

When a function is a method of an object, this refers to the object itself.

5. Explicitly Setting this:

You can explicitly set the value of this using functions like bind, call, and apply.

NOTE :
this can sometimes be complex, especially in nested functions or callback scenarios.
JavaScript Function Type
- In JavaScript, all functions are objects.
- They are the instances of the Function type Because functions are objects,
they have properties and methods like other objects.

length
(Determines the number of named arguments
Functions properties specified in the function declaration.)

prototype
property references the actual function object.
Function methods: apply, call, and bind

A function object has three important methods: apply(), call() and bind().

The apply() and call() methods call a function with a given this value and arguments.

The difference between the apply() and call() is that you need to pass the arguments
to the apply() method as an array-like object, whereas you pass the arguments to
the call() function individually.
Function methods: apply, call,bindbind

let cat = { type: 'Cat', sound: 'Meow' };


let dog = { type: 'Dog', sound: 'Woof' };

const say = function (message) {


console.log(message);
console.log( this.type + ' says ' + this.sound);
};

say.apply(cat, ['What does a cat say?']);


say.apply(dog, ['What does a dog say?']);

say.call(cat, 'What does a cat say?');


say.call(dog, 'What does a dog say?');
Bind() Method
In JavaScript, the bind() method is used to create a new function that has a
specific this value, and optionally, arguments that are "bound" to it.

This is particularly useful when you want to explicitly set the value of this
within a function, regardless of how the function is called.

The bind() method does not invoke the function immediately but returns a
new function with the specified context and arguments.

functionToBind.bind( thisValue[, arg1[, arg2[, ...]]])


apply() Method

In JavaScript, the apply() method is a function method that allows you to invoke
a function with a specific this value and an array (or an array-like object) of
arguments.

It is similar to the call() method, but instead of passing individual arguments


directly, you pass them as an array or array-like object.

The apply() method can be useful when you have a function that accepts a
variable number of arguments and those arguments are stored in an array. It's
also often used to invoke functions with a specific this context and arguments
extracted from an array or array-like object.
JavaScript Closures
A closure is a function that references variables in the outer scope from its inner
scope.

The closure preserves the outer scope inside its inner scope.

Lexical scoping
Lexical scoping

let name = 'John';

function greeting() {
let message = 'Hi';
console.log(message + ' '+ name);
}

According to lexical scoping, the scopes can be nested and the inner function
can access the variables declared in its outer scope.
Lexical scoping

function greeting() {
let message = 'Hi';
function sayHi() {
console.log(message);
}
sayHi();
}
greeting();
JavaScript closures

function greeting() {

let message = 'Hi';

function sayHi()
{
console.log(message);
}
return sayHi;
}
let hi = greeting();
hi();
Thank You

You might also like