Let’s Learn JavaScript • Lesson 1 • Introduction

📅 July 13, 2017
Have you ever entered text in a search engine and noticed suggested results appear as you type? That’s JavaScript.

Have you scrolled through a web page of images and observed new images added to the page as you scroll towards the bottom of the page? That’s JavaScript.

 

Have you watched forms display a red border or error message as you finished entering a credit card number? That’s more JavaScript.

Have you ever thrown up your hands in anger as annoying popups littered your desktop with mind-jarring, blinking ads accompanied by new browser windows that expand to fullscreen in order to advertise an online survey? That, too, is JavaScript.

JavaScript is a programming language that produces dynamic web pages. If you have ever wanted to learn how to perform this mysterious magic in JavaScript, then here is the first lesson that introduces the background of this fun language.

Lesson 1 Overview

  • Client-side vs. Server-side
  • What is JavaScript?
    • Cross-Platform
    • Interpreted vs. Compiled
    • Strongly typed vs. Weakly typed
    • Object-oriented
    • JavaScript and Java Are Different
    • Full Programming Language
  • JavaScript Limitations
    • JavaScript cannot read or write files
    • JavaScript cannot directly access databases
    • JavaScript cannot protect your code from prying eyes
    • A JavaScript program is limited to the browser it is running in
  • What Do I Need to Program JavaScript?
    • The Web Browser
    • The Text Editor
  • What Operating System Should I Use?
  • Coding Tips
    • Avoid an IDE (For Now)
    • Develop In A Dedicated Directory

 

Client-side vs. Server-side

These lessons focus on what is called client-side JavaScript, which is JavaScript that runs within a web browser. When you make a connection via the Internet or on a LAN (Local Area Network), the computer or device making the request is called a client, and the computer it talks to is called the server.

Clients connecting to a server.

A client is a program running on a computer, a tablet, a game console, a cell phone, a Raspberry Pi, or whatever other device that might connect over a network.

The server is a program running on a (usually) more expensive, faster computer system or group of computer systems that is capable of handling many, many, many client requests simultaneously.

Client-server model.

This concept is referred to as a client-server model. A client makes a request to a server. The server does something with the request, such as process or retrieve data, and then the server sends the result back to the client for display on the user’s device.

Web browser on client requests a web page from the web server.

Server-side JavaScript runs on a server, such as with Node.js, but server-side scripting is another topic. Client-side JavaScript is more accessible to most people due to its simplicity. Only after learning client-side JavaScript should you branch out and learn the more complex server-side JavaScript offered by Node.js.

 

What Is JavaScript?

JavaScript is a cross-platform, interpreted programming language that incorporates object-oriented concepts. It was developed and released by a company called Netscape (yes, the same Netscape that developed the Netscape Navigator web browser) around 1995 as a weakly typed scripting language to make web pages feel more alive and dynamic.

At that time, web pages were static. This meant that once you loaded a web page, all content was fixed. Text and graphics did not change (unless you used an animated GIF image). There was no interaction (unless you used a Java applet or Flash control). What you saw was what you were stuck with unless the server altered the content upon the next page refresh.

JavaScript changed that. Now, users could hover the mouse cursor over an image, and it would change into another image to produce a rollover effect. Text would alter as the page loaded in order to greet the user with the current time and possibly the user’s name in order to make a page feel more personalized.

Session state could be saved between pages using cookies in order to provide some form of “memory” on a web site.

Today, when combined with the features of HTML 5, we go far beyond what the initial release of JavaScript was limited to.

Cross-Platform

Cross-platform means that your program will run on any architecture, operating system, and browser. For example, if you write a JavaScript program using Linux and test that it functions properly in the Vivaldi web browser, then the same program will run on a Mac in the Safari browser or on a Nintendo Wii with the Opera browser.

Write a script once and run it on different platforms.

There are a few exceptions, such as outdated browsers lacking support for some features, but most modern browsers today support the latest standards and will run JavaScript code written on a different platform.

Interpreted vs. Compiled

There are two ways to run a program: interpreted or compiled. A programming language is usually designed with one method or the other. The heavy-weight, strict programming languages, such as C, C++, and Java, must be compiled before execution — the process of running a program.

When you write a computer program, you type lines of code called statements. This is plain text in a language we understand, such as English — just like writing a letter. This plain text version of the program written in our language is called source code. But the computer has no idea how to read our language. A computer only understands 0’s and 1’s. So, we must convert the source code into 0’s and 1’s that the computer can execute.

The CPU (Central Processing Unit) is the processor in a computer system. It contains its own instruction set called machine code. A program must be converted from source code into machine code in order for the CPU to execute it.

The method used in this conversion process is either interpreted or compiled. If we convert source code ahead of time into a machine-readable program, called an executable file, for execution, then we are said to have compiled the program. We then execute the compiled code, not the source code. C, C++, and Java require that source code be compiled before running the program. If you make a change to the source code, then you must recompile the program in order to update the changes in the executable before running it again.

Compiled Code. Source code must be compiled separately for each target platform. An executable compiled for a specific platform only runs on that platform. Each platform/architecture requires its own executable. Often, the source code must be tweaked for various platforms and architectures. The advantage is speed. Since each compiled executable is machine code, it will run as fast as its CPU and platform will allow.

An interpreted language takes a different approach that does not require compiling before execution. It will run the program as it reads the source code. A special program called an interpreter steps through the source code and produces the results immediately. There is no separate compile step.

Interpreted Code. An interpreter specific to each platform reads and executes the same source code. There is no compile step. The advantages are convenience and portability. The same code will run on any platform as long as an interpreter exists for the platform. However, interpreted code runs slower than compiled code.

Why use one method over another? There are advantages and disadvantages to both techniques, but the main difference is speed. Compiled programs run faster — much faster — than interpreted programs because a compiled program speaks the machine code language of the processor.

An interpreted language might be more convenient to edit and run, but it always requires an interpreter to perform the same conversion process every time, so it runs slower.

Almost all modern web browsers available today include built-in JavaScript interpreters, sometimes called engines. For example, the JavaScript interpreter in Google Chrome is called V8, and it handles the execution of all JavaScript encountered on a web page.

If you have a web browser, then you already have a JavaScript interpreter. All you need to do is write the JavaScript source code and run it in a browser.

Strongly Typed vs. Weakly Typed

Typing refers to the kind of data type that variables can store. If this sounds strange at this point, that’s okay. We will elaborate upon this subject later. For now, there are two main types: strong and weak.

Let’s use a box to illustrate typing. If we have a box that only holds gold coins and gold coins only, then the box is strongly typed. We cannot put silver coins or copper coins in the box because the box was designed only for gold coins.

However, if we have a box that is weakly typed, then we can store any type of coins. We could start with gold coins, dump them out, and then put silver coins in the same box. The box would be weakly typed.

A strongly typed box is allowed to store only one type of shape. For example, if the box is constructed to hold circles, then it cannot hold squares, stars, or triangles. A weakly typed box may hold any type of shape. It might begin storing stars, then the stars may be replaced with squares or triangles.

JavaScript is weakly typed. A variable might hold a string, but we can change that to a number at anytime and then back again. Strongly typed languages throw an error when this happens, but JavaScript allows it.

This will make more sense when we introduce variables.

Object-oriented

JavaScript allows programs built using object-oriented methodologies. If you want to create an object with properties and methods, you can. It is not a requirement, but the option is there.

JavaScript and Java Are Different

Both have the word “Java” in them, but they are two different languages.

Why? Blame it upon marketing. At the time when the Internet was gaining popularity around 1994, users were craving more interaction with web pages. When Java was released for mass consumption around 1996, web users were delighted. Java applets could perform a seemingly endless variety of magical tricks, such as changing the mouse cursor into a mouse with a swishing tail, graphical raindrop effects on site banners, messing up the browser’s status bar with international phone numbers, and displaying incredibly annoying banner ads that took at least three minutes to load over a dial-up modem. It was great.

Java become popular quickly.

Very popular. Very quick.

Since Java was the new darling of the programming world at the time, the folks at Netscape were wondering what to call their scripting language in order to gain mass acceptance. Netscape’s offering was based off of an obscure specification called ECMAScript…and that does not sound cool at all. (ECMA stands for European Computer Manufacturers Association.)

So, they had an idea. Since Java is popular, let’s call it JavaScript!

The idea worked, and JavaScript combined with HTML 5 is now apparently more popular than Java applets, which are falling out of favor.

About the only thing Java and JavaScript have in common besides the name is that they both use C-style syntax. This means many keywords, words reserved by the language, are similar, and statements end with semicolons. If you can read one language, then you can usually read the other because Java and JavaScript can trace their roots back to C.

There is more to the history of JavaScript than the short summary presented here, but to sum it up: Java is to JavaScript what Test is to Testimony.

Full Programming Language

JavaScript is a fully fledged programming language that can be used to create massive, complex programs. Just because most pages you view might consist of short scripts does not mean that JavaScript is limited to simple code. You can write extensive web-based applications in JavaScript complete with a feature-rich API (Application Programming Interface).

For everyday use in web browsers, good practice dictates that scripts be kept as small as possible for faster rendering by the browser. Longer programs take more time to execute, and this can stall a web page and make users wait.

JavaScript Limitations

JavaScript has its limits due to security reasons.

1. JavaScript cannot read or write files.

Whether on the client or on a server, JavaScript cannot access any files stored on your computer. Would you want somebody else’s code snooping through your files when browsing a web site?

JavaScript cannot view, edit, or delete files located on a user’s computer (except for cookies). This situation cannot happen.

On the server side, JavaScript can trigger PHP or CGI (Common Gateway Interface) scripts that indirectly cause JavaScript to access files on the server, but JavaScript itself does not have direct access to computer files.

On the client side, JavaScript can create cookies, which are really files, but that is all. Cookies are limited in their sizes and what they are allowed to store.

2. JavaScript cannot directly access databases.

Again, this must be accomplished using server-side scripting. JavaScript can read database objects stored using JSON (JavaScript Object Notation) and communicate with a server using AJAX (Asynchronous JavaScript and XML), but these require the help of the server.

3. JavaScript cannot protect your code from prying eyes.

Anyone can open the markup and source code of a page and view it. Nothing is protected or encrypted. Every interpreted language is viewable in its original form. This is what makes interpreted languages easy to edit.

However, if your code holds trade secrets, encryption keys, passwords, email addresses, or any other brilliant ideas you might have, they are not safe. Given enough time, anyone can sift through your code to find your hidden treasures. There are techniques that try to obfuscate JavaScript code in order to thwart reverse engineering, but it is not true privacy.

A browser must have complete access to all files needed in order to render a page. Whatever a browser can see, end users can see.

4. A JavaScript program is limited to the browser it is running in.

You cannot use JavaScript to open applications on your system. It cannot take over your computer and perform operations the way a seated user can. JavaScript is confined to a restricted space within the browser, so if, for example, you want to install a new Linux distribution on a spare hard drive in your system, then you must handle that yourself manually. JavaScript cannot do that.

What Do I Need to Program JavaScript?

Client-side JavaScript requires very little.

  • A web browser
  • A text editor

Until we learn server-related interactions, all JavaScript will run on your own system locally without the need for a server or even an Internet connection.

The process is easy: Write a script, and then run it in a browser.

The Web Browser

The web browser is where you load web pages that execute JavaScript code. Any modern browser today supports JavaScript, so pick the browser you like best.

A few browsers. From top left by row: Vivaldi, Mozilla Firefox Developer Edition, Opera, Mozilla Firefox, Chromium, and Google Chrome.

A few browsers:

  • Vivaldi – Superb browser with extensive customization and developer tools.
  • Mozilla Firefox Developer Edition – Firefox with a focus on developer tools.
  • Opera – Good for testing web pages in an alternate browser. Includes developer tools similar to Vivaldi.
  • Mozilla Firefox – Includes tools, but Developer Edition seems better. Better for page testing.
  • Chromium – Open-source version of Google Chrome. Includes developer tools.
  • Google Chrome – The proprietary version of Chromium. Includes developer tools.

During web development, you should always have more than one browser so you can test your page in multiple browsers to make sure that the page is rendered properly in all. Standards support can vary among browsers.

The Text Editor

A text editor is a program that reads and write plain text files. The key is plain text. Only the characters themselves are recording. There is no formatting information included as would be with word processors. Do not use a word processor.

Text editors can range from simple to complex, free to expensive. Try several and focus on the one that works the best for you. For Linux, gedit and xed are two that offer a range of programming-related features, such as code indentation and regular expression manipulations, in addition to color themes that offer pleasing aesthetics.

xed in Linux Mint is a plain text editor with enough features to facilitate coding JavaScript and other languages. Various themes and extensions are possible for customization.

Mac and Windows have their own offerings. If using Windows, avoid the built-in Notepad. Notepad is too limited, and it does not interpret end of line sequences properly. If you write a script in Linux gedit and then open it in Notepad, Notepad will show the entire script on a single line. For Windows, Notepad++ and ConTEXT are two recommendations.

What Operating System Should I Use?

Any will work because JavaScript is not tied to a specific operating system. Use whichever operating system you prefer. JavaScript does not care. Linux tends to offer the best programming-related environment, but you can code JavaScript equally well with Mac and Windows systems.

As long as you have a browser and a text editor, you can write JavaScript programs.

Coding Tips

Avoid an IDE (For Now)

An IDE (Integrated Development Environment) is a specialized program for developing code. It combines many features into one that makes coding more efficient. WebStorm is an excellent IDE for JavaScript.

An IDE offers a glorious wealth of programming conveniences. Shown here is WebStorm 2017.1.4 running in Linux Mint.

However, avoid an IDE for now. Use a plain text editor. The goal is to understand what you are learning in order to become proficient regardless of the text editor or IDE used.

While an IDE is good for advanced development, a plain text editor is better when learning a programming language because it forces you to think about the language and understand what you are doing. An IDE is comparable to learning how to ride a bicycle using training wheels — it offers too much help at first. You do not want to become dependent upon a specific IDE. What happens if you do not have one available? Can you still write code?

With a text editor, there are no visual aids that show your coding errors. You must pay close attention and analyze your code in detail. Auto-completion features are absent. You must memorize keywords, statements, and syntax and enter them properly or else your code will not run. However, do use a text editor that offers color-coding themes since highlight keywords and statement structure for easier learning.

Another reason to avoid an IDE for now is that many implement custom project directory structures. You cannot easily migrate a coding project from one IDE, such as NetBeans, into another IDE, such as Eclipse, without modification because the IDEs have different directory structures and project organization techniques. With a text editor, you can use the same source in any, and your code will run since you are editing plain text files that are independent of any IDE.

Again, IDEs interfere with learning at first. Only after you can code proficiently with a text editor should you begin using an IDE. Once you know the language well, then advance to an IDE so you can write scripts in less time.

Develop In A Dedicated Directory

Create a dedicated directory in your home and store all code there. Name it something recognizable, such as code, and organize your projects within it. Doing this prevents code litter throughout your system, and it confine all code to a specific directory. When writing code in other languages, such as C or C++, that have access to your local file system, then this strategy helps reduce the risk of your program deleting files. If any files are deleted, then only those in the code directory will be affected (usually).

Nemo in Linux Mint 18.1. This is a dedicated directory name code that contains all files for experimentation and JavaScript development. This avoids the problem of a page not updating because it might be accessing the wrong file in another directory. If a coding problem occurs, then the problem must be located here.

Of course, there is no danger of JavaScript deleting files from your system because it lacks the ability and the permission to do so.

In the next lesson, we will begin with HTML 5 basics.

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: