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

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





























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. 


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 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?

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.


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:

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


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.


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>Example web page</title>
  <link rel="stylesheet" type="text/css" href="css/example.css">
    <h1>Example Page</h1>
    <p>Glad you%u2019re here.</p>

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.


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>Example web page</title>
  <link rel="stylesheet" type="text/css" href="css/example.css">
    <h1>Example Page</h1>
<p>Glad you%u2019re here.</p>
    <script src = "js/example.js"></script>

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

Displaying Data

JavaScript can output data in various ways:

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.


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:

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


JavaScript has two types of values: Fixed and Variable

Fixed (AKA Literals) Variables

Decimals are optional

15.25 → Correct

1500 → Correct


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.


Inserting comments in code is highly recommended for multiple reasons:

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.


//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.


/*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;


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.


var quantity;
var x;
var myAge;


In the examples above, the variable names, also called identifiers, are quantity, x, and myAge.

Identifiers must be unique and follow these general guidelines:


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


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

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


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


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


\ 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.


var greeting = “What\’s up?”;

var question =  ‘Have you read \”The Hobbit\”?’;


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


Two possible values: True or False

Can be used to specify when certain parts of code should execute


Contains a list of values

The list is enclosed in brackets

Values have quotations around them, and are separated with commas


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.


Each object has properties and behaviors

Represented as name:value pairs, separated by commas

Enclosed in curly brackets


var car = {carMake: “Toyota”, carModel: “Prius”, year: 2012, extColor: “black”};

The object car, above, has the properties carMake, carModel, year, and extColor.


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)


var firstName = Symbol( );

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


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 “ ”.


var person = “ ”;

You can set an object to the value undefined, which will also change the type to undefined


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:


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:


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 can either assign a value to a variable or reduce multiple values to a single one.


var person = %u2018Jenni%u2019;

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


var sum = 5 + 5 + 0;

*This expression evaluates to 10.


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


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.


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:

Future Keywords

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

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

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


Operators and Operands

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


100 + 75
Operand Operator  Operand

 Mathematical Operators

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

Addition (+)

Adding numbers


var x = 10;

var y = 20;

var z = x + y

*evaluates to 30

Subtraction (-)

Subtracting numbers


var x = 10;

var y = 5;

var z = x – y;

*evaluates to 5

Multiplication (*)

Multiplying numbers


var x = 10;

var y = 5;

var z = x * y;

*evaluates to 50

Division (/)

Dividing numbers


var x = 10;

var y = 5;

var z = x/y;

*evaluates to 2

Modulo/Modulus (%)

Finding remainder after division


var x = 101;

var y = 2;

var z = x % y;

*evaluates to 1

Increment (++)

Incrementing numbers by 1


var x = 1;


var y = x;

*evaluates to 2

Decrement (–)

Decrementing by 1


var x = 2;


var y = x;

*evaluates to 1


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


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.


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.


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.


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.


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.


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


var x = 10;

x %= 3; // same as 10 % 3

*evaluates to 1

String Operators


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.


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.


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.


‘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.


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.


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.


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.


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.


var greeting;

var day = ‘Monday’;

switch(day) {

case ‘Monday’:

greeting = ‘Happy Monday!’;


case ‘Friday’:

greeting = ‘TGIF!’;



greeting = ‘Good Morning!’;



* 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 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.


var x = 0;
var y = 1;
while(x < 10) {

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.


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


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.


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:


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.


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.


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.


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.


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

Global Variable


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 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.


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:


To access an object method:






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” }; = { first: "Paris", last: "Jones" };

You can also create an empty object and then give it properties and methods

var person = {}; = {“brown”}; = 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:



length() – length of a string


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


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


Format: Number.Method



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


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.


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 is a JavaScript reserved word to identify a non-number value. Here are some instances of NaN values:

Mathematical calculations with non-numeric strings:


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


isNaN(“string”); – returns true


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

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


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


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

*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.


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.


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.


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’; = 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.


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.


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.


var house = {
       windows: 20,
       doors: 3,
       totalSum: function( ) {
     return + 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.


var windows = 10;
var house = {windows: 20};
var totalWindows = function ( ) {
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:


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.


– access all HTML elements


– gain information regarding browsing history

window.innerHeight and window.innerWidth

– gets the height and width of the available space on the page


– retrieves information about the browser screen


– gets information about the browser


– 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 – 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, 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>
	<title>%u201DMy Title%u201D</title>
	<a href=%u201D%u2026%u201D>My Link</a>
	<h1>My Header</h1>

The DOM:


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:

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 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:

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


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


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


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, (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.



> 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 (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:"GET","ajax_info.txt",true);

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:


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.


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 is the most widely used JavaScript framework. It simplifies many common JavaScript activities.

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.


jQuery uses the dollar symbol.


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

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

Getters and Setters


These retrieve information regarding a selected element.


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


These set values for selected elements.


$(‘.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.


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( )

Top courses in JavaScript

JavaScript Web Projects: 20 Projects to Build Your Portfolio
Andrei Neagoie, Jacinto Wong
4.7 (1,036)
Accelerated ES6 JavaScript Training
Maximilian Schwarzmüller
4.7 (4,415)
The Complete JavaScript Course 2020: From Zero to Expert!
Jonas Schmedtmann
4.7 (87,690)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
Academind by Maximilian Schwarzmüller, Maximilian Schwarzmüller
4.6 (11,163)
The Modern Javascript Bootcamp Course (2020)
Colt Steele, Stephen Grider
4.7 (5,590)
JavaScript Basics for Beginners
Mosh Hamedani
4.5 (7,273)
Modern JavaScript From The Beginning
Brad Traversy
4.7 (22,251)
Modern JavaScript (from Novice to Ninja)
The Net Ninja (Shaun Pelling)
4.8 (5,168)

More JavaScript Courses

JavaScript students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo