STATEMENTS Flashcards
1) What is the difference btw expressions and statements?:-
Expressions are evaluated to produce a value, but statements are executed to make something happen.
- One way to “make something happen” is to evaluate an expression that has side effects. Expressions with side effects, such as assignments and function invocations, can stand alone as statements, and when used this way are known as expression statements. A similar category of statements are the declaration statements that declare new variables and define new functions.
2) JavaScript programs are nothing more than a sequence of statements to execute. By default, the JavaScript
interpreter executes these statements one after another in the order they are written. Another way to “make
something happen” is to alter this default order of execution, and JavaScript has a number of statements or
control structures that do just this. Name the three groups and examples?:-
-> Conditionals statements like if and switch that make the JavaScript interpreter execute or skip other
statements depending on the value of an expression
-> Loops statements like while and for that execute other statements repetitively.
-> Jumps statements like break, return, and throw that cause the interpreter to jump to another part of the
program
3) The empty statement allows you to?:-
include no statements where one is expected. The empty statement looks like this:
;
- The JavaScript interpreter takes no action when it executes an empty statement. The empty statement is
occasionally useful when you want to create a loop that has an empty body. Consider the following for loop:
// Initialize an array a
for(let i = 0; i < a.length; a[i++] = 0) /* empty */ ;
- In this loop, all the work is done by the expression a[i++] = 0, and no loop body is necessary. JavaScript
syntax requires a statement as a loop body, however, so an empty statement—just a bare semicolon—is used.
When you intentionally use the empty statement, it is a good idea to comment your code in a way that makes it
clear that you are doing it on purpose.
4) The rule in JavaScript (as in most programming languages) is that by default an else clause is part of the ___ if statement?:-
nearest (even though you can remove the {}, it is alway best to use then, because it become clear which else goes with which if).
5) The if/else statement evaluates an expression and executes one of two pieces of code, depending on the outcome. But what about when you need to execute one of many pieces of code? One way to do this is with an?:-
else if statement. else if is not really a JavaScript statement, but simply a frequently used programming idiom
that results when repeated if/else statements are used:
if (n === 1) {
// Execute code block #1
} else if (n === 2) {
// Execute code block #2
} else if (n === 3) {
// Execute code block #3
} else {
// If all else fails, execute block #4
}
the alternative is the fully nested form:
if (n === 1) {
// Execute code block #1
}
else {
if (n === 2) {
// Execute code block #2
}
else {
if (n === 3) {
// Execute code block #3
}
else {
// If all else fails, execute block #4
}
}
}
6) An if statement causes a branch in the flow of a program’s execution, and you can use the else if idiom to
perform a multiway branch. This is not the best solution, however, when all of the branches depend on the value of the same expression. In this case, it is wasteful to repeatedly evaluate that expression in multiple
if statements. which statement handles this situation best?:-
The switch statement handles exactly this situation. The switch keyword is followed by an expression in
parentheses and a block of code in curly braces:
switch(expression) {
statements
}
- Sameness is determined by the === operator, so the expressions must match without any type conversion.
- The case clauses in a switch statement specify only the starting point of the desired code;
- When using switch inside a function, however, you may use a return statement instead of a break statement. Both serve to terminate the switch statement and prevent execution from falling through to the next case.
function convert(x) {
switch (typeof x) {
case “number”: // Convert the number to a hexadecimal integer
return x.toString(16);
case “string”: // Return the string enclosed in quotes
return ‘”’ + x + ‘”’;
default: // Convert any other type in the usual way
return String(x);
}
}
7) Because not all of the case expressions are evaluated each time the switch statement is executed, you should avoid using case expressions that contain?:-
side effects such as function calls or assignments. The safest course is simply to limit your case expressions
to constant expressions.
- Note that, the default: label appears at the end of the switch body, following all the case labels. This is a
logical and common place for it, but it can actually appear anywhere within the body of the statement.
8) JavaScript has five looping statements name then?:-
while, do/while, for, for/of (and its for/await variant), and for/in.
- The do while loop must always be terminated with a semicolon. The while loop doesn’t need a semicolon if the loop body is enclosed in curly braces.
- for(;;) is another way of writing an infinite loop, like while(true).
9) ES6 defines a new loop statement: for/of. This new kind of loop uses the for key‐word but is a completely
different kind of loop than the regular for loop. It is also completely different than the older for/in loop.
How does it work?:-
The for/of loop works with iterable objects. We’ll explain later exactly what it means for an object to be
iterable, but for now, it is enough to know that arrays, strings, sets, and maps are iterable: they represent a
sequence or set of elements that you can loop or iterate through using a for/of loop.
Here, for example, is how we can use for/of to loop through the elements of an array of numbers and compute
their sum:
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
sum += element;
}
sum // => 45
10) (for/of with objects) Objects are not (by default) iterable. What happens when you attempt to use for/of on a regular object?:-
a TypeError is thrown at runtime:
let o = { x: 1, y: 2, z: 3 };
for(let element of o) { // Throws TypeError because o is not iterable
console.log(element);
}
11) If you want to iterate through the properties of an object, you can use(name the two loops and condtions
that have to be meet for each loop, if any)?:-
-> the for/in loop,
-> or use for/of with the Object.keys() method(Because by default ordinary objects are not iterable):
let o = { x: 1, y: 2, z: 3 };
for(let element of o) { // Throws TypeError because o is not iterable
console.log(element);
}
let o = { x: 1, y: 2, z: 3 }; let keys = “”;
for(let k of Object.keys(o)) {
keys += k; }
keys // => “xyz”
- This works because Object.keys() returns an array of property names for an object, and arrays are iterable
with for/of. Note also that this iteration of the keys of an object is not live as an array would be, changes
to the object o made in the loop body will have no effect on the iteration. - If you don’t care about the keys of an object, you can also iterate through their corresponding values like
this:
let sum = 0;
for(let v of Object.values(o)) {
sum += v;
}
sum // => 6
12) If you are interested in both the keys and the values of an object’s properties, you can use for/of with
Object.entries() and destructuring assignment. Show code implimentation?:-
let o = { x: 1, y: 2, z: 3 };
let pairs = “”;
for(let [k, v] of Object.entries(o)) {
pairs += k + v;
}
pairs // => “x1y2z3”
- Object.entries() returns an array of arrays, where each inner array represents a key/value pair for one
property of the object. We use destructuring assignment in this code example to unpack those inner arrays into two individual variables.
13) (for/of with strings) Strings are iterable character-by-character in ES6. Implement a letter frequence
counter program for the word “mississippi” ?:-
let frequency = {};
for(let letter of “mississippi”) {
if (frequency[letter]) {
frequency[letter]++;
} else {
frequency[letter] = 1;
}
}
frequency // => {m: 1, i: 4, s: 4, p: 2}
- Note that strings are iterated by Unicode codepoint, not by UTF-16 character. The string “I ❤ do emoji ”
has a .length of 5 (because the two emoji characters each require two UTF-16 characters to represent). But if
you iterate that string with for/of, the loop body will run three times, once for each of the three code points
“I”, “❤”, and “ dog agian .”
14) The built-in ES6 Set and Map classes are iterable. When you iterate a Set with for/of, the loop body runs
once for each element of the set. You could use code like this to print the unique words in a string of text?:-
let text = “Na na na na na na na na Batman!”;
let wordSet = new Set(text.split(“ “));
let unique = [];
for (let word of wordSet) {
unique.push(word);
}
unique // => [“Na”, “na”, “Batman!”]
15) Maps are an interesting case because the iterator for a Map object does not iterate the Map keys, or the
Map values, but __________. Each time through the iteration, the iterator returns?:-
-> key/value pairs an array whose first element is a key and whose second element is the corresponding value. Given a Map m, you could iterate and destructure its key/value pairs like this:
let m = new Map([[1, “one”]]);
for(let [key, value] of m) {
key // => 1
value // => “one”
}
16) ES2018 introduces a new kind of iterator, known as an asynchronous iterator, a variant of the?:-
for/of loop, known as the for/await loop that works with asynchronous iterators.
17) A for/in loop looks a lot like a for/of loop, with the of keyword changed to in. While a for/of loop
requires an iterable object after the of, a for/in loop works with?:-
any object after the in. The for/in statement loops through the property names of a specified object. The syntax looks like this:
for (variable in object) {
statement
}
let o = { x: 1, y: 2, z: 3 };
let a = [], i = 0;
for(a[i++] in o) /* empty */;
- The for/of loop is new in ES6, but for/in has been part of JavaScript since the very beginning (which is why
it has the more natural sounding syntax).
And you might use a for/in loop like this:
for(let p in o) { // Assign property names of o to variable p
console.log(o[p]); // Print the value of each property
}
- I find that a common source of bugs in my own code is the accidental use of for/in with arrays when I meant to use for/of. When working with arrays, you almost always want to use for/of instead of for/in.
18) The for/in loop does not actually enumerate all properties of an object. It does not enumerate properties
whose names are?:-
-> Symbols.
-> And of the properties whose names are strings, it only loops over the enumerable properties.
- The various built-in methods defined by core JavaScript are not enumerable. All objects have a toString()
method, for example, but the for/in loop does not enumerate this toString property. In addition to built-in
methods, many other properties of the built-in objects are non-enumerable. All properties and methods defined by your code are enumerable, by default. (You can make them non-enumerable using techniques tested later).
19) Enumerable inherited properties are also enumerated by the for/in loop. This means that if you use for/in
loops and also use code that defines properties that are inherited by all objects, then your loop may not behave in the way you expect. For this reason, many programmers prefer?:-
to use a for/of loop with Object.keys() instead of a for/in loop.
20) If the body of a for/in loop deletes a property that has not yet been enumerated, that property __________.
If the body of the loop defines new properties on the object, those properties?:-
-> will not be enumerated.
-> may or may not be enumerated.
21) Another category of JavaScript statements are jump statements. As the name implies, these cause the
JavaScript interpreter to?:-
jump to a new location in the source code.
23) Any statement may be labeled by preceding it with an identifier and a colon. By labeling a statement, you
give it a name that you can use to refer to it elsewhere in your program. You can label any statement, although it is only useful to label statements that?:-
have bodies, such as loops and conditionals.
- By giving a loop a name, you can use break and continue statements inside the body of the loop to exit the
loop or to jump directly to the top of the loop to begin the next iteration. break and continue are the only
JavaScript statements that use statement label.
identifier: statement
mainloop: while(token !== null) {
// Code omitted…
continue mainloop; // Jump to the next iteration of the named loop
// More code omitted…
}
- A statement may not have the same label as a statement that contains it, but two statements may have the same label as long as neither one is nested within the other. Labeled statements may themselves be labeled.
Effectively, this means that any statement may have multiple labels.