JavaScript Basics

Punctuation

Capitalization

JavaScript is case-sensitive, like most passwords. A capital "J" is different than a lowercase "j". Keywords, which instruct the computer what to do, are all lowercase. Developer-created variables and functions have to have a single-word name with no spaces. So we use camelCase to show different words in a chain.

CamelCase

CamelCase is like a hashtag with each additional word starting with a capital. It makes names much easier to read: carStartingPosition, showTextOnScreen, testScore2. A few other special characters (namely, _ and &) can be used, but they're usually reserved for special situations. Stick with standard letters, numbers if needed (but no numbers as the first character).

Naming Conventions

There's more to the rules of convention here, like variables and properties should begin with a lowercase letter, while constructor functions begin with an Uppercase letter, and constants are ALL_CAPS with words separated by underscores. The main concepts are not to use spaces and to make it easy to read.

Semicolons

Each statement should end with a semicolon, unless the statement is followed by a code block, like a conditional, function, or loop. If you don't put them in, the browser will do its best to parse your code to make sense of it and figure our where each statement ends. It is a better practice to just tell the computer where you want each statement to end. Consider this:

Consider that statement. Could you read it? Was it easy or did it take a minute to parse the words and figure out what it was saying?

Quote Marks

JavaScript can understand 'single quotes' or "double quotes". Either is fine, but be consistent. I stick with double quotes except in special circumstances.

Brackets

There are three types of brackets in JavaScript. Each has its own sets of uses. Every open bracket must have a matching closing bracket. If you have brackets inside brackets, you need to close them properly. Inner brackets must be closed before outer brackets. For example, if you want some peanut butter in a cabinet, you open the cabinet, then open the peanut butter; you close the peanut butter, then close the cabinet.

() Parentheses are used for mathematical operations, like 3 * (2 + 5). They are also used for functions to call the function and to pass parameters into one. Parentheses are also needed for testing conditions in an if statement, while loop, and for setting the parameters of a for loop.

[] Square brackets are used to declare arrays. You also use them to access specific elements in an array. Square brackets can also be used to access properties in an object.

{} Braces, or squiggly brackets, are used to declare functions. They are also used to enclose code blocks that run, for example, as part of a loop.

Comments

Insert comments in your code to explain what your code is meant to do. You can also comment out lines of code to skip over them while you debug your work. There are two ways to add a comment. Use a double slash // to comment out a single line (or part of a line) of code. Wrap a comment block with /*     */ to disable several lines of code.

Variables

These are used to store values in a program. They allow for values to change and to be tested against repetitive conditions. If you're going to make a cold cut sandwich, the variables would be things like the type of bread, the type of cold cuts, the number of slices, etc. The sandwich itself is made through a repetitive process; bread slice, spread, cold cuts, bread slice. You can swap out the actual parts, but the underlying process is the same. That's one of the powers of variables.

There are three types of variables (for simplicity I'm separating out other types into their own categories): numbers, strings, and Booleans.

Variables are declared using the let keyword. You can just declare a variable, or you can assign its value when you declare it. Previous versions of JavaScript used the var keyword instead, and you may see that often in older code.

Input/Output

In many programs, you want the user to input some information and then react to it. You also want to provide feedback to the user when a task is done, or with updates along the way. In JavaScript alone, you're limited to the console window or alert/prompt boxes. More commonly, the input/output is passed to a webpage by updating HTML.

Writing to the console

To write to the console, use the log method of the console:

It is possible to pass variables in there too:

Using an alert

You can also pop up a dialogue box with information using the alert() function:

This also accepts variables:

Using a prompt

To get text input from a user, use the prompt() command. Typically, you assign this to a variable so you can run tests on the answer:

You can also supply a default answer:

Using confirm

You can use a confirm() popup to get a true or false response from the user. This is done with an OK or Cancel button.

Using HTML

There are different methods for HTML and they all look scary at first. The top priority is to have a unique id for each element you want to access, then you call the element through the HTML document object. You can do this to retrieve info or to update it.

To get information from a user from an <input> tag that has "answer" for its id:

To post information to a tag with an id of "response":

Operators

There are several operators. Math operators are great for numbers (+, -, *, /, %). Modulo/modulus (%) returns the remainder after division, so 20 % 3 is equal to 2, because 3 goes in 6 times to get 18 and 2 is left over.

Operations on variables don't look like regular algebra. If you have a variable (x) and you want to increase its value by five (5), you use: x = x + 5;. In algebra, this wouldn't make sense. If you tried to solve for x, you'd get 0 = 5 which is crazy. Instead, the computer evaluates the expression on the right side of the equals sign (x + 5 in this case) and when it has the answer, it then replaces the value on the left side (x in this case) with the answer.

++ increases the value of a number by 1 and -- decreases the value by 1. Example:

Strings are concatenated (joined together) with use of the + sign. "Hi" + "there" would give "Hithere". Notice that the browser does not automatically add a space between words. You have to do that yourself.

The dot operator is used to access properties of objects. To find the size of an array, for instance, use myArray.length;

Functions

A function is a set of code used to complete a single or small task. It can be called as needed over and over. It is possible to pass parameters into a function and it is possible to return values from the function. Declare a function with the keyword function.

Call the function: calculateArea(4, 7); This would return a value of 28. The value can also be stored in a variable:

Functions do not need to return any values. They can just carry out actions.

They also don't need any arguments, so they're very flexible based on your needs.

You can even have anonymous functions that don't have names. These are useful in a number of places but stick with named functions until you're more advanced.

 Conditional: if/else

Computers need ways of making decisions. An if statement tests for a condition. If it is true, then a certain code block will run. You can also set up an else statement that activates if the condition is false. Conditions can be comparisons, such if a number is greater than another number, or it can test if a Boolean is true.

The else statement is not required, but it is a good way for controlling code. It is also possible to nest several if statements together to make a logic chain. When one part of the chain is activated, the program steps out of the conditionals and runs the rest of the code after the logic chain.

It is also possible to test for two (or more) conditions at once. Let's say you want to decide if you should wear a jacket. You'll need one if it is cold or if it is raining. Use the OR operator || if only one condition needs to be true. If all conditions need to be true then use the AND operator &&.

Conditional: switch

When you have a lot of conditions to test against a single variable, you could use a whole set of if/else statements, but a switch statement is a cleaner way to go. A switch can be used for strings or numbers. Set up all the cases to test and it is prudent to also include a default at the end. Each case needs a break statement. If two cases give the same result, it is possible to have one case drop through to the next.

Comparisons

JavaScript also allows you to test if two values are the same number and the same type. For this, use a triple equals sign ===. Because variables in JavaScript are dynamic, it is always a good idea to use the triple equals for all comparisons. It is otherwise possible for two different variables to test as equal.

It is also possible to test if two values are equal using a double equals sign == to see if the values are the same. There are some things going on behind the scene so you may get some unexpected results. For example, if you compare a number and a string, JavaScript automatically tries to turn the string into a number for you. Likewise, when comparing a boolean, it converts true to 1 and false to 0. While this may make some comparisons seem easier, unless you're aware of what the rules are, you'll get some unexpected results. You're better off with cleaner code anyway.

You should always use === for equality comparisons.

You can also test for "less than or equal to" using <= or "greater than or equal to" >=

You may also need to test if something is not true. For this, use the NOT operatior ! at the front of the comparison operator, such as !== for "not strictly equal to". Examples: x !== 7; !snowingOutside;

Loops

A loop is useful when you need to repeat a block of code a certain number of times. It wouldn't be good to write the same code over and over. It is better to use a loop. Let's say you needed to fix a part of the code, you would have to change all the different lines you wrote in. But if you wrote it as a loop, then you only have to change the code once, inside the loop.

There are two types of loops, a for loop and a while loop. Use a for loop when you know how many times you need to run the code. Use a while loop when you don't know how many times to run the loop.

There is a variation of the while loop called a do...while loop. The difference is that the code in the block always runs at least once, whereas in a while loop, it is possible for the loop to be skipped entirely if the condition started as false.

A for loop is set up differently. It has three main parts: an initializer that sets a starting counter (var i = 0), a condition that keeps the loop running as long as that is true (i < 10),  and the incrementer for the loop (i++). You can use any variable name, but i is often used as an abbreviation for "iteration" or "index." The incrementer can go up or down and it can do than count by 1. To count by three, use i = i + 3 instead of i++.

A loop can also be controlled from within using the keywords break; and continue;. A break; command will exit the loop and move on outside the loop. A continue; command is used to jump to the top of the loop and keep going without finishing the code in the loop below the continue.

Arrays

An array is a variable that holds a list of information. Think of a shopping list or a set of test scores. Arrays are set up with square brackets []. Individual items are separated by commas. Elements in an array can be added or removed and so programs can be flexible. Also, it is possible to access individual items in an array using the index of items in the list. Index numbers start at zero.

Access items in the array using the index. Remember, indexes start at zero. scores[0] would be 75 and foodList[2] would be "cheese". You can set items using the index number too. foodList[3] = "milk";

You can also use array methods to alter the list. Use the name of the array, a dot, and the name of the method you want to use.

Objects

An object is like a super-variable. It holds several pieces of information related to a single object. It can hold variables, arrays, and functions, etc. Each variable is considered a property and is accessed using a dot operator. Properties should be set up when the object is created, but JavaScript lets you create properties on the fly. As convenient as that can be, it can lead to debugging problems and inconsistency in the code.

To understand an object, think of a car. A car has a make and model, a year, a color, cruise control, etc.

You access the information using the dot modifiers: myCar.year; Properties can also be reassigned in this way: myCar.cruiseControl = false; You shouldn't, but you can make new properties at any time by assigning them: myCar.color = "blue"; (You should have them initialized with the object declaration.)

If your object has functions inside, they're called methods to distinguish them as belonging to an object. They're just regular functions, but you call them with the dot operator. myCar.drive(); There's a lot more complexity possible too. There is the this keyword that lets the object reference itself so it is possible to perform operations or methods within the object on the object itself. It is advanced stuff and takes some getting used to.

Scope

It is possible to set up variables that only exist in small, temporary locations. This is called scope and it is very useful. Whenever possible, all variables should be the local scope. The global scope should be avoided whenever possible, but sometimes it can't be helped. As the name implies, a variable in a global scope can be used anywhere in your program by any function or operation. This may work for some things, but let's say you have a counter variable, it could accidentally be changed by another counter variable that has the same name elsewhere. The only way to change scope in JavaScript is to use functions. A variable that is declared inside a function is only visible within that function. Note: there is an exception to this rule through the use of closures, but that's more advanced stuff.

Conclusion

There are many other nuances to cover but this guide is meant only to be reference or a refresher. You can't really learn to code until you try to make your own programs. Typing in someone else's code is a good place to start, but you have to try creating your own in order to understand what is happening. Even with what I know and understand, there are times where I will overlook a nuance and something won't behave as expected. The best practice you can get comes from debugging your code and figuring out why the unexpected happened and figuring out what you have to do to fix it. Ask for help, sure, but you'll learn better if you try to fix it yourself. Good luck.