Let’s Learn JavaScript • Lesson 1 • Introduction

📅 July 13, 2017
• Have you ever submitted a form only to find that some fields will filled incorrectly with red borders? That is JavaScript in action.

• Have you scrolled through a list of images and noticed new images appear? That is JavaScript trying to make life easier for you while conserving bandwidth.

• 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 is JavaScript being used to aggravate in hopes that you will part with your money.

JavaScript is a full-featured programming language that produces web pages whose content can change when certain conditions are met. 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

We will focus on client-side JavaScript, which is JavaScript that runs within a web browser or other device that connects to a web server. When you make a connection via the Internet or from a LAN (Local Area Network), the computer or device making the request is called a client, and the computer it communicates with 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 data 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. JavaScript is the standard client-side scripting language for browsers today, so select a browser you like best.

Some browsers to pick from. Starting at the top left: Vivaldi, Mozilla Firefox Developer Edition, Opera, Mozilla Firefox, Chromium, and Google Chrome.

Browser to Try:

  • Vivaldi – Chrome-based browser with extensive customization.
  • Mozilla Firefox Developer Edition – Firefox with development in mind.
  • Opera – Alternate browser different from Chrome-based and Mozilla-based browsers.
  • Mozilla Firefox – The standard Firefox. Developer tools are available, but the Developer Edition is worth a try for comparison.
  • Chromium – The open-source version of Google Chrome.
  • Google Chrome – The proprietary version of the Chromium browser.

Always test your web pages in multiple browsers in order to check that they appear and perform similar in all. One of the disadvantages of web design is that a page might appear perfectly in one browser but display as a complete mess in another despite following web standards.

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.

All you need is a text editor and a browser (or two or three or four) in order to write JavaScript programs.

Coding Tips

Avoid an IDE (For Now)

An IDE (Integrated Development Environment) is a special-purpose program for writing program code by combining several features into a single easy-to-use program. This allows you to write programs in less time and with greater accuracy. The IDE WebStorm was designed with JavaScript in mind.

WebStorm 2017.1.4 in Linux Mint 18.2. WHile an IDE provides many features that programmers will find useful, beginners should not rely upon it when learning a new language.

As useful as an IDE might be, avoid using one for now. Use a plain text editor. By relying completely upon a text editor that provides no help, you must lean upon your knowledge and skills. This helps you learn the language better. By doing this, you will understand what you are learning. This way, you can be skilled programmer regardless of which IDE or text editor you choose to write programs with. If you rely upon an IDE, then you risk becoming dependent upon that particular IDE. Not good.

There are no visual aids when using a text editor. Did you make a mistake? Then, you must analyze your code in detail because incorrect syntax will not be underlined in red the way an IDE would reveal. Is your code not running? Again, double-check your program in a text editor. You have to know what you are doing, and a text editor drills this practice well. An IDE does not.

Memorize keywords. Learn statement syntax. Enter proper whitespace manually so your code is readable. An IDE will do these things for you, but a text editor requires that you pay attention to your code and develop the habits.

One good advantage is color-coding, Definitely use a text editor that highlights statements, keywords, and other syntax using colored text. This is a vital programming convenience, not a hindrance.

One more reason to avoid an IDE: Project dependency. Various IDEs will organize projects using custom project management systems that are incompatible with one another. This makes it tricky to migrate code written in one IDE to another IDE. Plain text files have no such limitation.

 

Use A Dedicated Directory

Never use a system directory or home directory to test your code. No, no, no!

If something goes wring, you do not want to ruin your operating system installation or delete personal files by accident in the event of program malfunction. When you write a program, it will probably contain bugs.

While there is no danger that JavaScript will damage your system, this is a good habit to develop. When you learn other languages that do traverse your system’s directory structure, such as C, then any problems will be confined to the development directory.

Create a new directory and name it whatever you like. The directory name code is obvious.

Nemo in Linux Mint 18. code is a directory devoted to nothing but program development code. All JavaScript development files should exist together in the same directory in order to avoid files not found because they are locate din other directories.

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: