📖 JavaScript Basics

Statements

A single JavaScript command or programming unit that ends with a semicolon (;). May be on a single line or multiple lines. Generally speaking, JavaScript ignores extra whitespace, carriage returns and tabs in your code.

Comments

Comments may be added to JavaScript code to document what is happening. Comments are displayed in the code only and are not executed as part of the script.

  • A single line comment is designated by a double slash (//). All text following the // to the end of the line will be treated as a comment.
  • Multiple line comments are preceded by a /* and concluded with a */. All code between the /* and */ will be treated as a comment.
// This is a single line comment
/* This is a multi-
   line comment */

Built-in Functions

  • Commands that perform a certain task such as alert() or document.write()
  • Always followed by parentheses () which may or may not contain values to be passed to the function.

prompt("text");

  • This is a built-in function that displays a special prompt box with the specified text and a textbox where the user can type in their response.
  • By setting a variable to the value of the prompt field, you can then use the user-provided data in your program.

var yourName = prompt("Please enter your name");
document.write("Welcome, "+ yourName);

Primitive Data Types (Literals)

JavaScript has a data type called primitives. A primitive type is a data type with a primitive (fixed) value. A primitive value is fixed. There are 5 primitive data types.

  1. String, which is text. String values are enclosed in quotation marks ("string value") to distinguish them from variable names (see below). If a number is enclosed in quotations marks ("75244"), then it becomes a string instead of a number. Strings can consist of letters, numbers and special characters.
  2. Number, any numeric value such as an integer or decimal number.
  3. Boolean, true or false.
  4. Null, empty and meaningless - doesn't have a value.
  5. Undefined, a value that is not defined.

Strings, numbers and booleans can be objects if created with the new keyword, but will mostly be used as primitives (at least in this class). We can also assign these primitive values to variables using the var keyword. IE: var myColor = "Blue";.

Variables

There are 2 types of variables in JavaScript; primitive value types and reference types. Variables are a location in memory that contains one or more values. A primitive data type variable holds a single primitive value for a variable. A reference data type holds values for objects, arrays and functions. You create a variable and give it a name so that you can reference that value in your JavaScript code. There are rules about naming variables:

  • Variable names must start with a letter, dollar sign ($) or underscore ( _ ).
  • Variable names can only contain letters, numbers, the dollar sign and the underscore. No spaces or other special characters may be used.
  • JavaScript is case sensitive, so you must be consistent with capitalization. If you create a variable called myVar, and later use MyVar, then JavaScript will treat them as two different variables. There are no hard and fast rules on capitalization but convention is to start with lowercase and capitalize the first letter of any subsequent words firstName, lastName, address, zipCode, etc. It is a very good idea to follow this convention to help you keep your names consistent. Many hours of debugging time can be attributed to simple capitalization errors.
  • There is a set of reserved words that cannot be used as a variable name. These are words that are part of the JavaScript language itself such asif, new, while, else, return, etc. 
  • You should use meaningful variable names that indicate what the variable represents to make it easier to follow and debug your JavaScript code.
  • To create a variable use the word var followed by the variable name:
    var myVar;
  • To assign a value to a variable use the equal sign:
    myVar = "This is my variable";
  • You can create a variable and assign it a value in the same statement:
    var myVar = "This is my variable";
  • You can create multiple variables at the same time by separating them with commas:
    var myVar1, myVar2, myVar3; or
    var myVar = "This is my variable", myNum = 100, myBool = false;

Note: Although it is good practice to use the var verb to create your variables, it is not strictly required by JavaScript. If you use a variable name that has not been declared, JavaScript will still create and use the variable. This is partly why it is so critical to adhere to naming standards. If you accidentally use MyVar instead of myVar, JavaScript will actually create a variable called MyVar and use it rather than giving you an error message.

let and const

Similar to var, let and const are two additional JavaScript container used to hold information. They are newer to JavaScript and were added to provide block level scope. Block level scope changes the availability of the element to the code. JavaScript uses code blocks (code contained within curly braces{}) to hold information for use in the script. Using block level scope limits the use of the variable to within the containing block.

Also, while the older var can be redeclared and updated, the newer let and const have different abilities. Assigning values to let will allow those values to be updated but not redeclared. Assigning values to const disallows both updates and redeclarations. Think of const as a constant value. 

So, the new variable containers let and const have block level scope and limits on the changes allowed but are preferred in most cases to the older var containers. In many cases, the use of these could be interchangeable with no discernable effects. You can find more information in the JavaScript docs at Mozilla.

Operators

Operators are symbols used in expressions to manipulate variables and literals. Operators may be used with literals and variables to create more complex expressions.

var area = length * width;
var circumference = 2 * pi * radius;
var amount = 500;

Operator Definitions
Operator TypeOperators
Arithmetic

+
-
*
/
%
++
--

addition
subtraction or negation
multiplication
division
modulus
increment - prefix or postfix
decrement - prefix or postfix

Assignment

=
+=
-=
*=
/=
%=

Assigns value of right operand to left operand
Adds value of right operand to left operand
Subtracts value of right operand from left operand
Multiplies right operand times left operand and stores in left operand
Divides left operand by right operand and stores in left operand
Divides left operand by right operand and stores remainder in left operand
Comparison
==
!=
>
<
>=
<=
equal
not equal
greater than
less than
greater than or equal to
less than or equal to
Logical
&&
||
!

AND
OR
NOT

String
+
+=
Concatenate
Combine

Concatenation

Be careful using the + operator. With numbers, the + operator is an arithmetic operator and will add numbers producing the sum of the numbers. With strings, the + operator is the concatenation operator which adds text strings together. If JavaScript thinks your numbers are strings, it will concatenate them instead of adding them. Usually, numbers are mistaken as strings when they are encased in quotes.

      var myNum = 3 + 2; // This will output the sum of the numbers 5
   var myString = "Three" + " plus " + "two."; // This will output the concatenated string 'Three plus two.'
var myNumString = "3" + "2"; // This will output the concatenated string '32'

Template Literals

Another way of inserting variable values into strings is to use template literals with string interpolation. Template literals with string interpolation allows you to avoid using the + sign to concatenate strings including variables. Consider the following example where the traditional concatenation is used to add strings and variables. Then compare to using template literal using string interpolation ${} to add the variable.

Notice with template literals you must use the backtick (`) symbol to delimit the ends of the string instead of the traditional quote (') or double quote ("). The backtick is on the keyboard to the left of #1.  

var concatenate = "concatenation";
document.write("This is a string with " + concatenate + ".");
// This will output 'This is a string with concatenation.'

var templateLiteral = "template literal"
document.write(`This is a string with ${templateLiteral}.`);
// This will output 'This is a string with template literal.'

Arrays

An array contains a set of data represented by a single variable name. This means an array is basically a list of one or more items. Items in a JavaScript array are indexed using tracking values called keys. Keys are simply a way to uniquely identify each element of the array called key-value pairs. The keys are integers, normally assigned by JavaScript, beginning at 0. So, JavaScript uses numeric indexed arrays that begin with a zero index to uniquely identify elements of an array.

Creating an Array

  • To create an array:
    var variable_name = [ ];
  • You can create an array and assign values to the elements at the same time:
    var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  • Each occurrence of an array is called an element. Elements are numbered beginning with 0 (zero).
    [0]="Sunday", [1]="Monday", [2]="Tuesday", ...
  • Refer to an element by putting the index number in square brackets [n] after the array name:
    array_name[index];
    daysOfWeek[0]; // This would return a value of "Sunday" from the daysOfWeek array above.

Adding Items to an Array

  • Initialize a new array:
    var course = ["ITSE 1301", "ITSE 1303", "ITSE 2313"] ;
  • To add an item to the end of an array, use the next available index number:
    course[3] ="ITSE 1311" ;
  • If you don't know the next index number, your can used the length property instead:
    course[course.length] ="ITSE 1311" ;
  • Another option is to use the built-in push() function. You may add one or more items in this way:
    course.push("ITSE 1311"); or course.push("ITSE 1311", "ITSE 2302", "INEW 2330");
  • To add an item at the beginning of an array, use the built-in unshift() function:
    course.unshift("ITSE 1311") ;

Deleting Items from an Array

  • To delete an item from the end of an array, use the built-in pop() function:
    course.pop();
  • To delete an item from the beginning of an array use the built-in shift() function:
    course.shift();

You can review an example of additional array functions on 2learnweb.