Skip to main content
Engineering LibreTexts

3.2: Primer on JavaScript

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    This section covers the basic procedural constructs of the JavaScript language. It covers the material that most programmers will be familiar with: variables, procedural constructs (branching and loops), and functions. While some concepts will be different from how most readers are used to thinking about them, all of the concepts here should be similar to concepts the readers already know. It is thus a primer, or elementary introduction, to JavaScript.

    3.2.1 Variable Types

    Variables in JavaScript are declared using a let12 statement (see important footnote below). For example, the variable loopCount can be declared as follows:

    Program 25 - Declaring a variable using let in JavaScript
    let loopCount;

    To someone coming from a strongly typed language such as Java, this statement is strange in that it does not declare the type of the variable, only that the variable exists. This is because JavaScript is a dynamic (or loosely) typed language. The type of the variable is the type of the last value that was assigned to it. A variable can, and very often does, change type during the execution of a program. This is illustrated in the following code fragment, where aVar is changed from a number to a string.

    Program 26 - Dynamic Typing in JavaScript
    let aVar = 7; // aVar is a number 
    aVar = “a string”; // aVar is now a string

    Dynamic typing is something that a programmer coming from a strongly typed language must become accustom to and requires the programmer to carefully consider their code or strange bugs can be introduced. Consider, for example, the following Java code fragment:

    Program 27 - Static typing failing when casting in Java
    int aVar = 7; 
    String s = "6";
    aVar = aVar + s;

    This code fragment will cause a type cast compiler error in Java, as the + sign casts the value of aVar to a string on the right-hand-side(rhs) of the equation, does concatenation to a string that is returned, and then tries to set the string to aVar, an int, which is invalid. The equivalent code fragment in JavaScript simply converts the variable aVar to a string, and performs concatenation, yielding the possible erroneous result of a string containing “76”.

    Program 28 - Program works in JavaScript as variable type is changed
        let aVar = 7;
        let s = "6";
        aVar = aVar + s;

    If the let keyword does not define a type, why use it? The purpose of the let keyword is to define the scope of a variable. It can be dropped altogether, in which case the variable defaults to global scope. The scope of a variable has three possibilities in JavaScript (ES6): global, function, and local scope. The rules of scope are as follows. A variable is declared with a let in a block, other than a function it is a local variable. A variable declared with a let that is contained in a function block defaults to the function where it is scoped. A variable not declared in any block, or a variable that is not declared using the let keyword, has global scope.

    These scoping rules are not as easy as they might appear. And since we are not yet using functions, variables in this section will have global or local scope. If the variable is declared in a block (between {}) it is a local variable, otherwise it is global scope. However, whether it is global or local should not have an impact on the examples in this section.

    This text will recommend that the reader use the let keyword to declare all variables. Scope plays a different, and I would argue a larger, role in JavaScript than many other languages. Later in this text it will always be required, as not using it leads to endless confusion. Therefore, I strongly recommend the reader get into the habit of using the let keyword now. But any further elucidation of the word let will have to wait until later in the text.

    There are 6 primitive types in JavaScript and one complex variable type called an Object. Information on the Object and Symbol types will be deferred until later in the text, but the other 5 primitive types are13:

    • Boolean: A Boolean is a binary logical value containing either true or false.
    • Number: There is only one number type in JavaScript, and it is a 64-bit IEEE 754 double precision (or floating point) number 14. The number can also be used as an integer value, and when used as an integer it will have 52 bits binary precision (or 15 digits precision), and allow integer values from -2251799813685248...2251799813685247
    • String: A string is a textural representation of data. It consists of indexed 16-bit character values
    • Null: A variable having a null value is defined and has a value, but that value is the null.
    • Undefined: A variable that has not been assigned a value.

    Some novice programmers have difficulties with the difference between null and undefined values. To have a null value, there must be a declared variable. It must be a variable, but the variable has no value. However undefined means the variable is not declared. Understanding this difference is common, and many web pages can be found using Google to find more information on it.

    3.2.2 Arrays

    Arrays in JavaScript are not like arrays in languages that most students are familiar with. Arrays in JavaScript are in reality map structures (normally called hashes or associative arrays) that use an index as a key. Even when used with an index, JavaScript arrays behave more like a Java ArrayList than a Java array. However, having warned the reader about the complexity of the JavaScript array, that complexity will be deferred until later in the text. For now, arrays will be treated like arrays in most of the languages the readers will be familiar with.

    An array can be created in two ways. The first way to create an array is to set a variable equal to an array literal, as in the following example.

    Program 29 - Creating an array variable by assigning the variable to an array literal
    var weekDays = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]

    As this example shows, to initialize an array in JavaScript, the variable is set to an array literal, or a value that is an array, and uses square brackets ([]) to contain the array members. This is a small difference from C derivative languages that use curly braces ({}) for array initialization. JavaScript will often look similar to other languages, but programmers should be careful as there are small syntax differences15.

    The second way to create an array is to call the Array() constructor function optional size of the array.

    Program 30 - Creating an array by calling a Constructor function
    var weekDays = new Array(5);

    Once again there is more than just a syntactic difference in using parenthesis (()) rather than square brackets ([]) when creating an array, and this will become apparent later when the semantic meaning of an array is looked at in more detail.

    The members of the array are accessed using the square brackets, [], and should be familiar to most reader.

    Program 31 - Assigning array values
    weekDays[0] = “Monday”;
    weekDays[1] = “Tuesday”; // etc.

    Arrays are zero based, as in most programming language, so the first element in the array is array[0], and the second element in the array is array[1], etc.

    Arrays in JavaScript automatically allocate space when needed, like a Java ArrayList. So, the following code would result in a weekDays array consisting of 5 members, not an ArrayIndexOutOfBounds exception as in Java.

    Program 32 - Showing how arrays automatically creates new space
    weekDays = new Array(2); 
    weekDays[0] = “Monday”; 
    weekDays[1] = “Tuesday”; 
    weekDays[2] = “Wednesday”; 
    weekDays[3] = “Thursday”; 
    weekDays[4] = “Friday”;

    Even though the true nature of arrays in JavaScript has been hinted at here, the examples used so far should at least look familiar to the reader and will be sufficient for the rest of this chapter.

    3.2.3 Procedural constructs

    There is a famous computer science theorem, the “Boehm-Jacopini Structured Programming Theorem”, which holds that all programs can be generated using only three programming constructs:

    1. A sequence which is just one statement after another.
    2. A branch, such as an if statement.
    3. A loop, such as a while or for loop.

    A sequence is easy to understand, as one statement follows. The other two structures will be covered in more detail in the subsequent sections of this chapter.

    Once again, the purpose of this book as a primer for preparing students to work with map applications is emphasized. There are a number of different JavaScript control structures, such as do-while switch, etcetera, that are not covered. This does not mean that they are not useful; however, they do not provide value to the purpose of this text. As was stated at the beginning of this text, this is not a text on JavaScript or any other technology, but a basic overview of technologies and how they fit together.

    3.2.4 if statement

    if statements correlate almost exactly to if statements in Java/C/C++/C#/etcetera. The format of an if statement follows:

    Program 33 - Format of an if statement
    if (condition) statement;

    In the if statement, the condition represents a variable or expression that reduces to a single value that is treated like a logic having values true and false.

    To use an if statement, the condition is reduced to a logic value and checked if it is true or false. The statement after the condition is run if the value is true.

    The statement after the condition is any valid JavaScript statement. The statement could be a single line of code, a block of code between two curly braces, or a null statement. The following code fragment shows these three possibilities.

    Program 34 - Format of if-else statement
    if (x < 100)
        x = x = 1; // statement is a single line of code
    if (x < 100){
        x = x + 1; // statement is a block of code
        y = y – 1;
    if (x < 100); // statement is null    

    Each if statement can contain a corresponding else condition that is executed when the condition in the if statement is false, as show below.

    Program 35 - Format of if-else statement
    if (condition) statement; // Do if true
    else statement; // do if false

    Finally, if and else statements can be combined to create if...else if...else blocks

    Program 36 - Format of if - else if - else statement
    if (condition) statement;
    else if (condition) statement;
    else statement;

    All of these branch operations should be familiar to programmers coming from nearly any language. It is assumed that the reader will be familiar with these statements, and they will not be covered in any more detail.

    There is one big difference between the if statement in JavaScript and some other languages like Java and C#. This difference has to do with the condition. The condition for if statement in Java/C# must be a boolean value of true/false. If any type other than a boolean is used for a condition, the compiler will produce an error. This is why the following statement produces a compiler error. The condition is set from the return value of the assignment (=) operation, which has a value of a long, not a Boolean.

    Program 37 - if statement that fails in Java
    long k = 12;
    if (k = 7) alert (“true”);

    In this case, the user probably wanted to use the comparison (==) operator. The == operator returns a Boolean value, so the statement with the == operator is valid.

    Program 38 - if statement that works in Java
    k = 12;
    if (k == 7) alert (“true”);

    There are a number of things to cover here. First, the assignment (=) and comparison (==) operators return values. It is hoped that readers are familiar with this idea that an operator is like a function and returns a value. Further it shows that the == statement always returns a logical value (or boolean) value. Finally it shows that Java/C# only allow boolean values for the condition variables.

    In JavaScript, the condition variable for an if statement can be of any type, which is the same as in C/C++. The condition variable is not a boolean value; instead the condition value is false if it is 0 and otherwise true. It does not matter what the type of the condition variable is, it is not checked in JavaScript.

    But because JavaScript allows the condition variable to be of any type, the following examples are all perfectly legitimate in JavaScript. The first 4 result in non-zero values, and would be true. The last two result in values of 0, and return false.

    Program 39 - Examples of true conditions in JavaScript
    // The following are all true
    if (true) alert("true");
    if (7) alert ("true");
    if("false") alert("true")
    var1 = 9
        if (var1 = 7) alert("true")
    // The following are false
    if (0) ;
    else alert("false")
    var2 = 9
        if (va2 = 0);
        else alert("false")

    This becomes an issue is when using the assignment (=) operator and the comparison (==) for values. Consider the following code fragment, where the programmer incorrectly typed the assignment operator (=) instead of the comparison operator (==)

    Program 40 - Incorrect result of using = for condition variable
    k = 12;
    if (k = 7) alert (“true);

    This statement always returns true since the assignment operator (=) sets the value of k to 7, and then returns a value of 7, which is true. If k were set to 0, this statement would always return false. This problem is addressed in most IDE’s, but that does not remove it from the language, and it is a problem the programmer must always be aware of.

    Other than the assignment (=) and comparison (==) operators, the other logical condition operation will look familiar to most programmers, and correctly return Boolean values. The condition statement supports all of the normal comparison operations, such as ==, >, <, >=, and <=. The logical &&, ||, and ! also work, and short circuit as expected.

    Usefully these logical operations even work on string types, so it is possible to write the following.

    Program 41 - Examples of comparison operators with strings
    let a = “name”;
    if (a == “name”); // true
    if (a >= “abcd”); // false

    3.2.5 Sentinel control loops - while statement

    There are generally three types of looping constructs: A sentinel control loop loops until some condition is met; a counter control loop, that loops a specified number of times; and an iterator, that loops over some data structure such as an array and performs an operation on each member of that data structure. These three looping constructs are often associated with while statements, for statements, and iterator loop17.

    These three types of loops will be covered in the next three sections. This section will cover the sentinel control loop, implemented with a while statement.

    The schema18 for a sentinel control loop is the following:

    Program 42 - Schema for a Sentinel Control loop
    Process the initial input, and set the initial loop condition
    Check the loop condition
        Process the data for each iteration of the loop
        Process the new input, and update the loop condition
    End of loop    

    The following JavaScript program shows an implementation of a sentinel control loop. In this plan, the user is asked to input, using the JavaScript prompt() function, a numeric value. The program then squares the number, uses the JavaScript alert() function to print the result back to the user, and prompts the user for the next number. This is repeated zero or more times until the users enters the sentinel value, -1, at which point the loop stops.

    Program 43 - Implementation of a Sentinel Control loop in JavaScript
        let inputValue = prompt("please enter a number, or -1 to stop")
        while(inputValue != -1) {
            alert(inputValue + " squared is " +
                 (inputValue * inputValue))
            inputValue = prompt("please enter a number, or -1 to stop")

    3.2.6 Counter Control loops - for statement

    A Counter Control loop is a loop that runs a fixed number of times based on an input variable. The schema for a counter control loop is the following:

    Program 44 - Schema for a Counter Control loop
    Initialize the counter
    Check the counter for ending value
        Process the data for this value of the counter
        Increment the counter value
    End of loop

    Because three steps (initialization, check, and incrementing a counter) in the Counter Control Schema always occur, they are included in many languages using a for statement. The for statement in many languages implements these three steps as follows:

    Program 45 - Translating a Counter Control loop into a for statement
    for (initialization; end condition check; increment) { 
        Process for each element;

    The following JavaScript program shows the implementation of a counter control loop19. In this plan, the user is asked for an input (n). The sum of all odd numbers from 1 to n is calculated and output using the alert() function.

    Note the use of the let keyword here to indicate the variable i is scoped to a local block and is thus local scoped in the for block. The variables total and inputValue are outside of any block and are global scoped.

    Program 46 - Implementation of a Counter Control loop
        let inputValue = prompt("please enter a number")
        let total = 0
        for (let i = 1; i <= inputValue; i = i + 2 ) {
            total = total + i;
        alert("The sum of odd numbers from 1 to " + inputValue + " is " + total);

    3.2. 7 Iterator loops – for/in and for/of for foreach statements

    An iterator is a looping structure that iterates over all of the members of an array. To understand an iterator, consider the weekDays array defined earlier.

    let weekDays = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]

    The members of this array could be printed out using a standard for loop as follows:

    Program 47 - Printing an array using a Counter Control loop
        let weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        for (let i = 0; i < weekDays.length; i++) { alert(weekDays[i])

    The for/in iterator allows the weekDays array to be processed in a simpler syntax. The for/in equivalent to the Program 47 is shown in Program 48. The value x is set to the index of the first member in the array, and the iterator sets x to the next array index until all members of the array are processed. Note that the implementation of a for/in loop seems strange but will become apparent later when the true nature of arrays in JavaScript is covered.

    Program 48 – Printing an arraying using a for/in iterator
        let weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        for (let x in weekDays) {

    JavaScript also has a for/of statement, which is an iterator that iterates over the values in the array rather than the array indices. The following is an example of the for/of iterator:

    Program 49 - Printing an arraying using a for/of iterator
        let weekDays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        for (let day of weekDays) {

    3.2.8 Functional iterator – forEach

    There is one other type of iterator, the forEach iterator. This iterator is executed by providing a function to be called for each array member and illustrates how functional programming works. The forEach iterator will be covered at the end of the chapter after functions have been covered and will be used to introduce the reader to Lambda Functions in Functional Programming.

    3.2.9 Functions

    Functions in JavaScript are similar to methods in Java or C#, or functions in C. They are used to abstract behavior. Functions are declared using the function statement, followed by the name of the function, an open parenthesis, arguments to the function, a close parenthesis, and a block which contains the body of the function. For example, a function which takes two input value distance and time, and returns the speed would look as follows:

    Program 50 - Implementatiton of the speed function
        function speed(distance, time) {
            return distance / time;

    Functions represent metadata as they provide some abstracted behavior to be used by data from the web page, and so the function definitions are generally found in the head of a document. Calling functions is part of the information on the web page and occurs in the body of the document. The following is an example of a web page that prompts the user for values of distance and time and prints out the speed. The program exits when a value of “-1” is entered for the distance.

    Program 51 - Sentinel Control loop program using a function to calculate speed.
            <title>Speed web page.</title>
                function speed(distance, time) {
                    return distance / time;
                let d = prompt("Enter the distance, -1 to end")
                while (d != -1) {
                    let t = prompt("Enter the time to travel the distance")
                    alert(d / t);
                    d = prompt("Enter the distance, or -1 to end")

    3.2.10 Quick Check

    1. What is the purpose of the let keyword in JavaScript?
    2. How is the type of a variable determined?
    3. What datatypes exist in JavaScript?
    4. What is an undefined variable? How does it differ from a null variable?
    5. What types of scoping are available in JavaScript? What is the default scope of a variable?
    6. What 3 types of control structures are needed to create programs? Give an example of each in a language you are familiar with.
    7. What three looping types exist in most programming languages? Give an example of each type in a language you are familiar with.
    8. True or false: All operators (including the assignment (=) operator) return values.
    9. What is short-circuiting of a logical operator? Show how this can be used to protect a program from a zero divide.
    10. Do operators return values?
    11. What is the result of operators returning values for condition variables for if, while, or for loops.
    12. The text said an if condition can have a null statement. What is a null statement? Why is it a bane to novice programmers? Why does JavaScript allow null statements?
    13. Can a for or while condition have a null statement?
    14. Does using the comparison operator (==) work for strings in Java/C#/C++/Python?
    15. Functions are said to have “positional parameters” in JavaScript. What is the difference between a positional and a keyword parameter?
    16. Do functions always return a value? What do you think is returned if nothing is specified?
    17. In your own words, explain what is meant that “functions are data” in JavaScript. This is used to defined Lambda functions. If you are familiar with Lambda functions in Java, are Lambda functions in Java really data? If not, what are they?
    18. What happens if you write the following code: specifically, does it work, and if it does, what is the length of the people array? What is the value of people [0]? What is the value of people [5]?
      let people = Array(2);
      people(1) = “Nick”
      people(2) = “Ann”
      people(7) = “Carol”

    13 For more information on JavaScript primitive, see US/docs/Web/JavaScript/Data_structures.

    14 For more information on IEEE 754 double format, see point_format.

    15 This syntax difference in array initialization represents more than just a small syntax difference. It is the first hint that an array and an array variable are semantically different in JavaScript than in other languages.

    16 Note that the Array() function is a JavaScript constructor function. The use of the constructor function requires the new operator and creates a JavaScript object. JavaScript objects, and the prototypes used to create them, will be covered in more detail later. For readers interested in more information, there are many web sites that cover Java objects, such as

    17 An iterator is implemented in Java as an extended for loop, but the syntax for these differ widely in different languages.

    18 A schema is “a representation of a plan or theory in the form of an outline or model”, The term schema and plan will generally be used in this text to discuss such structures, where schema is used to talk about the model what is to be done, and a plan is the implementation of a program structure. Experienced programmers have learned and internalized a large number of these schemas and tend to see programs less in terms of how the code progresses, but the schemas needed to solve a problem.

    19 This schema is really a more complicated schema to calculate a sum of numbers, however it contains a counting loop schema.

    This page titled 3.2: Primer on JavaScript is shared under a CC BY license and was authored, remixed, and/or curated by Charles W. Kann III.

    • Was this article helpful?