DEV Community

Cover image for Reviewing Eloquent Javascript #Chpt2
Prerana Nawar
Prerana Nawar

Posted on

Reviewing Eloquent Javascript #Chpt2

In this blog, I will write on my learnings from the Eloquent Javascript Book's Chapter 2 : Program Structure.

Here's the PDF for Eloquent Javascript Book's Chapter 2.

TOC:

  1. Expressions and Statements
  2. Bindings
  3. Declaring a Binding
  4. Functions
  5. Control flow
  6. break & continue
  7. Switch Statement
  8. Exercises

Expressions and Statements

  • A piece of code that produces a value is called an expression. An expression is created by combining variables, values and operators. That's why we always say Arthimetic Expressions and Logical Expressions because it always outputs a value whether it be numerical value or boolean value.

    
     10 + 20; // Expression that produces the numeric value 30
     10 > 9; // produces to boolean value true
    
    
  • On the other hand, a statement is an instruction to perform a specific action, and that's why we say conditional statements because conditional statements execute statements based on the value of an expression. A program is a list of statements.

    
     let number = 10;
    
    
  • Semicolons are used to end a statement. You can choose to not write them (because there is ASI: Automatic Semicolon Insertion in Javascript).

  • If you want to know more about ASI Rules here's a list.

  • Remember : We CAN'T omit it semicolon when having two or more expressions on the same line.

    
     let num1 = 10; let num2 = 20; c = num1 * num2; console.log(c);
    
    

Bindings

  • To understand Bingings (variables) in Javascript first think of bings as arrows pointing to values rather than thinking to containers storing the value. Two bindings can refer to the same value
  • In Javascript , the type of value assigned to a variable decides whether the value is stored with by value or by reference.
  • All primitive types that are Boolean, null, undefined, String, and Number are stored by value.
  • All Objects including Array, Function are stored by Reference.
  • When we define a binding without giving it a value, its undefined.

    Alt Text

  • The collection of bindings and their values that exist at a given time is called the environment.

Declaring a Binding

  • let and const were introduced in ES6 (newer).
  • Scoping:
    • var : function scoped (only available inside parent functions)
    • let and const : block scoped (available inside a block denoted by { } )
  • Remember: The name of a variable should always reflect the meaning of its contents, like when you label boxes (mnemonic).

    • Example: ❌ This is not Mnemonic
    
     let a = 8                          
     let b = 1000
     let c = a * b
     console.log(c);
    
    
    • Example: ✅ This is Mnemonic
    
     let hours = 8                          
     let rate = 1000
     let pay = hours * rate
     console.log(pay);
    
    
  • When to use what : Use const by default; if the value of the variable needs to change then use let. Almost never use var.

  • Variable naming conventions:

    • Should not start with capital unless they are a class.
    • Must start with a-z or _ or $.
    • If a variable is multi-word, you can use:
      • Camel-case: let inputNumber = 0;
      • Pascal Case: let InputNumber = 0;
      • Snake case: let input_number = 0;

Functions

  • A function is a group of statements that performs a particular task. Functions allow us to repeat tasks that involve a similar sequence of steps (processing).

Alt Text

If you want to know more about Functions, Loops, Conditional Statements I have wrote a separate blog on it: link.

Control flow

  • In computer programming, control flow or flow of control is the order function calls, instructions, and statements are executed or evaluated when a program is running.

Alt Text

break & continue

  • Two statements, break and continue, provide more control upon loops in Javascript.
  • The break statement immediately stops the loop and passes the execution to the next statement after the loop ( jumps out ).

    
     for (i = 0; i < 10; i++) {
       if (i === 5) { 
            break; 
       }
       console.log(i);
     }  
    
     // Output : 
     0
     1
     2
     3
     4
    
    
  • On the other hand, the continue statement breaks one iteration (in the loop) and continues with the next iteration in the loop ( jumps over ).

    
     for (i = 0; i < 5; i++) {
       if (i === 3) { 
            continue; 
       }
       console.log(i);
     }
    
     //Output:
     0
     1
     2
     4
     5
    
    

Switch Statement

  • Switch is an alternative to nested if statements.
  • Syntax:

    
     switch (expression) {
        case value1:
            statement
            break;
        case value2:
            statement
            break;
        case valueN:
            statement
            break;
        default:
            statement
        }
    
    
    • The value of the expression is compared with the values of each case.
    • If there is a match, the associated block of code is executed.
    • If there is no match, the default code block is executed.

Exercises

  • Looping a triangle .

    #
    ##
    ###
    ####
    #####
    ######
    #######

    • Code:
    
    let num = 7;
    for (i = 1; i <= num; i++) {
        var str = "";
        for (j = 1; j <= i; j++) {
            str = str + "# ";
        }
        console.log(str);
    }
    
    
  • FizzBuzz

    • Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz" for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).
    • Code:
    
     for (let i = 1; i <= 100; i++) {
        // console.log(i);
        if (i % 3 === 0) {
            if (i % 5 === 0 && i % 3 === 0) {
                console.log("FizzBuzz");
            } else {
                console.log("Fizz");
            }
        } else if (i % 5 === 0 && i % 3 !== 0) {
            if (i % 5 === 0 && i % 3 === 0) {
                console.log("FizzBuzz");
            } else {
                console.log("Buzz");
            }
        } else {
            console.log(i);
        }
     }
    
    
  • Chessboard

    • Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a "#" character. The characters should form a chessboard.

      
         # # # #
       # # # # 
         # # # #
       # # # # 
         # # # #
       # # # # 
         # # # #
       # # # #
      
      
    • Code

    
     var size = 8; 
     var result = "";
    
     for (var i = 0; i < size; i++) {  
       for (var j = 0; j < size; j++) {
         if ((j + i) % 2 == 0)
           result += " ";
         else
           result += "#";
       }
       result = result + "\n";
     }
    
    console.log(result);
    
    

    Again, So that's all these are my key Learning from the Chapter 2 of Book Eloquent Javascript. Also, Please do share your key learning from the Chapter 1 and what did you understood the most.

    This is a Bloging Challenge from #teamtanayejschallenge

    Here's a link to the Website: https://ejs-challenge.netlify.app/

    References:

    MDN Javascript

    Javasript Info

    W3School Javascript

    Thank you very much for the patience. I’d love to hear your feedback about the post. Let me know what you think about this article, and javascript in general, through my Twitter and LinkedIn handles. I would love to connect with you out there!

    Peace!

Discussion (0)