Programming Basics

 

  1. JavaScript-- A Programming Language
  2. Lexical Structure
  3. Variables
  4. Data types
  5. Expressions and Operators
  6. Conditionals and Control Flow
  7. Loops
  8. Functions - Variables (local / global – value/ reference)

 

Programming Basics

 

A programming language consist of a series of predefined statements and capabilities used by the programmers to implement software applications. Examples of SW applications are: Windows OS, MS Word, etc..

 

JavaScript

 

JavaScript is an interpreted programming language with Object Oriented capabilities. Syntactically, the core JS language resembles C, C++, and Java.

 

We will learn basics principles of programming, using JavaScript. Once we have learned the basic concepts, we can easily implement them using LF Script- the scripting language we’ll use to implement workbooks.

 

Lexical Structure

 

The lexical structure of a programming is the set of elementary rules that specify how you write programs in the language.

-          Case sensitivity: JS is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters. For example: the while keyword, must be typed “while” and not “While” or “WHILE”.

-          Whitespace and line breaks: JS ignores spaces, tabs and newlines that appear between tokens in programs.

-          Optional semicolons: simple statements in JS are generally followed by semicolons (;), just as they are in C, C++ and Java. This serves to separate statements from each other. In JS, however, you are allowed to omit this semicolon if your statements are each placed on a separate line. For example:

a=3

b=4

or

a=3; b=4;

-          Omitting semicolons is not a good programming practice; you should get in the habit of using them.

-          Comments: any text between // and the end of a line is treated as a comment, also any text between /* and */ is treated as a comment.

 

Rules:

-          Comment, comment, comment! A basic rule of good programming style is that you should always think about the next person who has to look at your script. It might be a friend, a co-worker, an employer, or it could be you in three months. The easiest way to make sure you'll understand your own script in three months is to comment freely and often. If you want to comment a huge block of text, you can put it between /* and */ like this:

/* this is
a huge block
of text that I've
commented out */

-          Variables are defined at the top of the code, or functions

-          Indenting properly to make the code easy to read and understand

-          Modularity: Build logical segments of code to facilitate reusability

 

-          Templates are made for reuse

 

Variables

 

A variable is a name associated with a data value; the variable “stores” or “contains” the value.

 

Variables allow you to store and manipulate data in your programs.

Variables declaration

          Variables are declared using the keyword  ‘var’ followed by the name of the variable.

          Example:    var my_name;

Assignments

          To assign values to the variables we use the symbol ‘=’ followed by the value.

          Example:          my_name = “marilenis”;

                today_month = 12;

 

          You can give a variable a value when you declare it, or you can wait until later.

          Example: var my_name = “marilenis”;

 

Things to know about variables (good programming practice):

-          Variables must start with either a letter or the underscore character.

-          Variable names are case-sensitive.

-          Variables should describe what they are. X, Y are not good names for variables. Reward_Gas or Wrong_Answer1 are good names because they describe the values that the variables are storing.

-          You can give a variable a value when you declare it, or you can wait until later.

-          Statements end with a semicolon.

-          Variables should always be declared at the top of the code

 

Example in JavaScript: vars.html

Open vars.html in Notepad

 

Variables in QnA?

Variables or counters in QnA are used to keep track of Correct answers and Wrong answers.

Examples of variables declaration in QnA:

XRam    CACount,1

XRam    WACount,1

 

In this case, we are declaring two variables, type Xram, and allocating 1Byte of RAM to store the value of each counter.

 

Data types

An important difference between JS and other languages like C, C++ is that JS is untyped. This means that a JS variable can hold a value of any data type. For example:

 

Var x;

 

x = 10;

x = “Joseph”;

 

In this case the variables are storing two types os data: an integer and a string.

Other languages like C, C++, Java and LFScript are typed, which means that the variables can hold only the one particular type of data for which it is declared. For these languages the vars declaration looks like:

 

Var string x;

x = “Joseph”;

 

Var integer y;

y = 10;

 

The syntax used in LFScript language to declare the variable X of type T in ROM is:

 

Rom X: T = value;

 

 

 

 

 

Expressions and Operators

 

An expression is a “phrase” of JS that a JS interpreter can evaluate to produce a value. The simplest expressions are literals or variable names, like these:

 

10

“Joseph”

 

More interesting expressions can be created by combining simple expressions. For example:

 

10 + “Joseph”

 

The + is an operator used to combine two expressions into a more complex one. Some examples of operators are: *, /, %, +, -, &

 

Let’s see some examples: expressions.html

 

Conditionals and Control Flow Statements

 

A JavaScript program is simply a collection of statements. Statements usually end with semicolons.

 

Conditional

 

If … else

The if statement allows the program to make decisions, or to execute statements conditionally.

 

Syntax 1:

     If  (expression) {

          Statement

     }

 

Expression is evaluated. If the resulting value is true, then statement is executed. If the expression is false, then statement is not executed.

 

For example:

     Var my_name = “marilenis”;

 

     If (my_name == “marilenis”) {

          Print(“Your name is correct”);

     }

 

Syntax 2:

     If  (expression) {

          Statement1

     }

     Else {

         Statement2

     }

                    

Expression is evaluated. If the resulting value is true, then statement1 is executed, otherwise statement2 is executed.

 

For example:

     Var my_name = “joseph”;

 

     If (my_name == “marilenis”) {

          Print(“Your name is correct”);

     }

     Else {

          Print(“Your name is incorrect”);

     }

 

Note: Using curly brackets {} to enclose the bodies of if and else statements is a good programming practice.   

 

Syntax 3:

     If  (expression1) {

          Statement1

     }

     Else if (expression2) {

          Statement2

     }

     Else if (expression3) {

          Statement3  

     }

                    

Expression1 is evaluated. If the resulting value is true, then statement1 is executed, otherwise expression2 is evaluated, If the resulting value is true, then statement2 is executed, otherwise expression3 is evaluated …

 

This form is used when we need to execute one of many pieces of code.

 

Note: The coding convention of “expression/statement” in JavaScript is analagous to the conceptual sequence of “event/action” in the State Machine model. That is to say, “If event1 occurs, do action1”.

 

Switch

An if statement causes a branch in the flow of a program’s execution. You can use multiple if statements, as in the previous section, to perform a multi-way branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.

 

To handle this situation we use a switch statement.

 

Switch (expression) {

     statements

}

 

The statement is composed by blocks of code labeled with the case keyword followed by a value and a colon. When a swith executes, it computes the value of the expression, and then looks for a case label that matches the value.If it finds one, it starts executing the block of code at the first statement following the case label. If it does not find a case label with a matching value, it starts execution at the first statement following a special case default: label. Or, if there is no default: label, it skips the block of code altogether.

 

Example:

 

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:                        //Start here if n==4

          // Execute code block #4

     break;                          //Stop here    

}

 

Note the break keyword used at the end of each case . The break statement causes execution to jump to the end of a switch statement or loop. The break statement specifies an ending point. In the absence of break statements, a switch statement begins executing its block of code at the case label that matches the value of its expression and continues executing statements until it reaches the end of the block. Another keyword is continue. The continue statement is used in a similar manner to break, but instead of exiting the loop, continue causes execution to jump back to the first case and and proceed with the loop as before.

 

Note:  A block of switch code with several cases is a good illustration of how a state machine handles event processing.  Each case, evaluated within a state, represents the equivalent of an event description and a pointer to a handler for that action which says what to do, and where to go (which state) next.

 

Loops:

-          While

-          For

 

While

The while is the basic statement that allows JavaScript to perform repetitive actions. It has the following syntax:

 

While (expression) {

     Statement

}

 

The while statement works by first evaluating the expression. If it is false, JavaScript moves on to the next statement in the program. If it is true, the statement that forms the body of the loop is executed and expression is evaluated again. Again, if the value of expression is false, JS moves on to the next statement in the program; otherwise it executes the statement again.  This cycle continues until expression evaluates to false, at which point the while statement ends and JS moves on. NOTE that you can create an infinite loop with the syntax while(true);

 

Open while.html in your browser

Open while.html in Notepad

 

Note: in this example the variable count starts off at 0 and is incremented each time the body of the loop runs. Once the loop has executed 10 times, the expression becomes false (i.e, the variable count is no longer less than 10), the while statement finishes, and JS can move on to the next statement in the program.

 

For

The for statement provides a looping construct. It uses a counter variable that is initialized before the loop starts and then it is tested as part of the expression evaluated before each iteration of the loop.

 

The initialization, the test, and the update are the three crucial operations of a loop variable; the for statement makes these three steps an explicit part of the loop syntax.

 

The syntax of the for statement is:

 

For (initialize; test; increment) {

     statement

}

 

Initialize is evaluated once- This expression is usually an assignment. Test is evaluated before each iteration and controls whether the body of the loop is executed. If the test expression is true, the statement that is the body of the loop is executed. This can be represented by the following pseudo-code:

 

     Initialize;

     While(test=true) {

          Statement;

          Increment;

     }

 

Open for.hrml in the browser

Open for.html in Notepad

Let’s analyze how it works .. Your homework is: read for_complex.html, play with it and analyze how it works.

 

Functions

 

A function is a piece of code that is defined once in a program and can be executed, or invoked, many times by the program. A function can be passed arguments, or parameters, specifying the value or values that the function is to operate upon, and a function can return a value. Functions are defined in JS with code like this:

 

function square(x)

{

     return x*x;

}

 

Once a function is defined, you can invoke it by following the function’s name with an optional comma-separated list of arguments within parameters. The following lines are examples of functions invocations:

 

y = square(x);

calculate_distance(x1, y1, z1, x2, y2, z2);

 

The most common way to define a function is with the function statement. This consist of the function keyword, which is followed by:

-         The name of the function

-         An optional comma-separated list of parameters names in parentheses

-         The statements that comprise the body of the function, contained within curly brackets

-         Functions may or may not contain a return statement

 

The return statement causes the function to stop executing and return the value of its expression (if any) to the caller. If a function does not contain a return statement, it simply executes each statement in the function body and returns the undefined value to the caller.

 

Function parameters (value/reference)

 

A function accepts two types of parameters: value and reference.

Value means that the value of the parameter is used in the function statements but the variable passed as a parameter is not affected by the function.

Reference means that the function statements use the variable passed as a parameter, perform calculations and possibly modify the value of the variable passed as a parameter.

Expressions can be used as parameters. When you invoke a function, each of the expressions you specify between the parentheses is evaluated and the resulting value is used as an argument of the function. These values are assigned to the parameters named when the function was defined, and the function operates on its parameters by referring to them by name.

 

Variable scope (global and local)

 

The scope of a variable is the region of your program in which it is defined. A global variable has  a global scope- it is defined everywhere in your JS code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope. Function parameters also count as local variables and are defined only within the body of the function.

 

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively “hide” the global variable.