Skip to content

Latest commit

 

History

History
454 lines (339 loc) · 8.7 KB

5.STATEMENTS.md

File metadata and controls

454 lines (339 loc) · 8.7 KB

STATEMETNS

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

Conditionals

IF-ELSE

if (expression)
    statement


// --s

if (username == null)       // If username is null or undefined,
    username = "John Doe";  // define it

// --e


// --s
// If username is null, undefined, false, 0, "", or NaN, give it a new value
if (!username) username = "John Doe";
// --e


// --s
if (!address) {
    address = "";
    message = "Please specify a mailing address.";
}

// --e


// --s

if (expression)
    statement1
else
    statement2
// --e

// --s
if (n === 1)
    console.log("You have 1 new message.");
else
    console.log(`You have ${n} new messages.`);

// --e

// --s

i = j = 1;
k = 2;
if (i === j)
    if (j === k)
        console.log("i equals k");
else
    console.log("i doesn't equal j");    // WRONG!!

// JS Bunday deb o'ylaydi.

if (i === j) {
    if (j === k)
        console.log("i equals k");
    else
        console.log("i doesn't equal j");    // OOPS!
}


// -- e


// -- s

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
}

// -- e

SWITCH

switch(expression) {
    statements
}

// --S

switch(n) {
case 1:                        // Start here if n === 1
    // Execute code block #1.
    break;                     // Stop here
case 2:                        // Start here if n === 2
    // Execute code block #2.
    break;                     // Stop here
case 3:                        // Start here if n === 3
    // Execute code block #3.
    break;                     // Stop here
default:                       // If all else fails...
    // Execute code block #4.
    break;                     // Stop here
}
// --E


// --S
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);
    }
}
// -- E

LOOPS

while

while (expression)
    statement

let count = 0;
while(count < 10) {
    console.log(count);
    count++;
}

do/while

do
    statement
while (expression);


// -- S
function printArray(a) {
    let len = a.length, i = 0;
    if (len === 0) {
        console.log("Empty Array");
    } else {
        do {
            console.log(a[i]);
        } while(++i < len);
    }
}
// -- E

for

for(initialize ; test ; increment)
    statement

// For explanation
initialize;
while(test) {
    statement
    increment;
}


// -- S
for(let count = 0; count < 10; count++) {
    console.log(count);
}
// -- E

for/of

arrays, strings, sets, and maps are iterable

let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
    sum += element;
}
sum       // => 45

FOR/OF WITH OBJECTS

// -- S
let o = { x: 1, y: 2, z: 3 };
for(let element of o) { // Throws TypeError because o is not iterable
    console.log(element);
}
// -- E

// -- S
let o = { x: 1, y: 2, z: 3 };
let keys = "";
for(let k of Object.keys(o)) {
    keys += k;
}
keys  // => "xyz"
// -- E

// -- S
let sum = 0;
for(let v of Object.values(o)) {
    sum += v;
}
sum // => 6
// -- E

// -- S
let pairs = "";
for(let [k, v] of Object.entries(o)) {
    pairs += k + v;
}
pairs  // => "x1y2z3"
// -- E

FOR/OF WITH STRINGS

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}

FOR/OF WITH SET AND MAP

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!"]

// -- S
let m = new Map([[1, "one"]]);
for(let [key, value] of m) {
    key    // => 1
    value  // => "one"
}
// -- E

ASYNCHRONOUS ITERATION WITH FOR/AWAIT

// Read chunks from an asynchronously iterable stream and print them out
async function printStream(stream) {
    for await (let chunk of stream) {
        console.log(chunk);
    }
}

for/in

for (variable in object)
    statement



for(let p in o) {      // Assign property names of o to variable p
    console.log(o[p]); // Print the value of each property
}

/*
If it evaluates to null or undefined, the interpreter skips the loop and moves on to the next statement
*/


let o = { x: 1, y: 2, z: 3 };
let a = [], i = 0;
for(a[i++] in o) /* empty */;


// -- S
for(let i in a) console.log(i);
// -- E

Jumps

JavaScript allows statements to be named, or labeled, and break and continue can identify the target loop or other statement label.

The return statement makes the interpreter jump from a function invocation back to the code that invoked it and also supplies the value for the invocation.

The throw statement raises, or throws, an exception and is designed to work with the try/catch/finally statement, which establishes a block of exception-handling code.

break

for(let i = 0; i < a.length; i++) {
    if (a[i] === target) break;
}


// -- S
let matrix = getData();  // Get a 2D array of numbers from somewhere
// Now sum all the numbers in the matrix.
let sum = 0, success = false;
// Start with a labeled statement that we can break out of if errors occur
computeSum: if (matrix) {
    for(let x = 0; x < matrix.length; x++) {
        let row = matrix[x];
        if (!row) break computeSum;
        for(let y = 0; y < row.length; y++) {
            let cell = row[y];
            if (isNaN(cell)) break computeSum;
            sum += cell;
        }
    }
    success = true;
}
// The break statements jump here. If we arrive here with success == false
// then there was something wrong with the matrix we were given.
// Otherwise, sum contains the sum of all cells of the matrix.
// -- E

continue

continue;

continue labelname;


for(let i = 0; i < data.length; i++) {
    if (!data[i]) continue;  // Can't proceed with undefined data
    total += data[i];
}

return

return expression;

function square(x) { return x*x; } 
// A function that has a return statement
square(2)  

// -- S
function displayObject(o) {
    // Return immediately if the argument is null or undefined.
    if (!o) return;
    // Rest of function goes here...
}
// -- E

yield

Generator function bilan o'tiladi

throw

An exception is a signal that indicates that some sort of exceptional condition or error has occurred.

try/catch/finally

The try/catch/finally statement is JavaScript’s exception handling mechanism.

try {
    // Normally, this code runs from the top of the block to the bottom
    // without problems. But it can sometimes throw an exception,
    // either directly, with a throw statement, or indirectly, by calling
    // a method that throws an exception.
}
catch(e) {
    // The statements in this block are executed if, and only if, the try
    // block throws an exception. These statements can use the local variable
    // e to refer to the Error object or other value that was thrown.
    // This block may handle the exception somehow, may ignore the
    // exception by doing nothing, or may rethrow the exception with throw.
}
finally {
    // This block contains statements that are always executed, regardless of
    // what happens in the try block. They are executed whether the try
    // block terminates:
    //   1) normally, after reaching the bottom of the block
    //   2) because of a break, continue, or return statement
    //   3) with an exception that is handled by a catch clause above
    //   4) with an uncaught exception that is still propagating
}
try {
    // Ask the user to enter a number
    let n = Number(prompt("Please enter a positive integer", ""));
    // Compute the factorial of the number, assuming the input is valid
    let f = factorial(n);
    // Display the result
    alert(n + "! = " + f);
}
catch(ex) {     // If the user's input was not valid, we end up here
    alert(ex);  // Tell the user what the error is
}