1 Declarations with let and const
2 Variable Declarations with var
3 Declarations with var VS declarations with let
4 Execution Context
5 Destructuring Assignment
Programmers use name or identifier to represent values:
- you declare a variable and assign the variable a value; later, you refer to that value using the variable's name.
- this is said binding a name to a value.
Variable declaration
- until ECMAScript 5, variables and constants are declared using the keyword
var - in ECMAScript 6, variables are declared by the
letkeyword and constants by theconstkeyword -
letandconstwork the same way, butconstmust always be initialized.
1 Declarations with let and const
// a declaration statement for each variable let i; let myVariable; // a single statement for declaring multiple variables let i, myVariable; // variables declaration and initialization let x = 1, y = 1, z = 1; let text = 'Hello User'; // the speed of light constant const C = 299792458;
You can use the let keyword in the three kinds of for loop
to declare the loop variable
for(let i=0, l=data.length; i<l; i++) { // the for loop
console.log(data[i]); // data is array-like object
}
for(let item of data) { // the for/of loop
console.log(item); // data is iterable object
}
for(let propName in object) { // the for/in loop
console.log(propName); // data is plain object
}
Variable and Constant Scope
The scope of a variable is the area of the JS program where the variable is defined.
- variables and constants declared by
letorconststatements are block scoped: they are defined in the block of code where theletorconstappears. - JS blocks are: function and classes definitions, the bodies of
ifstatements,forandwhileloops; any set of curly braces constitutes a block of code. - note: variables declared as part of a for loop have their scope in the body of the loop.
A global variable is a variable that is declared at the top level, out of any block
- a global variable has global scope
- in a Node and client-side JS modules, modules have their scope. The scope a global variable is the file the variable is defined in.
- in client-side JS that do not use of modules, a web page can load any number JavaScript files using multiple
<script>elements. If a<script>element defines a global, that variable is defined in all the<script>elements that execute after theletstatement execution.
Repeated Declarations
It is an error to have two let or const declarations in the same scope
- You are allowed to re-declare a variable in a nested scope, but it is not a best practice.
Example: declare two variables with same name using let
let myVar = 10;
if(smth == true) {
let myVar = 100; // OK
}
let myVar = 100; // Syntax error
Variables and Types
JavaScript variables are untyped:
- no type is associated in a JS variable declaration
- it is legal to assign a number and then assign a string to the same variable
2 Variable Declarations with var
Until ECMAScript 5, you could declare variables only using the var keyword:
- the syntax of
varis the same oflet:
var myVariable = 'value';
for(var i = 0, len = data.length; i < len; i++) { // for loop
console.log(data[i]);
}
3 Declarations with var VS declarations with let
There are differences between var and let declared variables
- variables declared by
varare scoped to the immediate function body, while variables declared byletare scoped to the immediate enclosing block - unlike
letstatement, it is legal to declare multiple times the same variable using thevarstatement - variables declared by
varare hoisted: the declaration of the variable is moved up to the top of the function body, while the initialization remains in the place where the var statement appears. - variables declared by
var, out of any function, are global variables: these global variables are implemented as properties of the global object and cannot be deleted using thedeleteoperator.
Note: what happens if you try to use a variable name, omitting any of the var/let/const declaration statement?
- in strict mode you get a reference error; in non-strict mode, you create a global variable, even if your variable name is nested in a function or block. This is bug prone.
4 Execution Context
The execution context is the environment where the current code is being executed.
- the execution context of a variable or function defines what other data it has access to
- each execution context has an associated variable object that stores all variable and functions it defines. The variable object cannot be accessed by your programs, but is used behind the scenes to handle data
The global execution context
- the global execution context is the first context that is defined, when the JavaScript interpreter starts.
- in web browsers the global context is the window object
- when it has finished execution of all its code, the execution context is destroyed, along with all the variables and functions defined within it. The global context is destroyed when the application exits, for instance when a browser is closed
The function execution context
- each function invocation has its own execution context
- once a function starts executing, the function's context is pushed onto a context stack
- after the function has finished executing, the function's context is popped off, returning control to the previous executing context
- the current execution context of the context stack is the one that sits on the top of the stack
5 Destructuring Assignment
ECMAScript 6 destructuring:
- it is the process of breaking down a data structure into smaller parts
- it allows to extract the values contained in an array or an object and assign them to a variable
The destructuring assignment syntax
[ variable1, variable2, ... , variableN ] = array; // array destructuring assignment
{ variable1, variable2, ... , variableN } = object; // object destructuring assignment
- the left side specifies one or more variables, using a syntax that looks like array or object literals
- the right side assigns an array or an object value
The destructuring assignment can be used:
- in a variable declaration statement, to initialize variables
- in an assignment expression, to assign values to variable already declared
- in the definition of the parameters to a function.
Example: array destructuring
/**
* ARRAY DESTRUCTURING
*/
// the array to be destructured
const array = [5, 10];
// variable declaration and destructuring assignment
let [x, y] = array; // Same as let x=array[0], y=array[1]
console.log(x, y); // 5, 10
/* The number of variables on the left of a destructuring assignment does
not have to match the number of array elements on the right. */
[x,y] = [1]; // x == 1; y == undefined
[x,y] = [1,2,3]; // x == 1; y == 2
[,x,,y] = [1,2,3,4]; // x == 2; y == 4
// swapping variable values
[x,y] = [y,x]; // x == 4; y == 2
// default values
[x=10, y=20, z=30] = [1,2]; // x == 1; y == 2; z == 30
// rest syntax to collect remaining values
[x, ...y] = [1,2,3,4]; // y == [2,3,4]
/**
* DESTRUCTURING ITERABLES OBJECTS IN FOR/OF LOOPS
*/
let actresses = [
{firstName:'Uma', lastName:'Thurman'},
{firstName:'Scarlett', lastName:'Johansson'},
{firstName:'Jodie', lastName:'Foster'}
];
// loop variables are assigned elements of the array
for(const {firstName, lastName} of actresses) {
console.log(firstName, lastName);
}
/**
* DESTRUCTURING ITERABLE OBJECTS
*/
// You can destructure not only arrays but any iterable object: for example a String
let [first, ...rest] = "bye bye";
console.log(first); // "b";
console.log(rest); // ["y","e"," ","b","y","e"];
Example: object destructuring
/**
* OBJECT DESTRUCTURING
*/
// the objects to be destructured
let actress = {
firstName: 'Uma',
middleName: 'Karuna',
lastName: 'Thurman'
};
// 1 - ASSIGNMENT with DECLARATION
// variable have the same name of the properties of the destructured object
var {firstName, middleName, lastName} = actress; // same as: var firstName='Uma', middleName='Karuna', lastName='Thurman';
console.log(firstName, middleName, lastName); // "Uma Karuna Thurman"
// 2 - ASSIGNMENT without DECLARATION
// there must be parentheses around the assignment without declaration
({firstName, lastName} = actress);
console.log(firstName, lastName); // "Uma Thurman"
// variable names do not have to match property names of the destructured object
const {firstName: umaFirstName, lastName: umaLastName} = actress;
console.log(umaFirstName, umaLastName); // "Uma Thurman"
// another actress object, with no middleName property
actress = { firstName: 'Helena', lastName: 'Bonham Carter' };
// the destructured value of middleName is undefined
({firstName, middleName, lastName} = actress);
console.log(firstName, middleName, lastName); // "Helena undefined Bonham Carter"
// destructured assignment with default values
({firstName = 'Name', middleName = '', lastName = 'Surname'} = actress);
console.log(firstName, middleName, lastName); // "Helena Bonham Carter"
// nested object destructuring
let customer = {
displayName: 'john77',
firstName:'John',
lastName: 'Smith',
address: {
street: '17, Thomas Street West',
locality: 'Dublin',
county: 'County Dublin',
eircode: 'D08 XV0T',
country: 'Ireland'
},
phone: '+353 14370969',
email: 'johnsm@iemail.com'
};
// assignment with declaration
var {
displayName,
firstName,
lastName,
address: { street, locality, county, eircode, country },
phone,
} = customer;
console.log(`${displayName} is ${firstName} and lives in ${country}`); // john77 is John and lives in Ireland
/**
* DESTRUCTURING ARGUMENT OBJECTS INTO FUNCTION PARAMETERS
*/
function whois({ displayName, firstName, address: {country} }) {
return `${displayName} is ${firstName} and lives in ${country}`;
}
console.log(whois(customer)); // john77 is John and lives in Ireland
/**
* DESTRUCTURING OBJECTS IN FOR/OF LOOPS
*/
actress = { firstName: 'Uma', middleName: 'Karuna', lastName: 'Thurman' };
// loop variables are assigned elements of the array of entries
for(const [pName, pValue] of Object.entries(actress)) {
console.log(pName, pValue);
}
No comments:
Post a Comment