"Hello" JavaScript | Programming Fundamentals

Learn to program with JavaScript

Rick Hernandez

This book is for sale at http://leanpub.com/hello-javascript-programming-fundamentals

This version was published on 2016-02-26

*   *   *   *   *

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

*   *   *   *   *

© 2016 Rick Hernandez

Table of Contents

Preface

Introduction

Programming The Easy Way

Development Environment

The Art and Science of Programming

The Art of Programming

The Science Programming

Enter the Programmers Mindset

Challenge

Expressive Programming

Key Programming Concepts

Flow Charts

Pseudo Code

Programming Challenge

JavaScript from Scratch

Sugar Syntax

Console

Variables

Data Types

Math & Logical Expressions

Control Structure

Loops and Iteration

Arrays

Programming Challenge

Beyond the Basics

Functions and Scope

Objects

Strings

Data Structures

Numbers

Dates

Regular Expressions

Congratulations

Guide

Begin Reading

Preface

I want to take this time to say thank you and congratulate you for taking the first step to becoming a programmer.

Created specifically for new programmers, with no programming experience. This is a true Step by Step book where you will learn the programming fundamentals with JavaScript.

This is the book that will finally show you how you can start to program with JavaScript, not only will you learn the fundamentals of programming but you will obtain the skills necessary to be able to transfer those skills to any programming language.

This book is not just about JavaScript; it’s about the programming fundamentals that are required by every programming language. You will learn more than just programming with JavaScript. After you complete this book, you will have the skills and the confidence to start and complete real world software applications.

We will not focus on showing you code that you will copy and paste and then consider yourself a programmer. NO! We will look into the Programming Fundamentals, The Art and Science of Programming, The Programmers Mindset, Key Programming Concepts and over 35+ Unique Programming Challenges. Yes there will be practical steps for you to follow, but the book completely avoids the “type this and it’ll work” style that most programming books use.

The Programming Fundamentals covers the following topics:

Mindset (Art of programming, Science of Programming, Programmers)

Flow Charts

Pseudo Code

JavaScript Syntax

Executing code with the Console

Variables

Data Types (Primitive, Composites)

Basic Math Operators

Logical Constructs and Expressions

Control Structures

Loops and Iteration

Arrays

35+ Programming Challenges

This book is not for you to passively read; it’s specifically designed to make you think!

The last chapter of the book introduces advance topics such as:

Introduction to Functions

Function Composition

Recursion

Introduction to object Oriented Programming

String Mutations

Simple Data Structures

Advance Number Properties

Introduction to Date Objects

Introduction to Regular Expressions

Once you get through the book you will have the mindset of a true programmer. You will be able to quickly navigate the world of frameworks, learn new programming languages, and get one step closer to creating the next great app.

Introduction

About the Author

[picture]

Rick H

Rick Hernandez works as a software developer with small to mid-size companies. He has been responsible for evaluating business requests to determine feasibility, identifying options, and recommend solutions for software development enhancements. He has assisted with interpreting customer requirements into conceptual design specifications, and has developed interfaces/prototypes and maintained software solutions. He also has written over 300+ technical publications published at Code With Intent. Rick has a deep passion and curiosity to help others succeed.

Say Hello

My intention with this book is to get you up and running with JavaScript and cover material that applies to all types of problems that you might encounter in your programming career. If for whatever reason you might have a question, comment, or suggestion about the book, I encourage you to take the time and write into Code With Intent.

Who Is This Book For?

The purpose of this book is to help you learn to program using JavaScript. While learning to program with JavaScript we will explore other questions such as:

“Do you really want to be a programmer?”

“How do you overcome frustrations when learning to program?”

“How do you solve any programming problem?”

“How do you easily learn any programming language?”

However, I assure you that if you have perseverance, creativity, and dedication to finishing this book, you will be off to starting your career as a programmer. It will not be easy, and at times you might feel like giving up, but DON’T! Stick with it and you will see your skills as a programmer increase, as well as your salary.

Programming is not for everyone, although the media might have you thinking that becoming a programmer is a 21st century skill. Don’t let this fool you, as programming is a skill that needs to be practiced and used, not just learned. You see programs are not just for the machine to use, but they are for other human beings to use in order to solve the problems that they have. If you decide to become a professional programmer, I suggest that you do it with the intention of making it a skill, which you will work on over time to progress and improve because it’s truly something that you enjoy, not just something you are doing to get a bigger salary.

I promise that after studying this material, you will never think about solving problems in the same way again.

Prerequisites

Before getting started with this book, you need to have a clear understanding of the following concepts to enable you to be successful with this book:

UNIX Philosophy

Basic command line experience

High School Algebra

If for whatever reason you are not completely comfortable with the above requirements, I have provided some resources for you to get you going before getting started with this book.

Bash Basics

The UNIX Operating System

Khan Academy

Code Samples

The book contains a variety of code samples and snippets that are used to illustrate a specific part of the book. Although each of the code sample concepts do play a role in the programming “challenge”, they are not used directly on those challenges. This means that the book does not rely on those specific parts of the code.

This will allow you to quickly reuse some of the snippets without having them tied to a single specific project.

All of the snippets used throughout the book are released under the MIT License. You are free to fork any part of the code and use it for your own applications.

The complete list of the snippets can be found on Github.

Code Conventions

Throughout this book, I will be using a derivative of the Felix coding style.

Tips Conventions

Pro Tip

Pro Tips contain information that is well established within the professional development group of programmers.

Suggestion

A suggestion is an opinionated or suggestive comment toward a specific topic.

Warning

Warnings are well established problems or common errors.

Programming The Easy Way

This book is not just about JavaScript; it’s about the programming fundamentals that are required by every programming language. You will learn more than just programming with JavaScript. After you complete this book, you will have the skills to solve useful real world problems with JavaScript. In order to achieve this, we will not be focusing on using the web browser (HTML/CSS). Instead we will be focusing on the problems at hand and use JavaScript to solve those problems.

“More than just copying and pasting code” - Rick Hernandez.

This book will not focus on showing you code that you will copy and paste and then consider yourself a programmer. NO! we will look into the programming fundamentals, the art and science of programming the programmers mindset, and so much more. Yes there will be practical steps for you to follow, but we will completely avoid the “type this and it’ll work” style that most programming books use.

This book is not for you to passively read; it’s specifically designed to make you think! I don’t just want you to follow my instructions; I want you to challenge those instructions.

Once you get through the book you will have the mindset of a true programmer. You will be able to quickly navigate the world of frameworks, learn new programming languages, and get one step closer to creating the next great app.

JSecademy.com 30 Day Free Subscription

Deciding to take advantage of the 30 day subscription period of JSecademy is a great decision. Not only will you get step by step videos walking you through the entire book, you will also receive help from a community of people wanting to learn more about JavaScript and software development. To get started, follow the simple steps below.

Sign up for JSecademy

Redeem Your Promotion

Enjoy a 30 Day Subscription

What is a Transaction ID? Depending on where you purchased this copy of the book, e.g., Amazon, Leanpub, etc., you should have received an order number. This is the Transaction ID. Transaction ID’s typically take 24-48 hours to validate. Get started with this right away

Happy Learning

Programming Workflow

For the sake of keeping the examples short, I will not be using the browser to run any of the code. Instead, I will be focusing on the actual problem and running the solution with Node.js. This will allow us to quickly test code and verify that it is working accordingly so that we can avoid HTML and CSS completely. The work flow for this is a simple and easy one to follow.

[picture]

Workflow

Write the code in a file with an extension of .js, e.g., app.js.

Let Node.js know about your file by executing it.

Code Example

1 node app.js

Node.js will terminate after your script has completed executing.

Development Environment

Setting Up Your Development Environment

The development environment that you decide to work on will dictate a large portion of your overall happiness as a programmer. Choosing the right platform and the right text editor could be one of the reasons why you choose to keep working as a programmer or decide to move on to the next great thing. The right choice will vary with everyone’s circumstances as it is based on your current needs and budget.

Before getting started with this book please complete the following series.

“Hello” Environments | Learn Modern Development Environments

Throughout this series, you will learn the in’s and out’s of multiple development environments, text editors (Vi, Vim, Atom, Sublime, Brackets), understand how to work with local, virtual and private clouds (VirtualBox, Vagrant, Cloud9), you will also learn how to automate the most common task using the command line. But most importantly you will have a good understanding of what to look for when you are creating your “ideal” development environment.

If it’s not clear by this point, the following are also required in order to run the software that will allow us to program using JavaScript.

Operating System: Windows, Linux, or OSX

Hardware: a minimum of 2GB of free memory and 4GB of free Hard Drive space

Internet Connection

Modern Web Browser: (Chrome, Firefox, or Internet Explorer)

That’s all! Power up your laptop, desktop, tablet, or phone and let’s get started learning to program with JavaScript.

The Art and Science of Programming

Computing is changing; prices of computers are going lower and lower every single year. This is due to Moore’s law, which says:

Over the history of computing hardware, the number of transistors in a dense integrated circuit has doubled approximately every two years. src

Which has allowed programmers like your self to develop applications that expand millions of lines of code, with teams created all across the world. In fact some programs are so large that not one single person can comprehend everything that is going on.

So what, exactly, is programming? Programming is the process of giving the computer detailed instructions to perform a specific task. What type of tasks? Anything from computing a natural number to creating the next great game. Who, exactly, gives these commands? Those are called programmers. They are responsible for creating instructions that the computer can understand. What type of instructions? This can vary from an implementation of an algorithm to custom definitions that the programmer decides to create. What are algorithms? Algorithms are a sequence of instructions that you follow for a certain outcome. The outcome can be figuring out a problem or just carrying out a procedure. Algorithms can be simple or complex.

That’s great, but what do transistors have to do with software and JavaScript? Everything! JavaScript was once a small language that was only used in browsers to provide interactivity for web pages. This was one of the main reasons programmers did not consider JavaScript to be a complete programming language. All of this has since changed. You see, JavaScript can be found in Robotics, Real Time Systems, Banking, Internet of Things, Web Browsers, Mobile Applications, Server Applications, Custom Command Line Tools, and even Text Editors. JavaScript is no longer just a web browser language; it’s actually “THE” language to know.

When exploring a new programming language such as JavaScript, it’s always a good idea to take a look around and see what others are doing with the same language. Githut provides a visual of the complexity of programming languages across 2 million active repositories hosted on GitHub. The number one most active language is JavaScript with Java not falling far behind; making programmers with a background in JavaScript in high demand. This is great news for you!

Where is the art and science? In this chapter, we will be exploring how programmers have to be creative, intuitive, and most importantly persistent in order to solve a problem. What type of problems? We will explore how problems are translated from a verbal conversation to a formal document, and then to actual code. I will provide you with a framework that you can follow to solve any type of problem. The science of programming will help you narrow down your options for a solution, and the art of programming will help you to choose a beautiful solution.

The Art of Programming

“I can’t define it, but I know it when I see it.”

If you hold up a flower and take a look at the flower, you will say “what a beautiful flower”. A painter might take that flower and put it into a painting, a biologist can take the flower and take a look at the cells of the flower. A programmer can take that very same flower and create a program to model the structure of the flower, examine it and understand its process of the flower. You see, programming can help you explore the real world around you, or it can help you create new worlds that you might imagine. There is no limit unless you strictly put it there.

Programming is more than just the lines of code that you write; programming gives you the ability to take an idea you have and quickly bring it to reality. That could be a mobile application or an elegant algorithm. Whatever the case may be, you will have to be creative and use your artistic taste to find a beautiful solution.

The true art of computer programming is being able to understand the problem at hand and coming up with a solution. Just like problems in the real world, computer problems have more than one solution. It’s your job as a programmer to be able to navigate this world of solutions and find the most elegant solution that you can find.

Programming requires the use of Art, Science, and Engineering. Later in this book we will be taking a closer look at the “sugar syntax” and we will explore different parts of programming where you will have to be creative.

What type of creativity? Take for example some of the choices programmers have to consider when designing a program.

The structure and layout

Design decisions on the type of code convention to use

Deciding on an algorithm to use

The Science Programming

What if I told you I can show you a framework that can solve just about any problem that you might encounter? Does that even sound possible? What if it is? What do you think it would look like? Could you guess how this framework might look or be? How can we test the framework to see if we have achieved success?

If you noticed from the above sentence, I’m clearly applying such a framework to find the framework. Here it is the Scientific Method, which has taken us across the ocean, across different medical breakthroughs, across multiple species, into outer space, and so much more.

Ask a question

State your assumptions

Conduct the experiment

Analyze results

Make a conclusion src

The Scientific Method will be necessary throughout your career as a programmer. It will help you in ways you never thought possible. For example, it can help you increase the speed of your program, eliminate errors, solve problems, avoid security failures, and most importantly, avoid looking at your text editor with a blank stare.

Throughout the book we will be using this method to solve all types of problems. But first, let’s take a closer look at each of the steps.

1. Ask a question

The question that you decide to ask will determine the entire process. Make sure that you take the time to clearly state the question, and avoid answering multiple questions at the same time. Focus on just one question then move on to the next one.

2. State your assumptions

Now that you have clearly stated your question, come up with some assumptions. What do you think will happen? Why would that happen? More than likely you will come up with multiple assumptions. Some of them might be wrong, but eventually you will find the right answer. Here is where you are encouraged to use your creativity. Now that you have all your assumptions, it’s time to predict what will happen in your experiment. Write this down, it’s important for the next step.

3. Conduct the experiment

What do you expect to happen? Actually sit down and conduct the experiment. This would include writing code, editing existing code, or going back to step one for more information.

4. Analyze results

Having implemented the experiment it’s time to reflect on the reasons why it was a success or a complete failure. Your interpreter Node.js will either throw an error or report the results back to you. Take the time and understand why you got the results that you did. Was it what you’re expecting? What assumption failed? Will you need to create another experiment?

5. Make a conclusion

Now that you have analyzed the results from your experiment, you are ready to make a conclusion about the results. Will you need to recreate the experiment again? What went wrong? What can you definitely say is true? Depending on how many times you have gone through the above steps, this will become second nature to you when programming.

Using the Scientific Method will advance you leaps and bounds beyond the common programmer. You will never have to copy and paste another line of code from the internet again. You can say goodbye to trying to make a program work, and say “hello” to a working program every single time.

Enter the Programmers Mindset

Learning anything new is a challenge, especially computer programming. As with any good thing in life, it takes training and practice with a long commitment to follow through. This includes changing the way you think about your current world. Why? Because you will have to push yourself to be more creative in order to think about new ways to solve problems.

Most computers can’t understand or comprehend any human languages like English or Spanish. This is both an advantage and a disadvantage. Computers don’t care about your feelings; they can’t read in-between the lines. The sooner you come to this understanding, the closer you will be to knowing the “Mindset” of a true programmer.

As you may know at this point, computers don’t think like you and I. Computer programs must have a high level of detail and precision when trying to carry out a solution to a problem. That means you must be able to give those exact instructions without a single miss. Don’t worry. There are plenty of tools that we will use to make this process easier. Take the following list as an example:

Designing - The act of creating a plan for the construction of a program.

Testing - The process of measuring quality, performance, and reliability of a program.

Debugging - Finding and removing errors from a program.

I don’t want you to be just a programmer; I want you to be a GREAT programmer. We will get to that goal by understanding the problems in front of us and translating them into something the computer can understand. The tools that we use to accomplish this will be the Scientific Method along with your design skills. Soon enough you will be off to creating amazing programs.

The rest of this book is dedicated to helping you learn how to think like a computer, be more of a creative problem solver, and learn to love or hate programming.

Challenge

Now that you know programming is more than just “working with computers”, I want to give you a taste of what you’re getting into so that you’re prepared. Some of the general ideas that float around the programming community are “you are a programmer” or “you’re simply not”. Due to these types of ideas floating around a lot of new programmers tend to be turned off, and one can see why. Let me be the one to tell you that programming is not easy, and if you find someone that tells you that programming is the easiest thing in the world, that doesn’t make them an expert.

An expert is a person who has made all the mistakes that can be made in a very narrow field ―Niels Bohr

Let’s take a closer look at “What is Programming?” The entire point of programming is to tell a computer what to do. So it comes down to: can you command your computer to do your bidding? Here is where the ego comes into play. YES!

Male Human - “oh computer make me cup of coffee”

Computer – “Coming right up sire”.

This cannot be stressed enough. If you are not good at giving commands in the real world then programming is going to be even more of a challenge to get started with. This is where being bossy really pays off! However, as a programmer it’s better to call it “attention to details”.

Programming is time-consuming! There is no way of getting out of it. The best example that I can think of is related to that of a math problem or writing a novel. Some parts of programming can take hours on hours to figure out and, to add onto this entire thing, the problem could end up being a single missing semicolon. It is just like spending hours on a tedious math problem and getting the wrong answer because one of the signs got messed up along the way. Be ready to spend hours in front of a text editor trying to figure out a solution.

Needless to say, it will take courage, persistence, and most importantly determination in order to become a programmer. It’s not just a big salary.

Figuring out if programing is for you. “You get it” or “you don’t”. Deciding to make programming your career requires a large shift in thinking, both in what has been done in the past and what will be done in the future. This is why older people tend to have a larger learning curve when learning to program. “But I have always done X!” If you are shifting from your current profession to programming, letting go of X can be challenging, but it must be done before something new (programming) can become a reality.

Once that barrier is removed, go over and take a personality test. This is just a rule of thumb, and it should give you a bit of a window into the type of personality you have. This is a good idea because if the personality that you have does not match with that of a programmer, an inner conflict will arise. This step is important, so don’t skip it.

What to do if my personality is not of a programmer? Don’t give up! If the role you carry is that of a project manager, or a CEO and understanding programming is a vital part to what you do. Then the sacrifice must be made (consuming resources) take a deep breath and get ready to learn an amazing way of thinking.

I have what it takes! If you fall into this bucket, then you are extremely young (7-13 years old) or you are a veteran in a profession that requires the same traits as a programmer, giving you a leg up on everyone else. These types of careers are musicians, mathematicians, scientists, or other strongly analytical professions. In the other case of a young programmer (7-13 years old), then you are in great shape to start learning programming.

Have fun! A programming career can be one of the most rewarding, fun accomplishments that you undertake in your lifetime. So have fun! Don’t take every single project too seriously; joke around. Break your code, fix it, fork off to different possibilities, improve your tools, but most importantly CODE.

Expressive Programming

In this Chapter we will take a look at some key concepts of programming. To avoid any confusion, we will not be covering any JavaScript. Instead, we are going to be focusing on some key concepts that you must first understand before moving on to JavaScript. This will give us the ability to focus on the fundamental concepts involved in programming rather than the details and nuance of JavaScript. Once you grasp these essential building blocks, learning a new language will become a simple exercise that you can complete in a matter of hours.

Programming Challenges: Practice makes perfect, at the end of this chapter you will find a series of challenges. You MUST complete all of these programming challenges before moving on to the next chapter. I want to stress the importance of practicing and using the programming tools and techniques covered in each of the sections.

Key Programming Concepts

Statements

In programming, a statement is a meaningful declarative sentence that is used to describe what a program will be doing.

Source Code

A text file containing valid programming statements.

Code Execution

[picture]

Execution

When your programs become larger than one statement, the statements are executed from left to right, top to bottom. In more complex programs you can stop execution, jump to another file, continue execution there, then return back to the file and continue on with the program.

Syntax

Syntax is the sets of rules that a programming language sets. The rules combine symbols and formatting to define the legal structure of a computer program.

For example, in the Spanish language, you have grammar that you must specifically follow, one example of this is when you add an “o” to a word to denote male, and an “a” to denote a female.

Example:

“Chica” : a girl or young woman.

“Chico” : a boy or young man.

Once you have a clear understanding of one programming language, you will be able to create programs that are valid for a specific language. Just like speaking English, you can take the knowledge you know over to another language such as Spanish.

Variables

Variables allow us to associate a value to a name. These values are stored in memory and are accessible through the name of the variable.

Example:

1 age = 21

The variable age holds the value 21. Throughout your program that value can change or remain the same.

Where Do Variables Live? Variables are stored in memory. You can think of computer memory as a collection of places for holding information. Computers have different type of memory: cache memory, video memory, and RAM (random access memory). Your programs will typically use free RAM memory.

[picture]

memory

Variable Scopes

A variable’s scope is a section of a program where that variable exists. You can have two types of variable scopes: local, or global.

[picture]

Scope

Operators

Operators are used for helping you work with variables. There are comparison operators, logical operators, assignment operators, and arithmetic operators.

Comparison Operators: A comparison operator is a binary operator (true or false value) that takes two operands whose values are compared.

Operator | Description
== | Equal to
!= | Not equal
> | Greater than
>= | Greater than or equal to
< | Less than
<= | Less than or equal to

Logical Operators: A programming symbol that is used as a logical operation.

Operator | Description
&& | and
|| || | or
! | Not

Assignment Operators: In programming, the assignment operator ‘=’ is the operator used for assignment. The assignment operator assigns the value from the right side of the operator to the left side of the operator.

Operator | Description
= | assignment

New programmers tend to get confused with the assignment operator and the equality operator, remember that programming is NOT math.

[picture]

assignment

Arithmetic Operators: Arithmetic operators are used when you need to operate with one or more values. Each of these operators is executed according to the order of operations in math.

Operator | Description
+ | Addition
- | Subtraction
* | Multiplication
/ | Division

Expressions

An expression is a group of variables and operators grouped together to evaluate to a value.

Example:

1 x = 3 + 5

Comments

Comments are used to make annotations to a specific part of a code.

Counters

Counters are a type of variable, just like variables they are stored and used based on a location in memory. Counters typically change their value through out a program to count a value.

Accumulators

Accumulators are a type of variable. Just like variables, they are stored and used based on a location in memory. Accumulators differ from counters by accumulating a value instead of counting that value.

For example, you can have an accumulator that finds the sum of an order and a counter to count the items they purchased.

Inputs

Most programs will need some type of input to operate on. Whether it’s setting up the initial value or asking a user for a specific input, your program will likely require some type of input.

Outputs

Anytime a computer reports back to a user with a result. There are many different types of outputs including, but not limited to, output to a file, a printer, the web, binary files, a screen, or another device.

Decisions

[picture]

Decisions

Most interesting programs will need to make a decision. What type of decision? A computer has the ability to make decisions based on a boolean expression. This can be based on a logical operator or an expression that evaluates to true or false.

Example of a decision statement

1 if <some condition is true>
2   Do this
3 else
4   Do this

With a conditional execution you can control the flow of the program.

Start

All programs must start at one point. The starting point of a program is where you decide your program will start executing.

Stop

Stop is where you decide to terminate your program. At times, this stopping point can be decided by you, but other times it will be determined by parts of your code.

Loops

Loops represent the concept of repeating a process over and over again. Constructing loops is one of the core parts of a program. A loop’s condition must evaluate to true or false. If the loop’s condition is true, the loop will continue to execute until it becomes false. If a loop never evaluates to false, it will turn into an infinite loop that will continue forever. Since loops can fall into this problem of looping forever, there are certain keywords that can help you decide to keep looping or to stop.

Break A break can be used to terminate a loop.

Continue A continue is used to keep a loop iterating.

Computers love to be in loops, and later in your studies you will find out that loops compose a large part of all programs. Start getting comfortable with the idea of a loop.

[picture]

Loop

Naming Conventions

JavaScript does not have any specific rules for naming variables; however, other languages do. Naming conventions help your code stay fluent within the context of your program. This is important because you want to have consistency throughout your entire program. Below you will find general rules when naming your variables.

Variables tend to start with a letter.

Spaces are not allowed in variables

Special characters such as “!,-,@” are not allowed in the name

Digits are allowed but keep Rule number 1 in mind.

Example of valid names

1 user
2 total
3 output
4 results

Example of invalid names

1 Becky Johnson
2 output!
3 12Users
4 first-name

Variable names should clearly express how the variable is going to be used. For example, the following names are valid but not typically a good idea to use:

1 tuna = 32
2 TheResultsFromACalculationWithALongName = ((32 + x) / 5)

Debugging

Finding mistakes in your program can be a very difficult task, and at times you might feel like you just can’t solve the problem (Scientific Method is one your tools, don’t forget it). In many cases, finding the bug can become the job itself.

Data Types

Data types are a type of item that is defined by a programming language. Typically these are numbers, strings, objects, booleans, etc.

Arrays

[picture]

Arrays

An array is an ordered collection of data (either primitive or objects). Based on its place in the array, each data item has a numeric index through which you can access the corresponding value. In JavaScript, arrays are also objects that have their own properties.

Booleans

[picture]

Booleans

Booleans are used to represent a true or false value.

Summary

The list of concepts in this section composes nearly every computer program. Having a good understanding of these concepts will serve you well in your programming career.

Flow Charts

Now that we have a clear understanding of the building blocks of programming, it’s time to use a tool to express those ideas. Flowcharts help us to do exactly that! Flowcharts are used in many professions and different symbols can have a different meaning depending on the context.

Flowcharts will help us to better plan our programs from a high level or a low level implementation, detail of an algorithm, workflow, or a process. This is a vital tool for any programmer. Not only will it help you better understand the problem and solution that you have, but it will also help you document and communicate it to other team members. You will be a much happier programmer once the life cycle of your project comes to an end and you have a flow chart explaining exactly what your program is doing.

What exactly are flowcharts? Even though you might not know it, we use flow charts in our day to day lives, from traffic stops to workflows in a factory. The main parts of flow charts are a set of shapes (rectangles, parallelograms, rhombuses, etc) that are connected by a set of arrows. We will be using the following shapes and definitions to model our programs.

Process: Denotes a process or an action to be taken.

[picture]

Process

Preparation: Stores a preparation measure before defining a process.

[picture]

Preparation

Flow: Indicates the direction of a flow.

[picture]

Flow

Terminator: Represents the start, end, or return section.

[picture]

Terminator

Decision: Represents a decision being made.

[picture]

Decision

I/O | Input or Output: Represents data input or output from a process.

[picture]

Decision

Summary

Flowcharts are abstract entities that can be used in many different forms. Throughout the rest of the text, we will use these symbols to represent our programs. If you don’t yet know how to use these flowcharts, don’t worry. We will get plenty of examples once we start translating each one of them to actual JavaScript code.

Pseudo Code

Pseudo code is another form that can help us represent what a program is doing at a high-level. The main purpose of pseudo code is to have a human-readable representation of your program. Remember pseudo code is NOT a programming language. You will typically use pseudo code after you have diagramed your program using flowcharts. Pseudo code can be very different depending on who is writing it. The main goal of pseudo code is to clearly state your ideas.

Remember there is no formal predefined way to write pseudo code.

Process: In the example below, you can see that we are working with a three-variable program. The three variables are x,y,z and an addition operations is being executed on them.

1 x = 30
2 y = x + 1
3 z = x + y
4 <More Instructions>
5 <More Instructions>
6 <More Instructions>

Preparation: Preparation is simply initializing our variable to a set value.

1 name = 'Ferguson Jones'

Flow: In most programming language the flow of a program is from top to bottom. With pseudo code you would read it just like you would read a paragraph from left to right.

Indentation: Indentation is used to denote scope.

Decision

1 if <Condition is true>
2   <TRUE BRANCH>
3 else
4   <FALSE BRANCH>

Loops

1 while <Condition is TRUE>
2   <TRUE BRANCH>
3
4 for each <item in collection>
5   <item in collection>

Example of Pseudo Code to find the largest number

1 listOfNumbers = 1,2,3,4
2 for each number in listOfNumbers
3   if max is defined
4     if max < number
5       max = number
6   else
7     max = number
8 display max

Again, don’t get to hung up on the syntax of pseudo code. Use it as a tool to model your programs. Take, for example, the following program:

1 start the program
2 Find the last 10 people that entered the building
3 If no one has entered the building today
4   Terminate program
5 otherwise email each of the individuals and let them know about any cafeteria sp\
6 ecials
7 Terminate

From the pseudo code you can tell that this program will be emailing the cafeteria specials to the first 10 people that have entered the building. Pretty handy, right? It’s a simple program that almost anyone can read, and that’s the entire purpose of using pseudo code to model a solution to a problem.

Programming Challenge

The purpose of this section is to provide you some hands-on practice in order to learn to use flowcharts and pseudo code. The challenges are sorted from easiest to most difficult. Each of the challenges comes with the solution. Try your best to solve the challenges before taking a look at the solution.

Warning

If you decide to look at the solution before attempting to solve the problem yourself, you will NOT learn to program.

I don’t want you looking at the answer and say “Oh that’s easy, anyone can do that.” If you really think anyone can do it, I challenge you to get started with the problem set.

What symbol do you use to start and stop a program?

View Solution

What symbol is used to gather an input? What about output?

View Solution

What symbol do you use to represent a process?

View Solution

How many outputs can a decision symbol have? What are they?

View Solution

Draw a complete flowchart program to ask a user for a number, display the number on the screen and all the numbers from 1 up to the numbered entered by the user.

View Solution

Draw a complete flowchart program to determine the sales tax of any items price at 8.2%.

View Solution

Create a Flowchart or Pseudo Code to output the sum of all the numbers up to the number given. Example: User provides 4 as the input output would be 1+2+3+4=10

View Solution

Create a Flowchart or Pseudo Code to output the power of a given number. Example: User provides 3 as the base and 2 as the power 3*3=9

View Solution

Create a Flowchart or Pseudo Code to output the factorial of any given number. Example: User provides 3 which is 3*2*1=6

View Solution

Create a Flowchart or Pseudo Code to sort a list of numbers in ascending order Example: User provides the 12,23,1,13,7,12 the result is 1,7,12,12,13,23

View Solution

Create a Flowchart or Pseudo Code to sort a list of numbers in descending order Example: User provides the 12,23,1,13,7,12 the result is 23,13,12,12,7,1

View Solution

Create a Flowchart or Pseudo Code to find the largest number and display it to the user. Example: User provides the 12,23,1,13,7,12 the result is 23

View Solution

Create a Flowchart or Pseudo Code to find the smallest number and display it to the user. Example: User provides the 12,23,1,13,7,12 the result is 1

View Solution

Create a Flowchart or Pseudo Code to display the fibonacci sequence. The Fibonacci sequence is a sequence of numbers that can be determined by simply adding the previous two numbers of the sequence together to generate the next number. Example: The fibonacci sequence 1,1,2,3,5,8,13,21,34

View Solution

Becky is an event manager. Her job is to plan, manage, create, and promote large events such as music festivals, conferences, ceremonies, parties, or conventions all across the world. She has a particular problem: she would like to know how many people attend an event, preferably by email, since all her events are free and don’t require anyone to sign in or pay any amount of money. She mentions this problem to you. You suggested to her that you could create an application that would count how many people entered the venue. She is ecstatic to hear that you could help her. Can you model a solution to Becky’s problem?

View Solution

Now that you’re getting a taste of what programming is all about, I want to emphasize how important the following concepts are for any programmer.

You must thoroughly understand a problem before attempting to solve it.

You must be able to translate your proposed solution into a program the computer can understand.

In the next chapter we will be taking a closer look into the translation of our programs into JavaScript code.

JavaScript from Scratch

[picture]

JavaScript from Scratch

I think everyone should learn how to program a computer, because it teaches you how to think. I view computer science as a liberal art, something everyone should learn to do. - Steve Jobs

Congratulations! At this point you should be fairly comfortable with creating a program using flow charts or pseudo code. Unfortunately, JavaScript does not convert flowcharts or pseudo code to actual code. Maybe it will sometime in the future. Don’t worry. The skills that you picked up in the last chapter can be carried on to any language. In this chapter, we will be taking a look at how we can implement those programming fundamentals specifically in JavaScript.

From this section you should expect a translation of all the flowcharts and pseudo code covered in the previous section.

At the end of the chapter you will be required to solve another problem set, but this time flowcharts and pseudo code won’t be good enough. They can be used, but the end solution must be valid, executable code.

What exactly is JavaScript?

JavaScript, also known as ECMAScript, is a cross-platform, multi-paradigm, dynamic programming language. It is a small and lightweight language. JavaScript can be connected to the objects of its host environment to asynchronously provide programmatic control over them.

JavaScript is NOT Java. If you later decide to move on to program with Java, you can take with you the concepts that you learned in the Expressive Programming chapter.

The programming language JavaScript was originally designed and created in 10 days on May 1995 by Brendan Eich. The language was created to run on a browser named Netscape, later renamed Mozilla. The purpose of the language was to allow new programmers to easily create new programs, making JavaScript a very fluid and easy language to get started programming with.

What is ECMAScript? ECMA(European Computer Manufacturers Association) is a non-profit organization that originally created the standard specification for ECMAScript. JavaScript is an implementation of that standard.

What is ActionScript 3? ActionScript 3 is an implementation of the ECMAScript standard. Although the language itself is used to develop software applications for Adobe Flash Player, it resembles that of JavaScript.

What about ES6? ES6, also known as ECMAScript 6, is another iteration of the ECMAScript standard that provides a much simpler and clearer syntax. As of this writing, ES6 is released but not yet supported across all platforms. ES5 is what’s used throughout this book. ES6 has full backward support for ES5.

Examples use cases of JavaScript

Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.

Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation of the application to another, or perform file manipulations on a server.

JavaScript is entering a completely new and exciting cycle of evolution, innovation, and standardization. With new developments in platforms such as Node.js, we can now use JavaScript on the server-side and HTML5 APIs to control user media, open up web sockets for always-on communication, get data on geographical location and device features such as accelerometer, and so much more. It is an exciting time to learn JavaScript!

Let’s start making the computer answer all of our commands

Sugar Syntax

Every programming language needs a specific syntax, and JavaScript is no exception to this. Syntax can be thought of as the punctuation and grammar of the actual statements being written. Just like written languages, this can be a highly opinionated subject, but I will try my absolute best to show you examples of what you will encounter in your career as a JavaScript programmer.

JavaScript is very forgiving in the syntactic correctness of your statements, but don’t take this too lightly. Other programmers will be reading your code, so it’s best to be as clear as possible. You can have a perfectly syntactic, valid program and it still not work the way you want it to. This is due to not having the right semantics. You will soon find out that it’s easy to create syntactic, valid programs but not semantic programs.

Case Sensitive

JavaScript’s interpreter can distinguish between uppercase and lowercase letters. Typically what you will find in most programs is camel-cased variables, functions, and classes.

Comments

Code comments are a valuable tool that you can use to make your code more readable and understandable in certain cases. Comments are great, but you should give your code the ability to speak for itself, meaning that comments should only be used when you know exactly what message you want to deliver to the reader, another human being. Some situations where comments might be useful could include specific cases, documentation for a piece of code, or explaining complex logic. Documentation needs to be written at a higher level of abstraction that communicates to the reader the intention of the code and what post- and pre-conditions are expected when executing that specific part of the code.

Single-Line Comment: Single line comments start with // and end at the line break.

Code Example

1 // The code below shows a single line of code with a comment
2 'one line comment'; // This entire line will be ignored

Multi-Line Comment: Multiple line comments, start with /* and end with */.

Code Example

1 /*
2     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non diam ante.
3     Phasellus at quam vitae sapien porta egestas vel eu lorem.
4     Duis viverra lectus eget nisi placerat, et scelerisque felis suscipit.
5     Morbi faucibus eu urna ut laoreet. Nullam condimentum rutrum sem.
6     Hendrerit accumsan sed vitae ante.
7 */

In-Line Comment: Having a comment with in a line of code can be useful at times.

Code Example

1 (10 % /* Even Number */ 2 == 0);

TODO: As a new programmer you might encounter a TODO:, in this book or in a piece of code from an online repository. The purpose of a TODO: is to create a task or set a reminder to improve the code in one way or another.

You will typically see it written in this form.

Code Example

1 // TODO: Improve this code
2 // ....
3 // ....
4 // ....

Code Example

1 // TODO: don't have any special purpose.
2 // You could easily use something else.
3 // By convention TODO: is what you will typically find.

Pro Tip

Some text editors support the ability to be able to quickly jump to a specific TODO: in a file.

Semicolons

Semicolons are optional in JavaScript. It’s considered best practice to have a semicolon after each statement. In later sections we will see how semicolons are used throughout a program.

Statements

Statements are multiple evaluations that are combined to create a program.

Code Example

1 (10 % /* Even Number */ 2 == 0);
2 32 + 72;
3 "Ferguson" + " " + "Jones";

This program does very little—it just evaluates multiple values. It does not display or affect anything else. If you wish to run the program, you will find that you end up with no output.

Special Tokens

JavaScript uses special characters that are reserved for creating source code. Below is a list of the most common symbols that you will encounter.

[picture]

Tokens

Don’t worry too much about exactly what each of these symbols do. We will explore this in a later section.

Representing Scope

Using flowcharts, we were able to represent scope by inserting a shape inside another shape. In JavaScript, we can do the exact same thing by using the open and close curly braces {}.

[picture]

Scope

Code Example

1 if(number > nextNumber){
2   // TODO: swap numbers
3 }

Again, don’t worry about the if statement. It’s covered in more detail in the Control Structures section. Make a note of the open and close curly braces {} . They represent the start and stop of the scope. Although JavaScript does not require them for a single line of code, it is best practice to add them because it keeps your code clear and concise.

Syntax Questions

Are indentations or white spaces required? Indentations are optional. You can use spaces, tabs, or nothing at all. Although it’s highly recommended that you have them in order to make sense of your program. In the examples that are provided in the book you will encounter indented code. The indentations are used to clarify scope, define different blocks of code, and have overall maintainable code.

Console

When programming in a specific environment, you will automatically inherit the abilities of that environment. The interpreter Node.js will provide you with the most common functionality that your program might need. Some abilities include getting input from a user, reading files, writing files, and displaying values on the screen, but that’s beyond this scope of this book.

One of the functionalities that Node.js provides is the ability to display a value on the screen. The way that Node.js does this is by invoking a function that is part of the Node.js API.

I/O | Input or Output: Represents data input or output from a process.

Flow Chart

[picture]

Output

Pseudo Code Example

1 name = ferguson
2 display the name

Code Example

1 var name = "Ferguson";
2 console.log(name);

From the example above you can see that we use a variable named console and then use the . notation to log the name. Don’t get too hung up on the syntax of how this is working. Just know that it works.

The console object differs from that of a regular variable by providing you with some new functionality. Here are a the most common uses of the console object:

Display Value

Code Example

1 var name = "Ferguson";
2 console.log(name); //Result -> Ferguson

Display Value with a string

Code Example

1 var name = "Ferguson";
2 console.log("Name:", name); //Result -> Name: Ferguson

You can keep adding variables to the console.log to keep displaying them, for N number of items.

Code Example

1 var name = "Ferguson";
2 var age = 21;
3 console.log("Name:", name, "Age:", age); //Result -> Name: Ferguson Age: 21

Don’t worry if all of this does not make perfect sense. Just know that you can now display the results of your program on the screen. In a later section we will explore in more detail how exactly console.log() works.

Variables

JavaScript is a loosely typed language. There is no need to explicitly declare the type of data that the variable will be holding. This means that, with JavaScript, a variable is a value that can change depending on the conditions that you set for it in your program. If you remember back to your algebra studies, a variable can hold any kind of value and that value can change depending on the conditions of the problem. The same applies to programming.

Variable Preparation: Stores a preparation measure before defining a process.

Flow Chart

[picture]

Preparation

Pseudo Code

1 name = "Becky"

JavaScript Code Translation

1 var name = "Becky";

Naming Conventions Naming conventions for variables are strict. They can be any word that does not start with a number or a special character except ($, _,.). When creating variable, name keep in mind the best practice covered in the Key Concepts section.

Case Sensitivity: Variables are case sensitive. For example, if you have two variables that are exactly the same word but have different cases, they are different variables.

Non-Space Sensitivity: Spaces do not matter in your programs. You typically only add spaces for readability. The Node.js interpreter does not care if you have spaces or not. There are even specific tools that you can use to remove all white spaces from your program to obtain a minified version.

JavaScript Code Sample

1 var name = "Becky";
2 var Name = "Robert";
3 console.log(name); //Result -> Becky
4 console.log(Name); //Result -> Robert

Semicolons

Semicolons are highly controversial. JavaScript is very flexible and forgiving in this manner.

JavaScript Code Sample

1 var firstName = 'Isabella' // BAD

The code is perfectly valid, but it’s always best to tell JavaScript when a statement ends by using the ; at the end of the statement.

JavaScript Code Sample

1 var firstName = 'Isabella'; // best practice

If you want to create two variables; for example, firstName and lastName, simply use two variables.

JavaScript Code Sample

1 // best practice
2 var firstName = 'Isabella';
3 var lastName = 'Ramirez';
4 /* OR */
5 var firstName = 'Isabella', // <---- use the comma to separate variable names
6     lastName = 'Ramirez';

Warning

New programers might tend to make the mistake of creating two variables on the same line.

JavaScript Code Sample

1 var firstName = 'Isabella' var lastName = 'Ramirez' // WRONG will not execute

That might seem like it is perfectly good code, it’s just missing the semicolon ; at the end. If you add the semicolon at the end of firstName, the code will run. This is because the JavaScript interpreter will add the semicolon at the end of the line automatically. Don’t trust or count on this happening every time. It’s best to split the code into separate lines and provide semicolons.

Data Types

[picture]

Data Types

Primitives

Type | Description | Examples
Numbers | Numerical representation of a values | 1,7,13,19,3.14,0.99923
Strings | Sequence of characters composing a string | "Becky Anderson" or 'Becky'
Booleans | True or False value | True or False
null | Declared but does not yet have a value | null
undefined | Represent no value | undefined

Numbers

JavaScript has only one type of number of type called number. You can represent numbers in four different ways. Don’t overthink the usage of the numbers. For example, infinity and NaN might not work like you intend. All numbers are stored in a 64-bit floating point. That means that whole numbers up to 15 digits are accurate, but decimal number representations are considered approximations.

Number Types | Example
Whole Number Value | 32
Decimals Value | 32.333333
Infinity Value | Infinity
NaN value | NaN

Whole Numbers also known as Integers

JavaScript Code Sample

1 var number = 1000;
2 console.log(number); //Result -> 1000

Decimal Number

JavaScript Code Sample

1 var number = 1000.9999;
2 console.log(number); //Result -> 1000.9999

Infinity Number

JavaScript Code Sample

1 var number = Infinity;
2 console.log(Infinity); //Result -> Infinity

NaN Number

JavaScript Code Sample

1 var number = NaN;
2 console.log(NaN); //Result -> NaN

Strings

The datatype String can hold a value of type string. The strings syntax states that the string must start with either a single quote or double quote. Whichever one starts the string must also end it.

JavaScript Code Sample

1 var firstName = 'Brandi';
2 var lastName = "Rodriguez";
3 console.log(firstName); //Result -> Brandi
4 console.log(lastName); //Result -> Rodriguez Rodriguez

Some of your programs might require you to convert a string to a certain format. JavaScript provides the escape character \ to exclude parts of a string and turn them into special characters. This is handy for when you want to put a double quote in your string without ending it, as well as similar cases.

The escape characters are the following.

Type | Description
\' | single quote
\" | double quote
\\ | backslash
\n | new line
\t | tab
\b | backspace
\f | form feed

JavaScript Code Sample

1 var user = 'Account:\t123\nName:\tBrandi Rodriguez\nNick Name:\t\'@Brandii91\'';
2 console.log(user);
3 /* Result ->
4 Account:	123
5 Name:	Brandi Rodriguez
6 Nick Name:	'@Brandii91'
7 */

Strings do not work the same way that numbers do. The only exception to this is the concatenate process. When you add two or more strings you end up with a single linked string.

JavaScript Code Sample

1 var firstName = 'Brandi';
2 var lastName = "Rodriguez";
3 var fullName = firstName + ' ' + lastName;
4 console.log(fullName); //Result -> Brandi Rodriguez

In the Beyond The Basics chapter, we take a closer look at how we can mutate strings to different forms.

Booleans

A boolean can either be true or false. You can create Booleans by an evaluation or a simple true or false value. If it’s as simple as a true or false value it must be all lowercase. For example, TRUE will not work but true will.

JavaScript Code Sample

1 var activeAccount = true;
2 console.log(activeAccount); //Result -> true
3 console.log(10 < 3); //Result -> false

null

null represents a value that is empty; it holds no value. You will find nulls when you explicitly don’t want to have a value on a variable.

JavaScript Code Sample

1 var name = "Brandi";
2 /* Brandi is not feeling so good */
3 /* NULL her out! */
4 name = null;
5 console.log(name); //Result -> null

undefined

undefined represents a value that is meaningless; it holds no value. undefined is typically found in variables that are declared but contain no value.

JavaScript Code Sample

1 var name;
2 console.log(name); //Result -> undefined

Undefined vs Null: Undefined means that the variable has been declared but does not yet have a value. Null, on the other hand, is set to a variable to represent no value.

Composites

Type | Description | Examples
Arrays | A container that holds values | var items = [123,32,12.0,'becky',22]

Objects and Functions are considered composites but not covered in this chapter, but arrays are. Make a quick note of the [] bracket token notation being used to create one as you will need to know it for when we explore arrays in more detail in the array section.

Operators

Now that we can create primitive and composite data types, it’s important to be able to test for a certain data type. This is important; for example, your program might require a number but get a string as inout. Here is where you can use a control structure to evaluate that value using the typeof operator.

JavaScript Code Sample

 1 var firstName = 'Brandi';
 2 var account = '1234';
 3 var age = 21;
 4 var accountActive = false;
 5 var password = null;
 6
 7 console.log(typeof firstName); //Result -> string
 8 console.log(typeof account); //Result -> string
 9 console.log(typeof age); //Result -> number
10 console.log(typeof accountActive); //Result -> boolean
11 console.log(typeof password); //Result -> null

Math & Logical Expressions

Arithmetic: Just like in math, computers can operate on two or more numbers. If you recall from your algebra knowledge, multiple operations can be made on a set of numbers. Below you will find examples of each of these operators.

Operator | Description
+ | Addition
- | Subtraction
* | Multiplication
/ | Division
% | Modulo

Addition

JavaScript Code Sample

1 var value = 3 + 3;
2 console.log(value); // Result 6

Subtraction

JavaScript Code Sample

1 var value = 3 - 3;
2 console.log(value); // Result 0

Multiplication

JavaScript Code Sample

1 var value = 3 * 3;
2 console.log(value); // Result 9

Division

JavaScript Code Sample

1 var value = 3 / 3;
2 console.log(value); // Result 1

Modulo The modulo is used to represent the remainder of two numbers. Modulus was omitted from the key concepts section due to other languages representing the modulo as a different symbol. JavaScript strictly uses the % symbol.

JavaScript Code Sample

1 var value = 3 % 3;
2 console.log(value); // Result 0

Logical Expressions

All logical expressions must evaluate to a boolean value. A logical expression is composed from a logical operator. Multiple operators can be combined to evaluate multiple values.

Operator | Description
== | Equal to
!= | Not equal
> | Greater than
>= | Greater than or equal to
< | Less than
<= | Less than or equal to

Control Structure

Single if statement

[picture]

Branch

JavaScript Code Sample

1 if(condition){
2   // True Branch
3 }

Ternary Operator

The conditional (?:) ternary operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Syntax Example:

JavaScript Code Sample

1 (condition ? expression1 : expression2)
2 (true or false ? true condition : false condition )

Condition is an expression that evaluates to true or false. expression1, expression2 expressions with values of any type.

Nested if statements

[picture]

Branch

JavaScript Code Sample

1 if(condition){
2   // True Branch
3   if(condition){
4     // True Branch
5   }
6 }

if else statements

[picture]

Branch

JavaScript Code Sample

1 if(condition){
2   // True Branch
3 }else{
4   // False Branch
5 }

Nested if else statements

[picture]

Branch

JavaScript Code Sample

 1 if(condition){
 2   // True Branch
 3   if(condition){
 4     // True Branch
 5   }else{
 6     // False Branch
 7   }
 8 }else{
 9   // False Branch
10   if(condition){
11     // True Branch
12   }else{
13     // False Branch
14   }
15 }

if else if else statements

[picture]

Branch

JavaScript Code Sample

1 if(condition){
2   // True Branch
3 }else if(condition){
4   // True Branch
5 }else{
6   // False Branch
7 }

Chained if else if statements

[picture]

Branch

JavaScript Code Sample

 1 if(condition){
 2   // True Branch
 3 }else if(condition){
 4   // True Branch
 5 }else if(condition){
 6   // True Branch
 7 }else if(condition){
 8   // True Branch
 9 }else if(condition){
10   // True Branch
11 }

Switch statement

[picture]

Branch

The switch statement evaluates an expression, matches the expression’s value to a case clause, and executes the statements associated with that case.

JavaScript Code Sample

 1 switch (condition) {
 2   case condition:
 3     /* True branch */
 4     /* True branch */
 5     break;
 6   case condition:
 7     /* True branch */
 8     /* True branch */
 9     break;
10   case condition:
11     /* True branch */
12     /* True branch */
13     break;
14   case condition:
15     /* True branch */
16     /* True branch */
17     break;
18   case condition:
19     /* True branch */
20     /* True branch */
21     break;
22   default:
23     /* Default branch */
24     /* Default branch */
25 }

Expression: an expression matched against each case statements.

Case: a case used to match against expression.

Default: executed if expression does not match any case statements.

The difference between a switch statement and an if else statement is that in a switch statement, you can continue execution on multiple branches, whereas in the if statement, you must explicitly remain on the branch that evaluated to true.

JavaScript provides the keyword break to stop a switch statement. If the switch statement is omitted, the switch statement will fall through, meaning the next statement will execute.

Using break

[picture]

Break

JavaScript Code Sample

1 switch (condition) {
2   case condition:
3     // True branch
4     break;
5   default:
6   // No need for a break here
7 }

Omitting the break statement

[picture]

Fall Through

JavaScript Code Sample

1 switch (condition) {
2   case condition:
3     // True branch
4   default:
5   // No need for a break here
6   // This will execute
7 }

Loops and Iteration

Loops and iteration help us to execute a piece of code repetitively. Loops and iteration differ in a couple of ways. JavaScript supports the following loop and iteration flows:

Keyword | Description
while | loops through a section of code while a specified condition is true
do while | loops through a section of code while a specified condition is true
for | iterates through a section of code N number of times
for in | iterates through a predefined number of items

Loops

while loop

The while loop’s condition is evaluated. If it evaluates to true, the loop will execute once and then check the condition again. This will continue until the condition becomes false or the break statement is used.

[picture]

While Loop

JavaScript Code Sample

1 while (condition) {
2   // Code statements go here
3   //...
4   //...
5   //...
6   //...
7 }

Pro Tip

Watch out for infinite loops, in general they are undesirable.

do while loop

Just like the while loop, this loop will loop through a piece of code. The do while loop does have a specific format that it must be typed in: the while keyword must be on the same line as the closing curly brace and have a semicolon at the end of the closing parentheses.

[picture]

Do While Loop

JavaScript Code Sample

1 do {
2   // Code statements go here
3   //...
4   //...
5   //...
6   //...
7 } while (condition); // <- NOTE the syntax

Pro Tip

The do while loop is guaranteed to execute, at least once.

Iteration

Iteration requires that you have a counter to keep track of what part of the iteration you are in and how much you have to go. Iteration helps you with iterating over a set of data when you know exactly how many items you need to iterate over.

for loop. The JavaScript for loop has three separate sections between the parentheses:

The initialization, only runs on the first iteration

The condition, runs on every iteration

Post iteration expression, runs at the end of each iteration

Each of these sections must be separated by a semicolon in order to be valid syntax.

[picture]

For Loop

JavaScript Code Sample

1 var iterations = 30;
2 for (var i = 1; i <= iterations; i = i + 1) {
3   console.log(i);
4 }

Results

1 1
2 2
3 ...
4 ...
5 29
6 30

The example creates a variable named iterations and sets it to 30. Inside the loop, the variable i is created and set to 1. The for iteration will check whether it should continue iterating or stop. The last part of the loop is to increment the count of i. The loop will stop when i becomes larger than 30.

Just as you can increment a count, you can also decrement a count.

JavaScript Code Sample

1 for (var iterations = 30; i < iterations >=  0; iterations = iterations - 1) {
2   console.log(iterations);
3 }
4 // Alternative syntax
5 var iterations = 30
6 for (; iterations >=  0; iterations = iterations - 1) {
7   console.log(iterations);
8 }

Results

1 30
2 29
3 ...
4 ...
5 1
6 0

The code displays a countdown from 30 to 0. It is best practice to set the definition of the counter inside the for loop.

Increment or Decrement Syntax

JavaScript supports multiple syntaxes to change the value of a counter. The most common ones are the following:

Pre-increment or Pre-decrement

1 var count = 0;
2 ++count;
3 --count;

Post-increment or Post-decrement

1 var count = 0;
2 count++;
3 count--;

Addition or subtraction

1 var count = 0;
2 count = count + 1;
3 count = count - 1;

Addition or subtraction short hand

1 count += 1;
2 count -= 1;

Difference Between Pre- and Post-? There is a slight performance increase when you pre-increment or pre-decrement a counter thanks to how JavaScript evaluates the expression.

What about Different Operators? All arithmetic operators are supported, but the most common are increment and decrement.

Early termination

Loops can be terminated early by using the break keyword. This is specifically useful for when you need to stop a loop without knowing the number of repetitions beforehand.

[picture]

Early Termination

JavaScript Code Sample

 1 var numberOfUsers = 300;
 2 while (true) {
 3   if(numberOfUsers == 249){
 4     console.log('Go no further!');
 5     break;
 6   }else{
 7     console.log(numberOfUsers);
 8     numberOfUsers = numberOfUsers - 1;
 9   }
10 }

Results

1 300
2 299
3 298
4 ...
5 ...
6 251
7 250
8 Go no further!

The code above is in an infinite loop. The code prints out the first 50 numbers preceding 300 in reverse order. When it gets to 249, it displays the message Go no further! instead, then terminates using the break keyword.

How does Node.js REPL Work?

The REPL(read–eval–print loop) can be accessed on your machine by using the node command on your terminal.

How exactly does REPL work?

Reads the code that you provide

Evaluates the code

Outputs the result, if any.

Goes back to step 1.

The REPL loop will evaluate any code, no matter how complicated, process that code, and then go back to step one ready to take new requests. This is also known as a program that is in an infinite loop.

Arrays

[picture]

Arrays

Arrays are the first composite data type that we will be taking a look at. Arrays are not a primitive type. Arrays are considered a data structure, which is just a way of defining how information is stored in memory. Our programs up to this point have used variables, and many of them. At times some of the programs that you create they will require more than a handful of variables, and this is where arrays are most commonly used. Arrays allow you to group a set of variables into a single data structure and have just one variable to contain multiple variables or values in memory.

An array is an ordered collection of data (either primitive or objects). Based on its place in the array, each data item has a numeric index through which you can access the corresponding value. In JavaScript, arrays are also objects that have their own properties.

Arrays can be created with the [] bracket notation.

JavaScript will allow you to add any data type to an array, but first you must declare an array with a given name. The most common names that you will find in an array would be a plural name, for example instead of having firstName you would have firstNames. This is typically used to show that the array has more than one item. Each of the items in the array must be separated by a comma ,.

Example of declaring an array

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy']; // Array \
2 with items
3 var lastNames = []; // Empty Array
4 var ids = [21]; // Single item in array
5
6 console.log(firstNames);
7 console.log(lastNames);
8 console.log(ids);

Results

1 [ 'Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy' ]
2 []
3 [ 21 ]

JavaScript allows you to have mixed datatypes in an array.

JavaScript Code Sample

1 var ages = ['Twenty One', 'Eighteen', 19, 22]; // Array with ages
2 console.log(ages);

Results

1 [ 'Twenty One', 'Eighteen', 19, 22 ]

Result

In JavaScript, all arrays start their indices at 0 and end at one less than the size of the array.

[picture]

Array Indexes

In the example above, the array is size 5 but the indexes range from 0 to 4. Each value of an array can be accessed through a valid index.

Example of accessing a value with an index.

JavaScript Code Sample

1 var ids = [12,1,12,7,null];
2 console.log(ids[3]);

Results

1 7

How Do I Add a Variable to an Array? The example above sets the initial values of the array inside the bracket [] notation. This is just a quick way to create variables without a name. If you have a variable that needs to go in an array, you can simply add it to the array just as you would with a definition of a brand new value.

Example of adding a variable to an array

JavaScript Code Sample

1 var specialId = 32;
2 var ids = [12,1,12,7,specialId];
3 console.log(ids[4]);

Results

1 32

What If I Use an Invalid Index?: This is a common error that new programmers typically make—it even has a name. It is called an “off by one error”. In JavaScript, nothing major will happen. You will just access a place in memory that is undefined. In other languages, this can be a more serious issue.

JavaScript Code Sample

1 var ids = [12,1,12,7,null];
2 console.log(ids[5]);

Results

1 undefined

Arrays are used when you need to keep a large amount of data in memory at the same time.

This is a perfect example of what not to do.

Example of what NOT to do

 1 // BAD CODE!!!!
 2 // DONT DO THIS!!!
 3 var becky = "Becky";
 4 var ferguson = "Ferguson";
 5 var megan = "Megan";
 6 var kim = "Kimberly";
 7 var brandy = "Brandy";
 8
 9 console.log(becky);
10 console.log(ferguson);
11 console.log(megan);
12 console.log(kim);
13 console.log(brandy);

Results

1 Becky
2 Ferguson
3 Megan
4 Kimberly
5 Brandy

Now instead of having five variables, all five names can now be stored in a single variable. The following example uses an array along with a for in loop to display the names.

JavaScript Code Sample

1 /* Much Cleaner */
2 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
3 for (var index in firstNames) {
4   console.log(firstNames[index]);
5 }

Results

1 Becky
2 Ferguson
3 Megan
4 Kimberly
5 Brandy

Although both of the programs are valid, one of them is very rigid and hard to change and maintain. For example, if you had a list of 300 first names, would you create 300 variable names? Probably not! Remember, an array is a group of memory locations that contain data types that are grouped together.

You should use arrays when you know that your program is going to require a piece of data throughout the execution time of the program. Computers are slow to read and write from files, databases, or other locations. It’s always your best and fastest option to work with local variables.

Arrays can grow to be large data sets. How large? As much as your computer memory will allow.

Iterating over an array

Iterating over an array is the process of walking through the array based on an expression. You can use any of the loop or iteration keywords to go through an array. Arrays have different properties available, such as the length property.

while loop

JavaScript Code Sample

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var index = 0;
 3 if(firstNames.length > 0){
 4   /* Safe guard, just in case it's an empty array */
 5   do {
 6     console.log(firstNames[index]); // The value is looked up based on the value\
 7  of the index
 8     index++; // Post increment the index value
 9   } while (index < firstNames.length);
10 }

do while loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
2 var index = 0;
3 while (index < firstNames.length) {
4   console.log(firstNames[index]); // The value is looked up based on the value o\
5 f the index
6   ++index; // Pre increment the index value
7 }

for loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
2 for (var index = 0; index < firstNames.length; index++) {
3   console.log(firstNames[index]); // The value is looked up based on the value o\
4 f the index
5 }

for in loop

JavaScript Code Sample

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
2 for (var index in firstNames) {
3   console.log(firstNames[index]); // The for loop out puts the index, instead of\
4  the value
5 }

Pro Tip

The most common loop structure to iterate over an array is the for loop.

All of this programs output the same values

Results

1 Becky
2 Ferguson
3 Megan
4 Kimberly
5 Brandy

This process of iterating over the array is not just limited to going in sequential order from 0 up one less than the length of the array. Whatever expression you can create that evaluates to a valid index and terminates the loop will work. For example, you can also only display the indices that fall into an even number or iterate the array in reverse.

Only displaying even indexes.

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
2 for (var index = 0; index < firstNames.length; index++) {
3   if(index % 2 == 0){ // This will be true at indexes 0, 2, and 4
4     console.log(firstNames[index]);
5   }
6 }

Results

1 Becky
2 Megan
3 Brandy

Iterating over an array in reverse

1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
2 for (var index = firstNames.length - 1; index > -1; index--) {
3   console.log(firstNames[index]);
4 }

Results

1 Brandy
2 Kimberly
3 Megan
4 Ferguson
5 Becky

Mutating Arrays

It’s great that we can iterate over an array, but some of our programs might require us to change the value of an item in the array. Take for example the following program. It will swap out the beginning of the array with the end of the array. In other words, it will reverse the array.

JavaScript Code Sample

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var startIndex = 0; /* Location of the first item */
 3 var done = false;
 4
 5 for (var endIndex = firstNames.length - 1; endIndex > -1; endIndex--) {
 6   if(startIndex == endIndex || done){
 7     if(!done){
 8       // We are at the middle, all done!
 9       done = true;
10     }
11     console.log(firstNames[startIndex]);
12     startIndex++;  // Continue iterating the rest of the array
13   }else{
14     var temp = firstNames[startIndex]; /* Hold this value while we swap out the \
15 values */
16     firstNames[startIndex] = firstNames[endIndex]; // Swap out the last item wit\
17 h the first item
18     firstNames[endIndex] = temp; // Swap out the first item with the last item
19     console.log(firstNames[startIndex]); // Display name
20     startIndex++; // Start iterating the array
21   }
22 }

Results

1 Brandy
2 Kimberly
3 Megan
4 Ferguson
5 Becky

Pro Tip

Remember when mutating an array the values of the array change.

Now, if you iterate through the array in sequential order you will get the reversed array instead of the original array.

JavaScript Code Sample

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var startIndex = 0; /* Location of the first item */
 3 for (var endIndex = firstNames.length - 1; endIndex > -1; endIndex--) {
 4   if(startIndex == endIndex){
 5     // We are at the middle, all done!
 6     break; // Terminate loop early
 7   }else{
 8     var temp = firstNames[startIndex]; /* Hold this value while we swap out the \
 9 values */
10     firstNames[startIndex] = firstNames[endIndex]; // Swap out the last item wit\
11 h the first item
12     firstNames[endIndex] = temp; // Swap out the first item with the last item
13     startIndex++; // Start iterating the array
14   }
15 }
16 for (var index = 0; index < firstNames.length; index++) {// Iterating over a mut\
17 ated array
18   console.log(firstNames[index]); // The value is looked up based on the value o\
19 f the index
20 }

Results

1 Brandy
2 Kimberly
3 Megan
4 Ferguson
5 Becky

Multiple Arrays

Just like you can have a single array, you can also have multiple arrays. Each of the arrays lives in a different location of memory, allowing you to treat them as two separate entities.

Iterating over two arrays

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];
 3
 4 console.log('First Names:');
 5 for (var index = 0; index < firstNames.length; index++) {
 6   console.log(firstNames[index]);
 7 }
 8
 9 console.log('\nLast Names:'); // Add an extra line for formatting
10 for (var index = 0; index < lastNames.length; index++) {
11   console.log(lastNames[index]);
12 }

Results

 1 First Names:
 2 Becky
 3 Ferguson
 4 Megan
 5 Kimberly
 6 Brandy
 7
 8 Last Names:
 9 Ramirez
10 Miller
11 Anderson
12 Thompson
13 Rodriguez

Just as you can iterate a single array you also iterate over multiple arrays. If you want to save time you can utilize the same loop.

Iterating over two arrays in the same loop

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];
 3
 4 if(firstNames.length == lastNames.length){ // Safe check to make sure arrays are\
 5  the same length
 6   // We would not want any undefined values
 7   for (var index = 0; index < firstNames.length; index++) {
 8     console.log('Full Name:', firstNames[index] + ' ' + lastNames[index]);
 9   }
10 }

Results

1 Full Name: Becky Ramirez
2 Full Name: Ferguson Miller
3 Full Name: Megan Anderson
4 Full Name: Kimberly Thompson
5 Full Name: Brandy Rodriguez

Warning

If you are unsure, if you should reuse a loop, just create a new one and optimize your code later. If you try to optimize early in the development life cycle you could end up wasting time in unneeded tasks. Always choose clarity over speed.

The above example can only be valid if both the first names and last names array equal the same length and are sorted in the correct order. If either of these conditions is not true, the program won’t work correctly.

Nested Loops: Arrays can be iterated in a nested loop. This is typically used when, while iterating over one array, you must look up a value in another array.

JavaScript Code Sample

 1 var firstNames = ['Becky', 'Ferguson', 'Megan', 'Kimberly', 'Brandy'];
 2 var lastNames = ['Ramirez', 'Miller', 'Anderson', 'Thompson', 'Rodriguez'];
 3
 4 for (var i = 0; i < firstNames.length; i++) {
 5   if(i == 0){
 6     // No formatting required
 7     console.log('First name:', firstNames[i]);
 8   }else{
 9     console.log('\nFirst name:', firstNames[i]);
10   }
11   // Display all last names
12   for (var j = 0; j < lastNames.length; j++) {
13     console.log('Last Name:', lastNames[j]);
14   }
15 }

Results

 1 First name: Becky
 2 Last Name: Ramirez
 3 Last Name: Miller
 4 Last Name: Anderson
 5 Last Name: Thompson
 6 Last Name: Rodriguez
 7
 8 First name: Ferguson
 9 Last Name: Ramirez
10 Last Name: Miller
11 Last Name: Anderson
12 Last Name: Thompson
13 Last Name: Rodriguez
14
15 First name: Megan
16 Last Name: Ramirez
17 Last Name: Miller
18 Last Name: Anderson
19 Last Name: Thompson
20 Last Name: Rodriguez
21
22 First name: Kimberly
23 Last Name: Ramirez
24 Last Name: Miller
25 Last Name: Anderson
26 Last Name: Thompson
27 Last Name: Rodriguez
28
29 First name: Brandy
30 Last Name: Ramirez
31 Last Name: Miller
32 Last Name: Anderson
33 Last Name: Thompson
34 Last Name: Rodriguez

Pro Tip

Most programmers use i, j, and k to keep track of an index

The loop starts and displays each of the first names with all the lasts names and continues on until it finishes. This might sound like a lot of arrays, but there are true use cases for nesting loops and arrays.

Multidimensional Array

JavaScript does not support two-dimensional arrays. Instead, you store an array inside another array, continuing on with as much memory as is available.

JavaScript Code Sample

 1 /* Two dimensional array that's 5 x 5
 2        C0 C1 C2 C3 C4
 3     R0[1][2][3][4][5]
 4     R1[2][4][6][8][10]
 5     R2[3][6][9][12][15]
 6     R3[4][8][12][16][20]
 7     R4[5][10][15][20][25]
 8 */
 9
10 var row0 = [1,2,3,4,5],
11     row1 = [2,4,6,8,10],
12     row2 = [3,6,9,12,15],
13     row3 = [4,8,12,16,20],
14     row4 = [5,10,15,20,25];
15
16 var table = [row0,row1,row2,row3,row4];
17 console.log(table[0][0]); // Get the first item in the array

Results

1 1

Five arrays are created with the name row* and are added to a new array called table

JavaScript Code Sample

 1 var row0 = [1,2,3,4,5],
 2     row1 = [2,4,6,8,10],
 3     row2 = [3,6,9,12,15],
 4     row3 = [4,8,12,16,20],
 5     row4 = [5,10,15,20,25];
 6
 7 var table = [row0,row1,row2,row3,row4];
 8
 9 for (var row = 0; row < table.length; row++) {
10   var tempRow = [];
11   for (var column = 0; column < table[row].length; column++) {
12     // Displays the row value
13     tempRow[column] = table[row][column];
14   }
15   console.log(tempRow);
16 }

Results

1 [ 1, 2, 3, 4, 5 ]
2 [ 2, 4, 6, 8, 10 ]
3 [ 3, 6, 9, 12, 15 ]
4 [ 4, 8, 12, 16, 20 ]
5 [ 5, 10, 15, 20, 25 ]

We have to use a temporary row to store the current row in order to be able to display it to the console.

Programming Challenge

With the help of the Scientific Method and the use of the Top-Down Design, you will be able to create fairly complex programs. The Top-Down Design is when you break up a large problem into smaller problems. In the previous chapter, we covered the Scientific Method, and I gave you a framework to solve any type of problem that you might encounter both in computing and in science in general. Now, we will be taking a closer look at how to apply the Scientific Method along with a Top-Down Design to solve an actual problem.

1. Understanding the problem

You must fully understand the problem before attempting to solve it. THIS IS IMPORTANT If you fail to understand the problem clearly, you will end up with an invalid solution.

How Exactly Do You Understand the Problem? Just like the Scientific Method, it all starts with a question. The questions that you ask will guide you through the process of understanding the problem. Each of the questions that you ask will get you closer to a valid solution both in design and efficiency.

What Questions Should I Ask? You need to ask enough questions to the point that you feel comfortable with the problem. This can take some time, but be patient and persist.

2. Understand the I/O

As you know by this point, all programs can have input or output. The inputs of a program are the preset variables, values, or assumptions. The output of the program will be the results of a certain process. Understanding what inputs and outputs are is required in order for you to design a valid program.

3. Design from top to bottom

When designing a program, you should begin by sketching out what you’re trying to achieve; typically, a solution to a problem. The sketch should be detailed enough for you to convert it to pseudo code or a detailed flowchart. After you have the detailed design, you can start to work on the expressions that are going to be needed for the program. This would be control structures, loops, and evaluations.

4. Validate your Design

The last step in the design process is to check that the design will solve the problem proposed in Step 1. You can check the program by walking through it step-by-step and evaluating the results. If at any point you find a mistake, fix the issue immediately and continue on with validating your program.

There are different methods for validating a program: automated tests, black box tests, white box tests and many more that are beyond the scope of this book.

Warning

If you decide to look at the solution before attempting to solve the problem yourself, you will NOT learn to program.

I don’t want you to look at the answer and say “Oh that’s easy, anyone can do that.” If you really think anyone can do it, I challenge you to get started with the problem set.

Don’t let the last couple of problems alarm you, they may look highly mathematical but they’re not.

1. Create a program that displays the following message: "Hello World".

View Solution

2. Create a program that displays the following list of colors: Red, Green, Blue, Cyan, White, Yellow, Magenta

View Solution

3. Create a program that displays the following colors in reverse: Red, Green, Blue, Cyan, White, Yellow, Magenta

View Solution

4. Create a program that displays the color with the fewest letters: For example Red, Green, Blue, Cyan, White, Yellow, Magenta would be Red

View Solution

5. Create a multiplication table that is 20 x 20 and display it on the screen.

View Solution

6. Create a multiplication table that is 20 x 20 and solve 18 x 13 using the table.

View Solution

7. Create a program that checks if a string is subset of another string. For example, both car and race are part of racecar.

View Solution

8. Create the Fizz Buzz game. The game is a simple counting game that increments by one each turn and replaces any number divisible by three using the keyword fizz and any divisible by five with the keyword buzz. If the number is both divisible by three and five, then the output is fizz buzz. Example output: 1,2,fizz,4,buzz,fiz, ... 13,14,fizz buzz, 16

[picture]

Fizz Buzz

View Solution

9. Create a program that finds the factorial of any given number.

[picture]

Factorial

View Solution

10. Create a program that will maximize the total change that is owed to a customer by providing them the right number of change in quarters, dimes, nickels, and pennies.

[picture]

Flow Chart

View Solution

11. Create a program to display the fibonacci sequence. The Fibonacci sequence is a sequence of numbers that can be determined by simply adding the previous two numbers of the sequence together to generate the next number. Example: The fibonacci sequence 1,1,2,3,5,8,13,21,34.

[picture]

Fibonacci Sequence

View Solution

12. Create a program that finds the average of a set of numbers. Take for example 12, 13, 18, 2, 32.

[picture]

Average

View Solution

13. Calculate the value of e, the mathematical constant.

[picture]

Sum of e

View Solution

14. Calculate the value of pi, the mathematical constant.

[picture]

Sum of pie

View Solution

Beyond the Basics

JavaScript is a multi-paradigm programming language. The main reason for this is to give developers a wide variety and options to freely create and develop on their selected paradigm. Each paradigm has advantages and disadvantages, and depending on the problem at hand, each methodology is more suitable for a specific type of problem than others.

This chapter is a light introduction to more advance topics in programming. Each of these topics can be expanded into their own books, e.g., Functional Programming, Object Oriented Programming, Software Engineering, etc. This chapter is used to provide you with an introduction to these more advanced topics and to start moving your skills as a programmer to the next level.

Each of the sections provides you with an introduction to these larger topics, along with some examples of the most common features that you will use as a new programmer.

No programming challenges are required for this chapter, since it’s just an introduction into these more advance topics.

Functions and Scope

“The full beauty of the subject of generating functions emerges only from tuning in on both channels: the discrete and the continuous.” - Herbert Wilf

JavaScript supports both functions and methods. The majority of the functionality that JavaScript provides is a set of predefined functions. These functions are pieces of predefined code that do some specific task such as print out a result to the terminal like console.log.

Functions naming conventions are the same as that of variables. They must have a unique identifier and not conflict with each other.

Pro Tip

When learning a new framework i.e Angular, Backbone, React, Underscore, etc the biggest challenge will be learning about all the functions available to you.

Use the following rule of thumb when creating new functions:

Give your functions a readable name

Know the parameters of a function

Know what to expect out of a function

Below, there is an illustration of a function g(x) that requires an input x and outputs value. The name of the function is clear and concise, the parameters are clear, and we know what to expect as output.

However, it’s unknown to us what exactly g(x) is doing. This is a key concept of functions—being able to use a function abstractly and get a requested output from it. This allows you to focus on the problem that you are attempting to solve instead of all of the details that go into g(x).

[picture]

Function

Functions in JavaScript are “First Class Citizens”. In other words, JavaScript supports passing functions as arguments to other functions, returning functions as the values from other functions, assigning functions to variables, and storing functions in a data structure. JavaScript supports higher-order functions, non-local variables in nested functions, anonymous functions, and closures.

Why use functions in the first place?

Functions are useful because they allow us to wrap up a piece a code that does one specific task, and only one task. In turn, this helps us to create large code bases with useful names allowing for code reuse to construct even more complex programs in record time.

Function Definition

 1 /*
 2   Raises a base number to a selected exponent.
 3   Returns value of base to exponent b^e
 4 */
 5 var power = function(base, exponent){
 6   if (exponent == 0) {
 7     return 1; // Base Case
 8   }
 9   if (exponent > 0) {
10     return base * power(base, exponent - 1);
11   }
12 };
13
14 console.log(power(2,5));

Results

1 32

In the example above, the variable power is assigned to a function. Anytime you want to use the function, you would just use the variable assigned to that function with parenthesis power(2,5); If a function has no parameters, use the name of the function along with a pair of empty parenthesis power();.

All functions must contain the keyword function along with a pair of braces {} and parenthesis (). Functions don’t need to have a name nor parameters. Functions can optionally return an explicit value; otherwise, all functions return the value of undefined.

Function Definitions

1 // function with the name power
2 function power(base, exponent){
3   // Code Block
4 }
5
6 // function with out parameters
7 function hello() {
8   console.log('hello');
9 }

Functions can wrap code that is used over and over again, which allows you to reuse code without having repetitive pieces of code all over the place.

The best way to find the right name for a function, is to be able to think about what the responsibility of the function will be. This is where having a strong background in Unix comes in handy. Take for example the code below. It’s composed from the smaller programs curl, grep, |, and >>. Each of them do exactly one thing and because of this single responsibility we can start to create larger and more complex programs based on simpler programs.

Sample

1 curl -i  https://www.jsecademy.com |  grep 'JavaScript' >> JSecademy.md

JavaScript also supports self-executing functions. This type of function is useful for creating a local scope to variables. All variables declared within the self-executing function are, by default, only available within the self-executing function. This helps create separation from other functions, preventing naming conflicts with other variables or functions.

Example of self-executing function

1 //Anonymous function
2 (function(){
3   // Code
4 }());//() Executes immediately

Self-executing function with parameters

1 var url = 'http://jsecademy.com'; // Global variable
2 (function(URL){ // Parameter
3   console.log(URL); // Local variable
4 }(url)); // Passing Global variable

Results

1 http://jsecademy.com

Parameters and Scopes

All functions in JavaScript can have parameters and scopes. Function parameters are optional and the amount of them can vary. All parameters in JavaScript are passed by reference, meaning that once the variable enters a function it will be in scope for that function. If the value changes inside that function, it will not affect the value outside the function.

On the function level scope, any new variables declared by the keyword var will only exist inside the local scope unless it’s returned back by using the keyword return.

Global variable passed by reference:

1 var url = "http://jsecademy.com"; // global variable
2 function printURL(url) {
3   console.log(url);
4 }
5 printURL(url);

Local Variables

1 function printURL() {
2   var url = "http://jsecademy.com"; // local scope variable
3   console.log(url);
4 }
5 printURL();

Results

1 http://jsecademy.com

Local variables prevent your program from conflicting with other local variables in other functions. This allows you to use the same variable names in two different locations this concept is also known as private variables.

Function Composition

[picture]

Function of Functions

Function composition, also known as function of functions, is where the result of one function is used as the input to another function, resulting in a third function. This allows for simple functions to build up to more complex ones. Since JavaScript treats all functions as first class citizens, function composition is highly encouraged to be used throughout an application.

Example of Function Composition

 1 (function printURL() {
 2   var url = 'http://jsecademy.com'; // Local variable to printURL()
 3   console.log('Original URL:', url);
 4
 5   // Requires URL without prefix
 6   function secureURL(url) {
 7       var securePrefix = 'https://'; // Local variable to secureURL()
 8       url = securePrefix + url;
 9       return url;
10   }
11
12   // Returns prefix from URL
13   function URLPreFix(url) {
14     if (url.substr(0, 'http://'.length) === 'http://') {
15         return 'http://';
16     }
17     if (url.substr(0, 'https://'.length) === 'https://') {
18         return 'https://';
19     }
20   }
21
22   // Return URL with out prefix, requires prefix
23   function URLWithOutPreFix(url, prefix) {
24     if (prefix === 'http://') {
25       return url.substr('http://'.length, url.length);
26     }
27     if (prefix === 'https://') {
28       return url.substr('https://'.length, url.length);
29     }
30   }
31
32   console.log('Secure URL:', secureURL(URLWithOutPreFix(url, URLPreFix(url))));
33 })();

Results

1 Original URL: http://jsecademy.com
2 Secure URL: https://jsecademy.com

In the example above, there is a self-executing function named printURL() that is executed right away. Inside the scope of printURL() there are three functions: secureURL(), URLPreFix(), and URLWithoutPreFix(). All of three of these functions are used in composition to create a secure URL. First, the URLWithoutPreFix() function requires a url and a prefix. The prefix can be obtained by using URLPreFix() function, which requires a url. Then, URLWithoutPreFix() returns a url without a prefix that is used by the secureURL() function and returns a url with the prefix of https://.

Composed like this, the code is not coupled to just converting URL’s to https://. Instead, it is broken up into multiple functions that can be used independently for specific tasks if need be.

JavaScript Code Sample

 1 var url = 'http://jsecademy.com';
 2 console.log('Original URL is:', url);
 3 // Return URL with out prefix, requires prefix
 4 function URLWithOutPreFix(url, prefix) {
 5   if (prefix === 'http://') {
 6     return url.substr('http://'.length, url.length);
 7   }
 8   if (prefix === 'https://') {
 9     return url.substr('https://'.length, url.length);
10   }
11 }
12
13 // Returns prefix from URL
14 function URLPreFix(url) {
15   if (url.substr(0, 'http://'.length) === 'http://') {
16       return 'http://';
17   }
18   if (url.substr(0, 'https://'.length) === 'https://') {
19       return 'https://';
20   }
21 }
22
23 console.log('URL Prefix is:',URLPreFix(url));
24 console.log('URL With out Prefix is:',URLWithOutPreFix(url, URLPreFix(url)));
25 console.log('URL With optional Prefix is: //' + URLWithOutPreFix(url, URLPreFix(\
26 url)));

Results

1 Original URL is: http://jsecademy.com
2 URL Prefix is: http://
3 URL With out Prefix is: jsecademy.com
4 URL With optional Prefix is: //jsecademy.com

From the example above, URL’s can now be manipulated into three options: with prefix, without prefix, or with the optional prefix that works with any type of prefix.

Recursion

[picture]

Recursion

Recursion is one of the topics that differ from the normal control flow of programs. The reason for this is that recursion is the act of calling a function from within itself. A recursive function MUST have a base case to terminate all of the calls made; otherwise, the stack will overflow with recursive calls.

Example of power function with recursion

 1 /*
 2   Raises a base number to a selected exponent.
 3   Returns value of base to exponent b^e
 4 */
 5 var power = function(base, exponent){
 6   if (exponent == 0) {
 7     return 1; // Base Case
 8   }
 9   if (exponent > 0) {
10     return base * power(base, exponent - 1);
11   }
12 };
13 console.log(power(2,5));

Results

1 32

Example of a enumeration with recursion

1 function enumartion(start,end) {
2   console.log(start);
3   if (end == 1)
4     return 1;
5   else
6     return enumartion(start + 1, end - 1);
7 }
8 enumartion(1,10);

Results

 1 1
 2 2
 3 3
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
10 10

How many calls does it take to overflow the stack? This depends on what platform JavaScript is running.

Testing Recursion call Stack

 1 (function(){
 2   var count = 0;
 3   function computeMaxCallStackSize(){
 4     try {
 5       count++;
 6       return computeMaxCallStackSize();
 7     } catch (e) {
 8         return;
 9     }
10   }
11   computeMaxCallStackSize();
12   console.log(count);
13 }());

Results

Platform | Calls
node | 11434
Chrome | 17926
Safari | 50723
Firefox | 107375

Objects

OO is about managing dependencies by selectively re-inverting certain key dependencies in your architecture, so that you can prevent rigidity, fragility, non reusability. - Uncle Bob

Programming paradigms come and go, but object-oriented programming has had constant growth since the term “Object Oriented Programming” was first coined by Alan Kay in the 1970s and gained wide adoption by the early 1980’s.

Up to this point, most of the programs from the examples have been functional programs or procedural programs. In a procedural programming paradigm, procedures work on data; in a functional programming paradigm, functions evaluate to other functions; and now in object oriented programming, the focus will be to create objects that contain both properties and methods that model them according to a specification.

JavaScript provides a wide range of objects that are defined with a preset value. Each of these objects has specific procedures (methods) and properties that can accomplish a wide variety of tasks. Since object oriented programming (OOP) is an entirely more advanced topic, we will only be covering the most basic and common objects that you will use, which are generic Objects, Arrays, Numbers, Dates, and Regular Expressions.

Below you will see an image of an object that is a light. It contains both methods and properties. The property is the simple one of a state, which holds the current state of the light (if it’s on or off). The object also has three methods, which are switch(), turnOff, and turnOn. The switch toggle will either turn the light on or off depending on what the state of the light is. This should start to give you an idea of how objects are used.

[picture]

Light Object

Data types are grouped into two different parts: primitives or composites. Each of these data types include predefined function definitions that can help you create your application. Composite data types can help you extend a primitive data type to do something completely different. This is a more advanced topic that is beyond the scope of this book. The remaining parts of this book will focus on how to use this predefined functionality that the JavaScript programming language provides for you.

Strings

Strings are a primitive data type that JavaScript includes in the language. Strings can be used to represent a sequence of characters.

Here are the most common string operations for mutating a string:

Methods

Method | Description
toString() | Returns the value of a string
toLowerCase() | Returns a new string that is all lowercase
toUpperCase() | Returns a new string that is all uppercase
charAt(index) | Returns the character at the specified index
concat(string) | Returns a new string composed from the strings passed in as a parameter

Properties

Property | Description
length | Returns the length of a string

Strings can be made all lowercase. JavaScript provides you with the toLowerCase() method. This method does not mutate the original string; instead, it returns you a new string that is all lowercase.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 var lowercase = firstName.toLowerCase();
3
4 console.log(firstName);
5 console.log(lowercase);

Results

1 Kimberly
2 kimberly

Just like you can go all lowercase, you can also go all uppercase with the toUpperCase() method. This method does not mutate the original string; instead, it returns you a new string that is all uppercase.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 var uppercase = firstName.toUpperCase();
3 console.log(firstName);
4 console.log(uppercase);

Results

1 Kimberly
2 KIMBERLY

Programs might require you to verify that a string is of a certain length. This is such a common request that in JavaScript, all strings have the .length property to identify the length of a string.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 var length = firstName.length;
3 console.log(length);

Results

1 8

Now that you know the length of the string, you can iterate over the string and use the charAt() method to display the letter at a given index position.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 for (var i = 0; i < firstName.length; i++) {
3   var character = firstName.charAt(i);
4   console.log(character);
5 }

Results

1 K
2 i
3 m
4 b
5 e
6 r
7 l
8 y

Concatenating Strings

When you would like to combine more than one string, you can use concatenation with the + addition operator. The most common use cases of concatenation of strings are the following:

Combination of multiple strings to compose a message

Displaying a value in a single line instead of multiple lines

Pro Tip

JavaScript combines two or more strings together to compose a new string.

Example of concatenating strings.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 var lastName = "Thompson";
3
4 var fullName = firstName + " " + lastName;
5 console.log(fullName);

Results

1 Kimberly Thompson

In the example above, three variables are used: firstName, lastName and fullName. The variable fullName is composed of firstName, an empty space " ", and lastName. Take special note of the empty space. We could have stored that space character in a variable, but instead we took advantage of the + addition operator to concatenate the strings.

JavaScript makes the operation of concatenating strings even easier with the concat() method. The function will join two or more strings to compose a new string.

JavaScript Code Sample

1 var firstName = "Kimberly";
2 var lastName = "Thompson";
3
4 var fullName = firstName.concat(" ", lastName, ".");
5 console.log(fullName);

Results

1 Kimberly Thompson.

In this example, four strings are joined together: firstName, an empty space " ", lastName, and the period ..

Pro Tip

The concat() function is specially useful when creating complex strings.

Summary

This is just a sample of what JavaScript strings can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with strings, check out the complete JavaScript Reference.

Data Structures

In Computer Science, you will find a wide variety of data structures that you can manipulate in your programs. For example, hash maps, arrays, associative arrays, graphs, lists, stacks, queues, and trees, just to name a few. Don’t worry. This is an entire section of Computer Science that is not covered in this book.

JavaScript provides you with one of these fundamental data structures which is the array. We have taken a look at them in the previous chapter, but now we will be taking our existing knowledge of objects and arrays and exploring how JavaScript can help us work with them.

Remember, arrays are just a data structure that stores related information together in a location in memory.

The following are the most common array operations for removing and adding items to an array:

Method | Description
push(item) | Adds item to the end of the array
unshift(item) | Adds item to the beginning of the array
pop() | Removes last item in the array
shift() | Removes first item in the array

Adding to an array

At this point, you should be fairly comfortable with adding items to any array based on an index.

Example of adding an item to an index

1 var names = [];
2 names[10] = "Brandy";
3 console.log(names[10]);

Results

1 Brandy

There will be cases where you won’t know the exact index location of where the item needs to be inserted. The push() method will add the item to the last available element location of the array.

Example of adding an item to an index

1 var names = ["Brandy"];
2 names.push("Ferguson");
3 console.log(names);

Results

1 [ 'Brandy', 'Ferguson' ]

The unshift() method will add the item to the beginning of the array and shift all the elements one location to the right.

JavaScript Code Sample

1 var names = ["Brandy" , "Ferguson"];
2 names.unshift("Megan");
3 console.log(names);

Results

1 [ 'Megan', 'Brandy', 'Ferguson' ]

Removing from an array

JavaScript supports multiple methods for removing items from an array. The easiest option is to set the value of a predefined location to be undefined. This partially works.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];
2 names[1] = undefined;
3 console.log(names);
4 console.log(names.length);

Results

1 [ 'Brandy', undefined ]
2 2

The value of index 1 is set to zero, but the length of the array remains at 2. This could be behavior that you want, but for most use cases you would want to remove the element and change the length of the array.

This is where the pop() method comes in handy. It will remove the last element of the array and change the length of the array.

JavaScript Code Sample

1 var names = ["Brandy", undefined];
2 names.pop();
3 console.log(names);
4 console.log(names.length);

Results

1 [ 'Brandy' ]
2 1

Pro Tip

JavaScript also supports the keyword delete to set a value of an array to undefined

If you want to remove an item from the beginning of the array you can use shift() method.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];
2 names.shift();
3 console.log(names);
4 console.log(names.length);

Results

1 [ 'Ferguson' ]
2 1

Mutating Arrays

Using arrays as a data structure can become very useful when mutating an array to do a specific task. JavaScript gives you a wide support for a variety of functions for mutating arrays that are pre-defined in the language.

The following are the most common operations for mutating an array:

Method | Description
toString() | Converts an array into a string
join(‘delimiter’) | Joins all items in array to a string with an optional delimiter
splice(startIndex, howManyToRemove, itemToAdd1, itemToAdd2) | Adds or removes from an array; returns items removed
slice(startIndex, endIndex) | Returns a new array with selected index
sort() | Sorts items of array alphabetically
reverse() | Reverses the order of the array
concat(array[]) | Joins two or more arrays
indexOf(item) | Searches array for an item and returns index

JavaScript arrays will automatically be turned into a string when outputting their values to the console. This is because the console object is invoking the toString() method behind the scenes. If you want to convert an array without the console, just use the toString() method.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];
2 var string = names.toString();
3 console.log(typeof string);
4 console.log(string);

Results

1 string
2 Brandy,Ferguson

The names are pre-formatted with a , comma when using the toString() method. You can alter this behavior by using the join() method on the array. When you join the array you can set a specific delimiter when each of the items is concatenated.

Pro Tip

Remember the join() method does not mutate the original array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];
2 var mutatedArray = names.join('|');
3 console.log(mutatedArray);

Results

1 string
2 Brandy|Ferguson

If you have a predefined index and know how many items you want to remove or insert into the array, then the splice() method will do exactly this. The method requires starting location to add or remove items, how many items to remove, and the number of items N to add into the array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson"];
2 names.splice(1,0,"Megan");
3 console.log(names);

Results

1 [ 'Brandy', 'Megan', 'Ferguson' ]

In the code example, we know the location to start the removal of items is 1, and it removes items in the array up to 0, which is no items in the array. Then, the last part is to insert into the array item Megan.

Arrays can output other arrays. The slice() method will return a new array that contains values from the original array. The method takes two arguments: the start index and the end index. The start index will remove all the elements up to one less than the end index. If you omit the second parameter, the method will automatically use the length property and return all items from the start index to the length of the array.

JavaScript Code Sample

1 var names = ["Brandy", "Ferguson", "Megan"];
2 var arrayOfNames = names.slice(0,2);
3 console.log(arrayOfNames);

Results

1 [ 'Brandy', 'Ferguson' ]

JavaScript has full support for sorting an array into alphabetical order, meaning that if you have any numbers in an array they will take precedent over letters. The sort() method will mutate the current array and return that mutated array.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", 323, "Ferguson"];
2 names.sort();
3 console.log(names);

Results

1 [ 323, 'Brandy', 'Ferguson', 'Megan' ]

JavaScript has full support for reversing an array. If you remember back to the code that reversed an array, it’s a trivial piece of code, but thanks to JavaScript support you won’t have to write this implementation yourself.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", 323, "Ferguson"];
2 names.reverse();
3 console.log(names);

Results

1 [ 'Ferguson', 323, 'Brandy', 'Megan' ]

JavaScript supports the ability to combine two or more arrays to compose a new array. Using the concat() function, you can combine as many arrays as you like. The order you pass each of the arrays into the function is the order they will be combined into the new array.

JavaScript Code Sample

1 var girlsNames = ["Megan", "Brandy"];
2 var boysNames = ["Ferguson"];
3 var luckyNumbers = [323];
4 var combinedArrays = girlsNames.concat(luckyNumbers, boysNames);
5 console.log(combinedArrays);

Results

1 [ 'Megan', 'Brandy', 323, 'Ferguson' ]

JavaScript also supports the ability to find an item’s index based on its value with the indexOf() function. The way this function works is when you pass in a valid value within the array, it returns the index of that value. If the value does not exist in the array, the function will return -1 to signify an invalid item.

JavaScript Code Sample

1 var names = ["Megan", "Brandy", "Ferguson"];
2 var name = names.indexOf("Brandy");
3 var invalidName = names.indexOf("Becky");
4 console.log(name);
5 console.log(invalidName);

Results

1 1
2 -1

Summary

This is just a sample of what JavaScript can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with arrays, check out the complete JavaScript Reference.

Numbers

JavaScript has only one type of number. Numbers can be written with, or without, decimals.

JavaScript Code Sample

1 var integer = 7;
2 var float = 3.14159;

Unlike many other programming languages, JavaScript does not define different types of numbers such as integer, short, long, and floating points. Numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

Precision:

Integers are considered accurate up to 15 digits.

Decimals’ max length is 17 digits after the decimal, but are not always 100% accurate.

Numbers have Properties and Methods that are available to you as a programmer.

Number Properties

Property | Description
MAX_VALUE | Largest number possible in JavaScript
MIN_VALUE | Smallest number possible in JavaScript
NEGATIVE_INFINITY | Negative infinity
NaN | Not-a-Number value
POSITIVE_INFINITY | Infinity

You can use the Number object to obtain the properties of a number.

Example of properties:

JavaScript Code Sample

1 console.log(Number.MAX_VALUE);
2 console.log(Number.MIN_VALUE);
3 console.log(Number.NEGATIVE_INFINITY);
4 console.log(Number.NaN);
5 console.log(Number.POSITIVE_INFINITY);

Results

1 1.7976931348623157e+308
2 5e-324
3 -Infinity
4 NaN
5 Infinity

Number Methods

JavaScript provides several methods to you for working with numbers. Here is a list of the most common methods that are used in programs:

Method | Description
toExponential() | Converts a number into an exponential notation
toFixed(y) | Formats a number with y numbers of digits after the decimal point
toPrecision(y) | Formats a number to y length
toString() | Converts a number to a string
valueOf() | Returns the primitive value of a number

JavaScript Code Sample

1 var age = 32;
2 console.log(age.toExponential());
3 console.log(age.toFixed(2));
4 console.log(age.toPrecision(8));
5 console.log(age.toString());
6 console.log(age.valueOf());

Results

1 3.2e+1
2 32.00
3 32.000000
4 32
5 32

Summary

This is just a sample of what JavaScript numbers can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with numbers, check out the complete JavaScript Reference.

Dates

Dates are an important part of any modern program. JavaScript provides you with the Date object. This object can be used to work with time zones or date mutations.

JavaScript’s Date object requires you to use the new operator. If you omit the new operator, the Date() function will return today’s current date as a string.

The most common use cases for dates are the following:

Get Methods

Method | Description
getDate() | Returns the day of the month (from 1-31)
getMonth() | Returns the month (from 0-11)
getFullYear() | Returns the year (four digits)

Set Methods

Method | Description
setDate(day) | Sets the day of the month of a date object
setMonth(month, day) | Sets the month of a date object
setFullYear(four digits) | Sets the year (four digits) of a date object

JavaScript Code Sample

 1 var today = new Date();
 2 console.log(today);
 3 console.log(today.getDate());
 4 console.log(today.getMonth());
 5 console.log(today.getFullYear());
 6
 7 var yesterday = new Date();
 8 yesterday.setDate(today.getDate()-1);
 9 console.log(yesterday);
10
11 var lastMonth = new Date();
12 lastMonth.setMonth(today.getMonth()-1);
13 console.log(lastMonth);
14
15 var lastYear = new Date();
16 lastYear.setFullYear(today.getFullYear()-1);
17 console.log(lastYear);

Results

1 Sat Dec 05 2015 15:46:06 GMT-0700 (MST)
2 5
3 11
4 2015
5 Fri Dec 04 2015 15:46:06 GMT-0700 (MST)
6 Thu Nov 05 2015 15:46:06 GMT-0700 (MST)
7 Fri Dec 05 2014 15:46:06 GMT-0700 (MST)

Summary

This is just a sample of what JavaScript Dates can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with Dates, check out the complete JavaScript Reference.

Regular Expressions

JavaScript supports regular expressions. You probably have not heard of regular expressions before. They tend to be called other names, such as “Regex” or “Regexp”.

In simplest terms, a regular expression is a way that we can express a description of a string.

Regular expressions have many useful use cases; for example, evaluating if a string matches a pattern, extracting specific parts of a string, or replacing parts of a string.

Regular expression syntax Every single regular expression starts with a / and ends with a /. What goes in between is the pattern that you are trying to match.

[picture]

Pattern

At the end of the expression you can use a flag to specify a specific function. Here is the list of flags that JavaScript offers:

Flags

Flag | Description
g | Global match
i | Ignore case
m | Multiline

[picture]

Flags

The flags specific order does not have any precedence; for example, gi and ig are the same.

Creating Patterns

JavaScript supports two methods for creating regular expressions.

1. Variable expressions

JavaScript Code Sample

1 var regex = /car/ig

2. Object Creation

JavaScript Code Sample

1 var regex = new RegExp('car', 'ig');

Now that you have a regular expression, you can use it to validate a string. Here is a list of the most common methods that you might use:

Method | Description
exec() | Search for a match in a string.
test() | Tests for a match in a string.

JavaScript Code Sample

1 var regex = new RegExp('car', 'ig');
2 var words = ["racecar", "chrome"];
3 console.log(regex.test(words[0]));
4 console.log(regex.test(words[1]));

Results

1 true
2 false

This regular expression is a simple one; it will match any string with the word car in it. To create more complex regular expressions, JavaScript provides a wide range of tokens for you to use.

Token | Description
. | The dot matches any single character except line terminators
\d | Matches a digit character in the basic Latin alphabet
D | Matches any character that is not a digit in the basic Latin alphabet
\w | Matches any alphanumeric character from the basic Latin alphabet, including the underscore
W | Matches any character that is not a word character from the basic Latin alphabet

JavaScript Code Sample

1 var regex = /c\w\wo/ig
2 var words = ["racecar", "chrome"];
3 console.log(regex.test(words[0]));
4 console.log(regex.test(words[1]));

Results

1 false
2 true

The regular expression matches any string that contains the pattern of c\w\wo where \w is used to denote any alphanumeric character.

Summary

This is just a sample of what JavaScript regular expressions can do. If you would like to see the full documentation for all the functions and methods that are available to you when working with regular expressions, check out the complete JavaScript Reference.

Congratulations

You are well on your way to becoming a GREAT programmer. You have successfully completed this book. This is a BIG DEAL! You need to celebrate. As a new programmer, you are now joining a select group of individuals. You might think that this is nothing special, but that would be wrong. Consider this: most people can’t learn to program. 50%-60% of every university computer science department’s intake fail the first programming course. This means that an average of 5 out of 10 people will fail to learn the programming fundamentals.

I want to hear about your success as a programmer. I welcome you to write into rick@codewithintent.com.

New programmers from all around the world need your help! Can you please go onto Amazon.com, JSecademy.com, or wherever you purchased this book and leave your feedback about the book. This will help new programmers decide if this book is right for them.

Leave a review:

Amazon

JSecademy

Thank you for giving me the opportunity to show you around the world of programming.

Best wishes,

Rick Hernandez.