JavaScript Tutorial: Learn the Basics

banner-JavaScript

By Jenni Choi for Udemy

Interested in more than a guide? Check out one of our full JavaScript courses.

Note: This post is part of our “Getting Started” series of free text tutorials on some of our most popular course topics.

To jump to a specific section, click the table of contents below:

PREREQUISITES

HISTORY

Compiled vs. Scripting Languages
Is JavaScript Related to Java?
ECMAScript
Outside the Browser
What Is It Used For?
HTML, CSS, JavaScript: One Body
Client-side JavaScript

GETTING STARTED

Console
Hello World

JAVASCRIPT AND HTML FILES

The SCRIPT Tag
Internal JavaScript
External JavaScript

Advantages of Using External Files

DISPLAYING DATA

SYNTAX & GRAMMAR

Statements

NAMING CONVENTION

Camel Case

VALUES

COMMENTS

Single Line Comments
Multi-line Comments/Comment Blocks

VARIABLES

Declaring Variables
Identifiers
Assignment
Initialization
Mutability
Data Types
Dynamic Data Types
Type of Operator
Expressions
Assignment
Evaluation
One Statement, Multiple Variables

OPERATORS

Operators and Operands
Mathematical Operators
Precedence
Assignment Operators
String Operators
Comparison and Logical Operators
Logical Operators
Type Coercion

CONDITIONALS

If Statements
If-else Statements
Else-if Statements

Switch Statements

LOOPS

For Loop
While Loop
Do While
Infinite Loops

FUNCTIONS

Syntax
Function Names
Calling/Invoking a Function
Parameters and Arguments
Return Statement
Functions in Variables
Anonymous Functions
Variable Scope

OBJECTS

Assessing Properties and Methods
Property Reassignment and Creation
Nested Objects
Built-in Objects
Global Methods
NaN
Arrays
Primitive Value
Creating Objects

INTERMEDIATE TOPICS

THIS KEYWORD

Window Object
Functions Inside Objects
Function Expressions

FORM VALIDATION

THE BOM

THE DOM

EVENTS AND CALLBACKS

Events
Callbacks

JSON

Syntax

AJAX

ADVANCED TOPICS

OBJECT CONSTRUCTORS

PROTOTYPAL INHERITANCE

LIBRARIES

jQuery


Prerequisites

It is highly recommended that those starting this tutorial have at least a basic understanding of HTTP Protocol and possess a solid grasp of HTML and CSS. You can find introductory resources for these topics on Udemy’s website. 

History

Brendan Eich created JavaScript in 1995 while working as an engineer at Netscape. It is an object-oriented programming language* which can be used to facilitate interactivity within browsers, without reloading pages for each action. JavaScript is a scripting language.

Object-oriented programming (OOP):  OOP revolves around “objects,” which have their own characteristics and behaviors.

Compiled vs. Scripting Languages

Compiled languages must undergo compilation, which translates code into computer-readable bits and bytes.

Scripting languages do not need to undergo compilation. They rely on special run-time environments and related interpreters—computer programs that execute code without compilation, through various methods.

Is JavaScript related to Java?

This scripting language was originally slated to be named LiveScript. However, for marketing purposes its name became JavaScript, to ride on the coattails of the popular Java language. The two languages share few similarities.

ECMAScript

ECMAScript standard refers to the JavaScript standardization document, created by the ECMA International organization. The terms JavaScript and ECMAScript are often used interchangeably.

Outside the Browser

As mentioned previously, as a scripting language, JavaScript relies on a host environment with a JavaScript interpreter. Its most commonly used one is the browser. Other host environments include Adobe Acrobat, Adobe Photoshop, server-side environments, databases, and embedded computers.

What is it used for?

  • Creating dynamic pages
  • Allowing user interactivity
  • Adding multimedia elements

HTML, CSS, JavaScript: One Body

Think of HTML as the skeleton, CSS as the skin, and JavaScript as the muscle.
HTML handles the web page content. CSS controls the visual presentation of the content. And, JavaScript makes the web page interactive by dictating its behavior.

Client-side JavaScript

JavaScript is mostly used on the client side. Client-side JavaScript entails code running on the client machine. Server-side JavaScript runs on the server serving web pages.

Getting Started

The easiest way to start using JavaScript is with a modern web browser; my favorite is Google Chrome.

Console

Google Chrome and other browsers offer the Console tool, which allows users to view information about the current web page and execute JavaScript.

A comprehensive guide to using Chrome’s console can be viewed via the following link.

Opening the Console in Chrome
You can open the Console tab in one of two ways:

  • Use the keyboard shortcut Command + Option + J (Mac) or Control+ Shift + J (Windows/Linux).
  • image02
  • Select > More Tools > JavaScript Console.
    (Note: for multi-line entries in the console, use shift + enter/return)

Hello World

Let’s write our first piece of JavaScript code. In your console, type the following piece of code and press enter.

alert('Hello, World!')

You should see an alert pop up with the greeting “Hello, World!”

That was easy! Now, let’s dive in and learn about the ins and outs of JavaScript.  

JavaScript and HTML Files

The SCRIPT Tag

When a browser detects a <SCRIPT> tag in an HTML file, it knows to execute JavaScript code.

Internal JavaScript

You can place JavaScript directly in the HTML file, between the <script> and </script> tags.
Example:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example web page</title>
  <link rel="stylesheet" type="text/css" href="css/example.css">

</head>
<body>
    <h1>Example Page</h1>
    <script>document.write(%u2018<h3>Hello!</h3>%u2019)</script>
    <p>Glad you%u2019re here.</p>
</body>
</html>

Internal JavaScript can be placed in either the head or body section of an HTML document.

External JavaScript

You can also link an external JavaScript file to an HTML file.
Example:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example web page</title>
  <link rel="stylesheet" type="text/css" href="css/example.css">

</head>
<body>
    <h1>Example Page</h1>
<p>Glad you%u2019re here.</p>
    <script src = "js/example.js"></script>
</body>
</html>

 

The path to the external JavaScript file is the value of the src attribute in the <script> tag.
It is recommended that scripts be placed at the bottom of the <body> element, to prevent delayed page loading due to blockage of HTML display by script loading.

Advantages of Using External Files

  • Separation of JavaScript and HTML makes both easier to read and maintain.
  • Pages can load faster due to the caching of JavaScript files by browsers, which decreases the size of HTML documents; Internal JavaScript increases the size of HTML documents because it gets downloaded upon each HTML document request.
  • You can link multiple HTML documents to the same JavaScript file, which can decrease page loading time due to browser caching.

Displaying Data

JavaScript can output data in various ways:

  • console.log()
    • Output goes to the browser console 
  • window.alert()
    • Data displayed using an alert box
  • document.write()
    • Data is written into the HTML document output
  • innerHTML()
    • Data is written into an HTML element

Syntax & Grammar

JavaScript is case-sensitive: myFunction and MYFUNCTION are not the same. It uses the Unicode character set. For more information on this character set, visit here.

Statements

A statement is an instruction given to the computer. A script consists of a series of statements specifically ordered to achieve a goal (like a recipe). Here are a few things to keep in mind regarding statements:

  • New Lines
    Every statement should start on a new line.
  • Semicolons
    Each statement should end with a semicolon; this tells the interpreter to complete this step and commence with the following statement.
  • White space
    White space consists of tabs, spaces, and new line characters
    White space between words and tabs are ignored
    Utilize white space to make your code easier to read
    Example:
    var car =“Toyota”;
    var car = “Toyota”; → Easier to read
  • Line Length
    Keep code length to 80 characters or shorter, to maximize readability
  • Line breaks
    Ignored except when found in a statement
    For multi-line statements, breaks should be used after operators (e.g., =, +, -)
    Example:Document.getElementById(“example”).innerHTML =
    “Insert New Text Here”;
  • Code Blocks
    Code blocks organize related statements within curly braces { } and make them easier to read
    Closing curly bracket is not followed by a semicolon
    JavaScript functions are often in code blocks
    Example:

    
    function myBirthday {
    	alert(%u201CHappy Birthday!%u201D);
    	Document.getElementById(%u201Cmessage%u201D).innerHTML = 
    %u201CYou%u2019re one year wiser!%u201D;	
    } 
    

     

Naming Convention

Camel Case

Convention dictates that JavaScript utilize CamelCase for identifier names (variables and functions). Also, all names should start with a letter.

Ex: myFunction, namingConvention

Values

JavaScript has two types of values: Fixed and Variable

Fixed (AKA Literals)Variables
Numbers
Decimals are optional
15.25 → Correct
1500 → Correct
Strings
Consist of text, contained within single or
double quotes
‘Jenny Smith’ // in single quotes
“Jenny Smith” // in double quotes
These act as containers for storing values
Stored data can change (think back to Algebra class)
The var keyword must be used to define/declare a variable
Values are assigned to variables with an equals sign
var age; // declare the variable
age = 30; // assign a value

* There will be more information regarding literals and variables later in the tutorial.

Comments

Inserting comments in code is highly recommended for multiple reasons:

  • Makes it easier for others to read and understand your code
  • Helps you remember what your code does and your thought process behind it
  • Prevents execution while testing alternative code

Single-line Comments

For comments spanning only a single line, you need to place // before the comment. The JavaScript interpreter will not process anything following the slashes.
Example:


//This is a single-line comment.
Alert(%u201CHappy Birthday!%u201D);

Multi-line Comments/Comment Blocks

For comments running across multiple lines, you must precede the text with /* and follow it with */. The enclosed text will not be processed by the JavaScript interpreter.
Example:


/*This comment is longer than
one line because I have a lot to
say about this section of code.
*/
function myBirthday {
Alert(%u201CHappy Birthday!%u201D);
Document.getElementById(%u201Cmessage%u201D).innerHTML =
%u201CYou%u2019re one year wiser!%u201D;
}

Variables

As mentioned previously, JavaScript variables are used for storing data values.

Declaring Variables

The first step in using variables is declaring them, which lets the interpreter know you want to use them. To do this, you have to use the var keyword.
Example:


var quantity;
var x;
var myAge;

 

Identifiers

In the examples above, the variable names, also called identifiers, are quantity, x, and myAge.
Identifiers must be unique and follow these general guidelines:

  • Must begin with a letter, underscore, or a dollar sign
  • Digits (0-9) can be used
  • Are case-sensitive
  • Cannot be reserved words, such as JavaScript keywords (more on reserved words in the next section)

Assignment

You can assign a value to a variable with the assignment operator, the equals sign (=).
Example:


var quantity = 10;
var x = 12;
var myAge = 30;

Before assignment, an existing variable is referred to as undefined.

Initialization

Initialization only occurs when a variable is assigned a value for the first time.

Mutability

You can also change the value of an existing variable with the assignment operator.

var quantity = 10;

var quantity = 20;

This code changes the value of the variable quantity from 10 to 20.

Data Types

Strings

  • Surrounded by single or double quotation marks
  • Can contain letters and other characters: e.g., ‘Good Morning!’
  • Special Characters

\ escape character

Confusion can arise in JavaScript code when dealing with strings and internal quotation marks, because all strings must reside inside quotes. JavaScript interpreters may see internal quotes as beginnings or ends of strings.
To avoid problems such as this, we can utilize the \escape character, which transforms special characters into string characters.

Examples:
var greeting = “What\’s up?”;
var question =  ‘Have you read \”The Hobbit\”?’;

  • Here are some additional special characters that can be used as string characters with the use of \escape:\\                   backslash
    \b                  backspace
    \n                  go to a new line
    \t                   tab

Numbers
Whole Numbers: e.g., 10
Decimals: e.g, 0.9
Negative Numbers: e.g., -278
Scientific Notation: 123e-5
Note: If you put numbers in single or double quotation marks, the values will be interpreted as strings

Booleans
Two possible values: True or False
Can be used to specify when certain parts of code should execute

Arrays
Contains a list of values
The list is enclosed in brackets
Values have quotations around them, and are separated with commas
Example:
var colors = [“White”, “Blue”, “Green”];
Array indexes are zero-based, meaning the index position of the first item is 0. In the example above, the index position of “White” is 0, and that of “Green” is 2.

Objects
Each object has properties and behaviors
Represented as name:value pairs, separated by commas
Enclosed in curly brackets
Example:
var car = {carMake: “Toyota”, carModel: “Prius”, year: 2012, extColor: “black”};
The object car, above, has the properties carMake, carModel, year, and extColor.

Symbol

Unique and immutable data type
Added as a new data type in ECMAscript6
Can be used as a unique, non-string identifier for object properties, which prevents name collision (more on objects and properties later in the tutorial);
You must use the symbol function to create a symbol (we will discuss functions in a later section)

Example:

var firstName = Symbol( );

This code ensures that the property firstName will have a unique, non-string symbol identifier.


Undefined

As mentioned previously, an undefined variable has not been assigned a value
Value is undefined
You can change a variable’s value to undefined by assigning it the value undefined
Note: An empty string is not undefined. It has a value and type. The example below has the type string and the value “ ”.
Example:
var person = “ ”;
You can set an object to the value undefined, which will also change the type to undefined

Null
Equivalent to does not exist
A quirk of JavaScript is that null’s type is object, instead of null
You can set an object’s value to null, though the type will still be object
Null and Undefined are not the same

Dynamic Data Types

JavaScript Data Types are dynamic, which means a variable can be used as different types:
Examples:


var x = 12; (Type is number)
var x = "Car";  ( Type is string)
var x; (Type is undefined)

typeof Operator

The typeof operator allows you to determine a variable’s type:
Examples:


typeof {carMake: %u2018Toyota%u2019, year: 2012}   (Returns object)
typeof %u201CJohn%u201D                            (Returns string)
typeof -750                                        (Returns number)

Note: JavaScript considers an array a special object. As a result,
the use of the typeof operator on an array will return an object.

typeof [%u201Cred%u201D,%u201Dwhite%u201D,%u201Dblue%u201D] (Returns Object)

Expressions

Expressions can either assign a value to a variable or reduce multiple values to a single one.

Assignment

var person = %u2018Jenni%u2019;

* This expression assigns the value Jenni to the variable person.

Evaluation

var sum = 5 + 5 + 0;

*This expression evaluates to 10.

Sequence
Expressions in JavaScript evaluate from left to right. Sequence matters!

Examples:

var x = 98 + 1 + “Red Balloons”

*Evaluates to 99RedBalloons.
*The first two values are evaluated as numbers and then added to the string.

var y = “Red Balloons” + 98 + 1

*Evaluates to Red Balloons981.
*Because the expression starts with a string, all of its values are treated as strings.

One Statement, Multiple Variables

You are not limited to one declaration per statement. For multiple declarations in one statement, begin with the var keyword and use commas to separate the unique variables. Also, a declaration can use more than one line.
Examples:


var student = %u201CJohn%u201D, studentScore = 100;
var student = %u201CJohn%u201D,
var studentScore = 100;

Reserved Keywords

Reserved words in JavaScript cannot be used as identifiers because they have specific meanings. Current reserved JavaScript keywords are listed below:

  • break
  • case
  • catch
  • class
  • const
  • continue
  • debugger
  • default
  • delete
  • do
  • else
  • export
  • extends
  • finally
  • for
  • function
  • if
  • import
  • in
  • instanceof
  • let
  • new
  • return
  • super
  • switch
  • this
  • throw
  • try
  • typeof
  • while
  • with
  • yield
  • var
  • void


Future Keywords

These keywords do not currently have intrinsic JavaScript meanings, but they might in the future. Therefore, these also cannot be identifiers.

  • enum
  • await

These are reserved as future keywords only when in strict mode. Strict mode places restrictions on code in order to improve error-checking.

  • implements
  • interface
  • package
  • private
  • public
  • protected
  • static

Also, avoid using names of inherent JavaScript functions or objects as identifiers (e.g., string).

Operators

Operators and Operands

When evaluating mathematical expressions, the numbers are called operands. And, the specific operation is carried out with an operator.
Example:

100+75
OperandOperator Operand

 Mathematical Operators

Mathematical operators can be used with numbers in literal or variable form.

Addition (+)
Adding numbers
Example:
var x = 10;
var y = 20;
var z = x + y
*evaluates to 30

Subtraction (-)
Subtracting numbers
Example:
var x = 10;
var y = 5;
var z = x – y;
*evaluates to 5

Multiplication (*)
Multiplying numbers
Example:
var x = 10;
var y = 5;
var z = x * y;
*evaluates to 50

Division (/)
Dividing numbers
Example:
var x = 10;
var y = 5;
var z = x/y;
*evaluates to 2

Modulo/Modulus (%)
Finding remainder after division
Example:
var x = 101;
var y = 2;
var z = x % y;
*evaluates to 1

Increment (++)
Incrementing numbers by 1
Example:
var x = 1;
x++;
var y = x;
*evaluates to 2

Decrement (–)
Decrementing by 1
Example:
var x = 2;
x–;
var y = x;
*evaluates to 1

Precedence

Arithmetic Operator Precedence

When evaluating arithmetic expressions, it’s crucial to know the proper order of precedence for various types of operations.
Here is a list in order from most to least important:
( )
Evaluate everything within parentheses
++ --
Increment and Decrement
* / %
Multiply, Divide, and Perform Modulo Division
+ -
Add and Subtract

Examples:
var x = (200 / 2) – 3 % 2;
*First, perform operation in parentheses, which evaluates to 100
*Second, perform the modulus operation, which evaluates to 1
*Finally, subtract 1 from 100, with a result of 99

Assignment Operators

You can change the value of a variable unlimited times, by using assignment. Simply set a variable (no need to use the var keyword since the variable was already declared) to a value using the equal sign.
Example:
var car = Toyota
car = Honda
*The variable car’s new value is Honda

In addition to the equals sign assignment operator, there are five more Assignment Operators, which give values to JavaScript variables.

+=

This operator adds the value to the right of the operator to the value on the left of it.
Example:
var x = 1;
x += 10; // same as 10 + 1
*evaluates to 11

-=

This operator subtracts the value to the right of the operator from the value on the left of it.
Example:
var x = 10;
x += 1; // same as 10 – 1
*evaluates to 9

*=

This operator multiplies the value to the left of the operator by the value on the right of it.
Example:
var x = 10;
x *= 1; // same as 10 * 1
*evaluates to 10

/=

This operator divides the value to the left of the operator by the value on the right of it.
Example:
var x = 10;
x /= 1; // same as 10 / 1
*evaluates to 10

%=

This operator initiates the modulo operation using the values to the left and right of the %= operator

Example:
var x = 10;
x %= 3; // same as 10 % 3
*evaluates to 1

String Operators

Concatenation

You can also add strings to each other. This process, linking strings end-to-end, is called concatenation, and can be used with literals and variables.
Examples:
var fullName = “Shilpa” + “ ” + “Kumar”
The expression evaluates to Shilpa Kumar
Without the middle value of “ “, the expression would evaluate to ShilpaKumar, because concatenated strings are joined end-to-end


var firstName = “Shilpa”;
var lastName = “Kumar”;
var fullName = firstName + “ “ + lastName

* evaluates to Shilpa Kumar

var numberString = “19” + 9 + 9
Evaluates to 1999
Remember that numbers added to a leading expression value with a string type will be treated as strings.

The += Assignment Operator

This operator can also be used for concatenation.
Example:
greeting1 = “Hello, “;
greeting1 += “Abraham.”; // Same as greeting1 + “Abraham.”
*Evaluates to Hello, Abraham.
*Note the space after the comma in greeting1. Remember: Strings are concatenated end-to-end without spaces, so you have to include them in the strings to be concatenated, if necessary.

Comparison and Logical Operators

Value comparison is important for correct code execution. This process uses Logic, which entails the use of a Boolean, which we discussed earlier. This means only two outcomes are possible: true or false.

There exist a group of operators that solely involve Booleans. They compare their left-side and right-side values and return a Boolean value: true or false.
Here is a list of JavaScript’s Comparison Operators:

== equal to // loose equality

Returns true if the left-side and right-side values are identical, regardless of type.
“21” == 21 // returns true, even thought “21” is a string, and 21 is a number
[2 , 4] == “2,4” // returns true, even though [2 , 4] is an array and “2, 4” is a string

=== equal value and type // strict equality

Returns true only if values and types are identical.
“10” === 10 // returns false because “10” is a string, and 10 is a number
[1, 2, 3] === [1, 2, 3] // returns true because values and types are identical

Note: In the vast majority of cases, you should use === strict equality when comparing for equality.

!= not equal

Returns true if values are not identical.
x = 10;
x != ‘10’ // returns false because the values of x (10) and ‘10’ are identical, despite the difference in types.

!== not equal in value or type

x = 10;
x !=== ‘10’ // returns true because the types are different, x (10) is a number, and ‘10’ is a string—despite the identical values.

> greater than

returns true if the left operand is greater than the right operand
8 > 10 // returns false

< less than

returns true if the left operand is less than the right operand
8 > 10 // returns true

>= greater than or equal to

returns true if the left operand is greater than or equal to the right operand
10 >= 10 // returns true

<=  less than or equal to

returns true if the left operand is less than or equal to the right operand
9 <= 10 // returns true

Logical Operators

Logical operators are used when comparing the results of multiple comparison operators.

&& (Logical And)

Only returns true if all conditions are met.
(( 4 > 2 ) && (5 <= 5)) // returns true because both comparisons return true

|| (Logical Or)

Returns true if at least one condition returns true
((5 < 1) || (1 = 1)) // returns true because the right-side condition is met

! (Logical Not)

When preceding an expression, It reverses its meaning.
!(5 >= 5) // returns false because the expression originally returned true when it didn’t have the !

Type Coercion

JavaScript sometimes automatically uses the process of type coercion to change a value’s data type in order to complete an operation.

Example:

‘10’ < 100 // The string ‘10’ could be coerced into a number data type to return true for this expression.

Type Coercion could lead to errors and unexpected values. To avoid these pitfalls, it is recommended that the strict equal operators === and !== be used when comparing two values.

Conditionals

As mentioned earlier, computers use Logic to run appropriate pieces of code at the right times, based on results of comparisons. In order to facilitate this process, we must use conditionals—statements that dictate actions to be taken after comparisons.

If Statements

If a condition is met, a particular code block should run.

Example:

If (4 > 2) {
Since the condition is met, code in this block should execute.
}

If-else Statements

Similar to the If statement. However, if the condition is not met, instead of simply not executing the if code block, an alternative code block runs.
Example:
If (4 < 2) {
Run this code block.
}
Else {
Run this code block, instead.
}

Else-if Statements

An else-if statement only executes if the previous condition is not met. If the else-if statement condition is not met, the else statement following it will execute.

Example:

if (4 < 2) {
Run this code block.
}
else if {
Run this second code block.
}
else {
Run this third code block.
}

Switch Statements

The variable—the switch value—determines which case to execute. The
switch statement lives in a single code block, with semicolons separating the cases from each other. A default option runs if the switch value does not match any of the cases.
Example:
var greeting;
var day = ‘Monday’;

switch(day) {

case ‘Monday’:
greeting = ‘Happy Monday!’;
break;

case ‘Friday’:
greeting = ‘TGIF!’;
break;

default:
greeting = ‘Good Morning!’;
break;
}

* If the switch value were Monday, case ‘Monday’ would execute, changing the greeting to Happy Monday! Then, the break keyword at the end of that case would tell JavaScript that it is done with this switch statement and can move on.

Loops

Loops allow you to repeat a code block until it returns false. Three types of loops are commonly used.

For Loop

The For Loop, the most common type of loop, allows you to run the code a specific number of times, and keeps track of the number of loops through the code block.
Here is the structure:


for (var i = 1; i < 10; i  ) {
This code runs. 
}	

Let’s dissect the For Loop:

As you can see, like an if statement, there is a condition to be met,
within parentheses. This condition has three parts. The for keyword
always begins for loops in JavaScript.

var i = 0; initializes the variable and sets it to 0. As a convention, var i is used, though you can name the variable anything you would like (e.g., var x, var taco). The reasoning behind this convention deals with the fact that the for loop is often used to loop through an array—a list of values which have assigned index positions, starting at 0.

As you may have guessed, the i in var i is short for index.
We will dive deeper into arrays later in the tutorial.

i < 10sets a condition for how many times the loop can run.

As long as the variable i is less than 10, the code block will run. A variable with the value of a number can also be used in place of a literal number.

Now, let’s examine the final part of the condition, i++; It increases the count of any number by 1. So, i++ increments the var i by 1 each time the loop runs.

The loop will run until var i reaches the value 10, at which point the code block will stop running.

While Loop

A while loop repeats a code block until a condition returns false. You would apply this when you do not have a specific number of
desired loops, or when you want to loop while a certain condition proves true.

Examples:


var x = 0;
var y = 1;

while(x < 10) {
x++;
y--;
}

In this example, we see that the while loop will run continuously until the variable x reaches 10, with x++ incrementing x by 1 and y– decrementing y by 1 each time the loop runs.

 

Do While

This type of loop is like a while loop, but will run a code block at least once, regardless of whether or not the specified condition is met. Example:


var count = 20;

do {

alert(%u201CLoop de loop!);
count  ;

} while (count < 20);

Note that in the Do While loop, the code block precedes the condition, ensuring that the code will execute at least once.
Even though the condition is not met, the code will still run the first time through the loop.

Infinite Loops

If you run a loop with a condition that never returns false, an infinite loop will result. The code block will keep executing until your browser runs out of memory. You definitely want to avoid this situation. The accidental omission of a counter can lead to an infinite loop.

Functions

A function consists of a reusable code block containing statements aimed at completing a particular task.

Syntax

You create—or declare—a function with the function keyword, which precedes the function name, which is followed by parentheses. The code block follows, enclosed in curly brackets.
Example:


function myFunction ( ) {
code block
}

Function Names

Like variable names, function names can contain letters, digits, underscores, and dollar signs.

Calling/Invoking a Function

You can call or invoke a function, thereby allowing its code to run, by using the function name followed by parentheses and a semicolon:
Example:
myFunction( );

Parameters and Arguments

Information provided to functions are called parameters, which are separated by commas. Parameters are names, while arguments are the actual values passed to functions.
Examples:


function areaRectangle (width, height) {
alert (“The area is  ” + (width * height) + “  feet.”);
}
areaRectangle(10, 20);

In the first example, the parameters of width and height have been passed to the function. In the second example, the arguments 10 and 20 have been passed to the invoked function.
Note: Arguments can also be variables.

Return Statement

In JavaScript, a return statement halts the running of a function and returns the resulting function value. Also, returned values can be stored in variables.

Example:


function addNumbers(a, b) {
    	return a + b;
}
var x = addNumbers (2, 4);

When the function hits a return statement, we exit the function after the value is returned. The returned value of 6 will be stored in variable x.

Functions in Variables

Functions can be saved as the value of a variable. And, you can call/invoke
the function by using the variable name followed by parentheses.
Example:


var subtract = function (a, b) {
return a - b;
}
var answer = subtract(5, 3);

The parameters a and b are passed to the function.
In the code block, the return keyword shows that the value of a – b will be
returned before the code stops execution. In the last line, we see that the subtract function is called, with the arguments 5 and 3. The returned value
of 2 is then stored in the variable answer.

Anonymous functions

A function without a name is called an anonymous function.
Functions stored in variables do not need function names because they are invoked with the variable names. Because these functions stored in variables reside where expressions normally would, they are called function expressions.
Example:


var area = function(width, height) {
return width * height;
};
var answer = area(5, 10);

 

Variable Scope

Variable location dictates your ability to use them.

Local Variable/Function-level Variable

  • When you initialize a variable within a function using the var keyword
  • You can only use this variable within this function
  • Has Local/Function-level Scope
  • Is deleted upon function completion
  • Different functions can share local variable names because each local variable does not affect the space outside of its function
  • Function parameters act as local variables

Global Variable

  • A variable initialized outside of a function
  • Can be used anywhere
  • Has global scope
  • Is deleted when the page is closed
  • Caution: can cause naming conflicts
  • Caution: any variables not declared with the var keyword automatically become global in scope

Example:


function findSum(num1, num2) {
var sum = num1 + num2;
return sum;
}
var answer = findSum (2, 5);

*var sum is a local variable because it was declared within the function, with the var keyword
*var answer is a global variable because it was created outside the function

Objects

Objects allow for the organization of JavaScript variables. A JavaScript object has properties, just like a real-life object. If a property relates to an object behavior and has a function as its value, this property is called a method—an action that an object can perform or that can be
performed on the object.
JavaScript has built-in objects, and you can create your own. Also, objects can be variables. And, JavaScript objects cannot be compared to one another.
Each object property and method has a name and value. For JavaScript objects, names are called keys. Objects can only hold unique key names, because each key is related to a particular value. A property value can be a string, number, Boolean, array, or another object. A method’s value is always a function. Object properties and methods reside within curly brackets.
Example:


var Car = {
make: Honda
model: Fit
year: 2012
talk: function(){
alert(%u201Cvroom, vroom!%u201D);
}
};

make, model, and year are variables called properties.
talk is a method— a type of property whose value is a function.

Accessing Properties and Methods

Object properties and methods can be accessed via the dot syntax.
To access an object property:
objectName.propertyName
To access an object method:
objectName.methodName()
car.make;
Honda
car.model;
Fit
car.talk();
an alert box pops up with the phrase “vroom, vroom!”

Property Reassignment and Creation

reassign object properties

car.make = “Toyota”;

Create new properties

car.color= “black”;

Nested Objects

Create an object to be another object’s property

var person = { hair: “blonde”, eyes: “brown” }; person.name = { first: "Paris", last: "Jones" };
You can also create an empty object and then give it properties and methods
var person = {}; person.hair = {“brown”}; person.talk = function () { alert("Hello!"); };

Built-in Objects

JavaScript has some built-in objects with useful operations.

Math Object

The Math object has methods for various types of calculations, such as the following:

Math.log() – returns the natural logarithm
Math.random() – returns a random number between 0 and 1
Math.round() – rounds to the nearest integer
Math.sqrt() – returns the square root

Date Object

The Date object provides the day, date, and time information. Format: dateObject.method()
Example Methods:
getFullYear() – returns the four digit year
setDate() – Set the day as a number (1-31)
Create New Date Object (with new keyword):
new Date( ) – creates new date object with current date and time

String Object

The String object possesses numerous properties and methods, such as the following:

Property

Format:    stringName.property()

length() – length of a string

Methods

Format: stringName.method()

charAt() – Returns the character at the specified index position (0-based index)
indexOf() – returns the index position of the first occurrence of a particular character in a string; returns -1 if the character is not found
replace() – replaces a specific value in a string with another one
search() – searches within a string for a particular value and returns the index position

If a parameter is negative, the position is counted from the end of the string. Note: Internet Explorer 8 and its earlier versions do not support negative positions.

toLowerCase() –  returns a string with all letters in lowercase
toUpperCase() – returns a string with all letters in uppercase

Note: String methods do not change original strings; they simply return new ones.

Number Object

Properties

Format: Number.PROPERTY

MAX_VALUE – returns largest possible value for a JavaScript number
MIN_VALUE – returns smallest possible value for a JavaScript number
NEGATIVE_INFINITY – represents negative infinity
POSITIVE_INFINITY – represents positive infinity
NaN – represents a “Not-a-Number” value

Methods

Format: Number.Method

variableName.toString()
literal.toString()
toExponential()  – returns string with number in exponential notation
toFixed() – returns string with number with a specified number of decimal places
toPrecision() – returns string with a number possessing a specified length
toString() – returns number in string form
valueOf() – returns value of number

Note: Number methods do not change the original variable.

Global Methods

These methods apply to any data type in JavaScript. The following methods can be used with numbers.

Number() – returns number value of converted variables
Examples:
Number(true); – returns 1
Number(false); – returns 0
Number(“10”); – returns 10

parseInt() – returns an integer after parsing a string and returns a whole number. Only the first number is returned.
Examples:
parseInt(“25”); – returns 25
parseInt(“25.5”); – returns 25
parseInt(“25 30 35”); – returns 25
parseInt(“25 miles”); – returns 25
parseInt(“miles 25”); – returns NaN because conversion is not possible

NaN

NaN is a JavaScript reserved word to identify a non-number value. Here are some instances of NaN values:
Mathematical calculations with non-numeric strings:
Examples:
var sum = 10 + “Chevy”; – returns NaN
*If the string had contained a numeric value, a number would have been returned.

Mathematical operations with NaN:
var num1 = NaN;
var num2 = 10;
var Sum = num1 + num2;

*Note: Interestingly, NaN is a number, and typeof NaN returns “number”.

isNaN( ) Method
This function determines whether a value is NaN
Example:
isNaN(“string”); – returns true

Arrays

Arrays are lists consisting of any data type. Every array item has an assigned index number, starting with 0. Indices allow for easy retrieval of an array item—called an element.

Creating Arrays

Array-literal Syntax
var newArray = [ ];
var bestFriends = [‘Dan’, ‘Marcy’, ‘Corey’];

Using the JavaScript Keyword new
var bestFriends = new Array(‘Dan’, ‘Marcy’, ‘Corey’];
*For efficiency, it’s much better to use the Array-literal Syntax when creating new arrays.

Retrieving Array Elements

  • Square-bracket Syntax

bestFriends[2]; – returns Corey, who is at index position 2 in the bestFriends array
Setting Array Values
bestFriends[1] = ‘Becky’; – replaces ‘Marcy’ with ‘Becky’ in the bestFriends array, because she was in index position 1

Properties

  • Length

bestFriends.length; – returns 3, the number of elements in the array

Methods
Arrays have many useful methods. Here are some of the most popular ones.

  • Push
    bestFriends.push(‘Paris’); – adds ‘Paris’ to end of bestFriends array
  • Pop
    bestFriends.pop(); – removes the last element in the array
  • Sort
    bestFriends.sort(); – sorts array elements in alphabetical order

*In arrays, spaces and line breaks are not important. A declaration can span multiple lines:

One Array Can Hold Different Types of Objects
Because arrays are special types of objects, they can hold variables of differing kinds, such as functions, objects, and arrays, simultaneously.
Example:
var testArray = [“tree”, 12, [1, 2, 3]];

Arrays are Special Objects
Though JavaScript objects usually use named indexes, to be used with strings, arrays used numbered ones. The typeof operator returns object, because an array is a special type of object.

Looping Through Array Elements
As previously mentioned, the for loop is frequently used to loop through an array.
Example:
var names = [“Eli”, “Niamh”, “Arebeth”];
for(var i = 0; i < names.length; i++) {
alert(“Hi ” + names[i]);
}

Primitive Value

Primitive values lack object status and methods. In JavaScript, there exist 6 primitive data types: string, number, symbol, Boolean, null, and undefined. Primitives cannot be changed.

Primitive Wrapper Objects
All primitive values, with the exception of null and undefined, possess wrappers around them that are object equivalents. When applying the valueOf( ) method, the primitive value is returned.

Creating Objects

Object Literal
Literal Notation is the most widely used method of JavaScript object creation.
The object is stored in a var with a name, and consists of key:value pairs, with properties and methods separated by commas.
Example:


var person = {

firstName: %u201CAbraham%u201D,
lastName: %u201CHall%u201D,
age: 31,
hairColor: %u201Cblack%u201D

};

Note: Line breaks and spaces do not affect the code.
Constructor Notation
You can also create JavaScript objects with the new keyword and the object constructor. This method results in the creation of a blank object, which you can then add properties and methods to.
First, you create a variable that has a value combining the new keyword and object constructor.
var car = new Object( );
Now, you can add properties and methods with dot syntax.


car.make = ‘Hyundai’;
car.model = ‘Sonata’;
car.talk = function() {
alert(“Vroom, Vroom!”);
}

Note: Avoid declaring Strings, Numbers, and Booleans as objects. These objects would cause a lag in execution time and unnecessarily complicate code.

Intermediate Topics

This Keyword

The this keyword refers to one object, typically the one a function operates within.

Window Object

A function not residing inside a function or another object is referred to as being in global scope or global context. For these functions, the default object is the window object. When the keyword this is used in global scope, it refers to the window object.

Example:


Function windowSize( ) {

	var height = this.outerHeight;
	var width =  this.outerWidth;

return [height, width];

}

*Above, the this keyword returns the height and width values for the window object, which this global function resides within

Global variables automatically become properties of the window object. Therefore, a global function can access all global variables and other window object properties, by using the this keyword.

Example:


var firstName = "Camilo",
var lastName = "Arevalo";

function name () {
// "this" inside this function will have the value of the window object​
// because the showFullName () function is defined in the global scope, just like the firstName and lastName​
console.log (this.firstName + " " + this.lastName);
}
​


*The this keyword in this context refers to the window object. Therefore, the function is able to access the firstName and lastName global variables within the window object.

Functions Inside Objects

A function defined within an object becomes a method, which utilizes the this keyword to refer to the object it resides within.

Example:


var house = {
       windows: 20,
       doors: 3,
       totalSum: function( ) {
     return this.windows + this.doors;

}
);
​

*The this keyword refers to the object which it lives within the house object.
*In the case of using an object constructor to create new instances of the object with different property values, the this keyword points to that particular instance of the object. (We will discuss object constructors and instances later in the tutorial.)

Function Expressions

When an object uses a named global function as a method, the this keyword applies to the object to which the function expression has been assigned as a method.

Example:


var windows = 10;
var house = {windows: 20};

var totalWindows = function ( ) {
return this.windows;

};

house.numWindows = totalWindows;
house.totalWindows( );
​

*The this keyword in the totalWindows function refers to the house object and its windows property because the function expression has been assigned as a method on the house object. The second-to-last line shows this assignment action.

Form Validation

Form validation usually occurs on the server’s end, after a client sends necessary data by pressing the Submit button. If there are issues with the data entered, the server has to return the data back to the client and request a re-submission of data, which leads to a longer, more burdensome process.

JavaScript can perform HTML form validation on the client side, which saves time and server resources.

Form validation performs two general tasks:

  • Basic Validation // Checks for completion of any mandatory fields
  • Data Format Validation // Checks for correct value and form

The BOM

The Browser Object Model, or the BOM, consists of the objects in the browser that JavaScript can access.
The Window object—representing entire browser (including toolbars, menus, the page itself, etc.)—lies at the top of the BOM hierarchy. Below the Window object, on the hierarchy, numerous objects can be accessed.
Note: Two objects must be separated by a dot.
window.document
– access all HTML elements
window.history
– gain information regarding browsing history
window.innerHeight and window.innerWidth
– gets the height and width of the available space on the page
window.screen
– retrieves information about the browser screen
window.navigator
– gets information about the browser
window.location
– mainly used to redirect someone to a different page

Window Methods

Here are the main methods:
window.alert(“Alert Message”) – an alert message pops up
window.confirm(“OK or Cancel”) – a confirmation box pops up
window.prompt() – a prompt box appears
window.open() – opens a new window
window.close() – closes a window

Window Properties

There are two main window properties:
• status – set the status bar message
• self – stores the name of the current window

The DOM

The DOM, or Document Object Model, is a standardized structure of the elements within your web page as it is currently loaded in the browser.
Here is an example of what a simple DOM looks like, based on the following code:


<!DOCTYPE html>
<html>
<head>
	<title>%u201DMy Title%u201D</title>
</head>

<body>
	<a href=%u201D%u2026%u201D>My Link</a>
	<h1>My Header</h1>
</body>
</html>
​

The DOM:

image03

The document object is powerful and possesses its own unique properties, methods and events (we will discuss events in an upcoming section), which allow programs and scripts to access and manipulate elements within your web page. With the DOM, you can create a document; navigate through its structure; and create, amend or delete elements or content.

In the Document Object Model, your web page has a logical tree-like structure. Each component of the tree is called a node. There are various types of nodes:

  • Document Node: The document itself
  • Root Node: The top element, which has no parent (the HTML node in the example above)
  • Element nodes: HTML elements
  • Attribute nodes: HTML attributes
  • Text nodes: Text within HTML elements
  • Comment nodes: Any comments within the document

The previous example shows 4 types of nodes: root, element, attribute, and text. Parent nodes have nodes descending directly from them, such as the Element node for <p> (in the above example), which has a child Text node. Nodes that align laterally are referred to as siblings, such as the Attribute nodes for <p> and <h1> in the image above.

Accessing and updating the nodes involve a couple of easy steps:

Step 1: Locate the element(s) you want.
Step 2: Use method(s) to work with its content.

Step 1:
Here are some common methods for locating an individual element:

getElementById() – targets the element’s unique id attribute
querySelector() – targets the element’s CSS selector

You can also select multiple elements using:

getElementsByClassName() – selects all elements with specified class
getElementsByTagName() – selects all elements with specified tag
querySelectorAll() – selects all elements with specified CSS selector

Step 2:
Here are some of the many methods and properties you can use to work with elements within the DOM, after you have selected the nodes you want to manipulate:

createElement() – allows you to create an element
hasAttribute() – checks if an attribute exists
getAttribute() – gets the value of attribute
setAttribute() – sets the value of an attribute
removeAttribute() – removes an attribute from an element
innerHTML() – changes the text within an element

Events and Callbacks

Events

Events are things that occur—usually user actions—and are related to objects.

Event Handlers
Allow you to specify what event you want to watch for. There are two types of event handlers:

  • HTML Event Handler:
    Not recommended because it’s better to separate HTML and JavaScript
    Entails responding to events occurring on a particular HTML element by adding an attribute to it:
    Example:
    <button onclick = “hide( )”>
    *This event handler indicates that when someone clicks this <button> element, the hide function should be called.
  • DOM Event Handler:
    Allows you to separate HTML and JavaScript
    Binds an event to a DOM element
    Can only attach one function to an event
    Example:
    Function hide() {
    //code to hide element
    }
    var el = document.getElementById(‘button’);
    el.onclick = hide;
    *A reference to The DOM node is often
    stored in a variable.
    *This Event Handler indicates that a click is the awaited event.
    * In the last line, the function is called.

Event Listeners

After a particular event occurs, a specific function executes.
Events commonly listened for:

• onLoad – page is loaded
• onMouseOver – cursor sits atop a target object
• onMouseOut – cursor leaves the targeted object
• onSubmit – a form is submitted
• onClick – user clicks target

Can work with more than one function at a time
Not supported in older browsers
Takes 3 parameters
Example:
Function hide( ) {
// code to hide an element
}
var el = document.getElementById(‘button’);
el.addEventListener(‘click’, hide, false);

*The first parameter for addEventListener is the event to look for; the second one is the function name; and the third one is a Boolean, which is usually set to false and relates to Event Flow.
Can also turn the second parameter into an anonymous function to enable passing of parameters

Callbacks

The function called by the browser when a particular event occurs is called a callback.

Example:

var clickAction = function(event) {

//code here

};

var button = document.getElementByID(‘#button’);
button.addEventListener(‘click’, clickAction);

*In the above example, the callback function is clickAction.

JSON

JSON, (JavaScript Object Notation), pronounced Jason, is used to send complex data between the server and the browser. It is a set of text formatting rules allowing for storage and transfer of data in a manner easy for computers and humans to understand.

Since servers only ‘talk’ through the exchange of information formatted as strings, JSON will convert any data structure (or combination of data structures) into strings, and then back again. Additionally, it is very easy to implement.

  • Conversion to string is through JSON.stringify
  • Conversion to JavaScript object is through JSON.parse

Syntax

  • Data stored in name/value pairs
  • Data separated by commas
  • Objects encapsulated in curly brackets
  • Arrays encapsulated in square brackets

Example:


> var han = {name: %u201CHan Solo%u201D};
> han
   => Object {name: %u201CHan Solo%u201D}

> var jsonHan = JSON.stringify(han)
> jsonHan
   => "{"name":"Han Solo%u201D}%u201D```
​

Here, we give an object (containing the key/value pair of ‘name’: ‘Han Solo’) the name ‘han.’ We then used this object as a parameter for the JSON.stringify()’ function, which resulted in the saving of “{“name”:”Han Solo”}”.


> var han = {
  comrades: [
    {name: 'Chewbacca'},
    {name: 'Leah'},
    {name: 'Luke'},
    {name: 'Lando'}
  ],
  ship: 'Millennium Falcon',
  profession: 'Smuggler'
};
> han
    => Object {comrades: Array[4], ship: "Millennium Falcon", profession: "Smuggler"}

> var jsonHan = JSON.stringify(han)
> jsonHan
    => "{"comrades":[{"name":"Chewbaca"},{"name":"Leah"},{"name":"Luke"},{"name":"Lando"}],"ship":"Millennium Falcon","profession":"Smuggler%u201D}%u201D```
​

Ajax

AJAX (Asynchronous Javascript And XML) sends and receives information from a server asynchronously, which allows for rapid updating of a portion of a website without a full page reload.

Ajax utilizes the XMLHttpRequest object, which allows exchange of data asynchronously with a server.
To send a server request, the open() and send() methods of the XMLHttpRequest object are used:


xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
​

For the first function, the first parameter specifies whether the request
type is GET or POST. The second parameter provides the file location on the server. And, the final parameter will be true for asynchronous or false for synchronous.

Advanced Topics

Object Constructors

Object constructors allow us to create several objects of the same type.
The standard way to create an “object type” is to use an object constructor function:
Example:


function house(color, squareFeet, year) {
    this.color= color;
    this.squareFeet = squareFeet;
    this.year = year;
}
var jenniHouse = new house("Green", 2500, 1978);
var karenHouse = new house("White", 3000, 1901);
​

*The function named house acts as an object constructor, which allows the creation of new instances of the house object.

Prototypal Inheritance

In JavaScript, an object can inherit properties and methods from another object, using prototypal inheritance. When an object inherits from another object, we refer to the parent object as the child object’s prototype.

After seeking a particular object property and not finding it, JavaScript climbs the prototype chain to find it—and returns undefined if the attempt to find the property is unsuccessful.

More than one object can inherit from a single object, but a single object cannot inherit from multiple objects. The aforementioned constructor function constitutes the most popular method for achieving inheritance.

Libraries

JavaScript Libraries, also called JavaScript Frameworks, help developers successfully deal with various types of challenges with advanced JavaScript programming. A library is not always necessary or recommended, and frameworks should be chosen for their suitability for a particular goal.

jQuery

jQuery is the most widely used JavaScript framework. It simplifies many common JavaScript activities.

  • Selecting Elements
    jQuery utilizes CSS-style selectors to manipulate the DOM
  • Events
    jQuery methods allow easy attachment of event listeners to elements
  • Other Actions
    jQuery allows faster, more elegant completion of various tasks, such as looping through elements, updating the DOM tree, and animating elements.

Getting Started

jQuery can be included as a file in a page using a script element placed before the closing </body> tag.

You can download a copy of jQuery. Or, you can include it via a Content Delivery Network (CDN). CDNs are a network of servers scattered geographically, to allow site users to access content through the closest network server, thereby maximizing browsing speed.

Syntax

jQuery uses the dollar symbol.
Example:


$('.btn').click(function ()
{ // some code });
​

*In the above example, a click handler attaches to those elements sharing the class btn.

Getters and Setters

Getters

These retrieve information regarding a selected element.

Examples:
var Width = $(‘.box’).width(); // Calling .width without a value returns the selected element’s width

color = $ (‘.box’).css(‘color); // Calling .css with only the property name color returns the value of the property

Setters

These set values for selected elements.

Example:
$(‘.box’).css(‘color’, ‘blue’).width(200);

// $(‘.box’) selects DOM elements with a class of box and sets their color to blue and their widths to 200px.
//Note: This chaining ability increases efficiency and simplicity.

Ajax

Using AJAX with jQuery is much easier than using it with regular JavaScript because jQuery possesses AJAX helper methods to save time and make code more readable.

The following list contains some of jQuery’s Ajax Methods:

$.ajax( ) // For sending AJAX requests to servers

$.ajaxComplete( ) // Used to execute a function when an AJAX request completes

$.ajaxError( ) // Used to execute a function when the AJAX request completes with an error

$.ajaxSetup( ) // Sets default values for future AJAX requests

$.ajaxSuccess( ) // Indicates that a particular function will run when an AJAX request completes successfully

$.get( ) // Loads server data via an AJAX HTTP GET request

$.getJSON( ) // Loads JSON data from server with a HTTP GET request

$.load( ) // Places data retrieved from a server into a selected element

$.post( ) // Loads server data using an AJAX HTTP Post request

DOM Loading

To execute JavaScript only after the DOM has loaded, using $(document).ready( ) to wrap around all of your JavaScript code ensures that your code will only execute when the entire page is ready. Otherwise, your JavaScript may execute before the DOM has loaded, which could result in missing DOM elements that the code needs.

Type Checking

The following methods allow you to determine the data types stored in variables by returning Boolean values:
$.isArray( )
$.isFunction( )
$.isNumeric( )
$.isPlainObject( )