Javascript Fundamentals For Absolute Beginners

If your looking to learn JavaScript fundamentals for absolute beginners your in the right place. In this tutorial we will cover all the basics of JavaScript so you can get started writing your own code.

This course is for beginners or anyone that just wants a refresher on basic JavaScript Syntax. After reading this article you will want to create some of your own JavaScript projects. Creating some projects on your own is the best way to really learn how to code. Use a search engine to find things you dont know or need to learn to complete your project.

What is JavaScript? Why should I learn it?

JavaScript is one of the 3 languages all web developers must learn. HTML, CSS and JavaScript form the basis of front-end web development. HTML defines the content, CSS is used to design how that content looks and JavaScript is used to program the behavior of web pages. 

JavaScript enables you to create interactive elements, dynamically updating content, control multimedia, animate elements, and modify the content of a page. It works on all modern browsers both on desktop and mobile.

A strong knowledge of JavaScript will allow you to create web applications and browser games.

How to follow along with this Java Script Course?

Download a code editor to write javascript on your computer.
A code editor helps by making your code easier to read by highlighting the syntax in different colors. It can also help suggest and auto complete code while your typing to save time. Helps you find errors and keep your project organized.

Or you can use an online JavaScript editor

javascript fundamentals for absolute beginners

Download Example File

How to add JavaScript to a page?

To insert JavaScript into a web page, use the <script> tag. 

The older method used the type attribute. This is no longer regured as Javascript is now the default scripting language.

Scripts can also be placed in external files:

<script language="javascript">
// Java script code here
</script>
<script>
// Java script code here 
</script>
<script type="text/javascript" src="script.js"> </script>

Adding Comments In JavaScript

Use comments to explain what is going on in your code. A single line comment start with //. Any text between // and the end of the line will be ignored. They are just there to create notes for yourself and others about what the code does.

You can also use comments to disable blocks of code. This is good when you are testing to see which part of the code is causing an error. Sometimes you may want to try out another version of code without deleting what you have already done.

// Inline comment or single line comment
var number = 6; // Good way to add a comment to the end of a line of code.
 
/*
Multi
Line 
Comments 
*/

/*Commenting out lines of code. 
document.getElementById("myHeader").innerHTML = "My First Headline";
document.getElementById("myParigraph").innerHTML = "My first paragraph.";
*/

//document.getElementById("myHeader").innerHTML = "My First Headline";

Storing Data – Variables

Variables are containers for storing data. They allow you to store and manipulate data. A varable name is a label that points to this data. 

Creating a variable is called declaring it. You declare a variable in JavaScript by using the var keyword. Generally it’s best practice to declare all variables at the beginning of a script. All variables must be identified with a unique name. To assign a value to the variable, use the = sign. A variable declared without a value will have the value undefined. It’s best practice to end all lines of code in JavaScript with a ; semicolon.  It’s not required but it’s considered best practice.

 

There are 3 ways to declare a variable in JavaScript.

  • Var: Global Scope – Can be accessed from anywhere.
  • Let: Local Scope – Only lets you use the variable within the scope of where you declared the variable.
  • Const: A Variable that can not be changed.

The general rules for creating names for variables are:

  • Variable names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter and not a number.
  • Names can also begin with $ (but that’s usually reserved for JQuery)
  • Names are case sensitive (Price and price are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as variable names.
  • It’s best practice to use Camel Case for variable names. First letter of the first word is small. First letter of all following words is capitalized.

JavaScript provides 7 different data types:

  • undefined: variable  that hasn’t been defined.
  • null: Means nothing. Set a variable to be nothing.
  • boolean: Set a variable to true or false.
  • number: variable that contains any number.
  • string: variable that contains any text.
  • symbol:
  • object: An object can store key value pairs.

In JavaScript, just like in algebra, we can use variables in an expression.

// Initializes a variable. The value is set to undefined.
var variable;  
 
// Numbers
var price_1 = 3.95;
var price_2 = 10.99;
 
// Expressions
var totalCost = price_1 + price_2;
var sum = 10 + 12 + 33;
var difference = 50 - 10;
var product = 10 * 10;
var quotient = 100 / 10;

// Increment a number
var myIncrement = myVar + 1;
var myIncrement2 ++;           // short hand samething

// Decrement a number
var myDecrement = myVar - 1;
var myDecrement2 --;           // short hand samething

//Find the remainder
var remainder = 44 % 10;    //4
// You can determine if a number is even or odd by checking the remander of 2

//varable = itself + a number
a = a + 40;
a += 40;      //Short hand

//varable = itself - a number
a = a - 40;
a -= 40;      //Short hand

//varable = itself multiplied by a number
a = a * 40;
a *= 40;      //Short hand

//varable = itself devided by a number
a = a / 40;
a /= 40;      //Short hand


// String (Text)
var customer = "Cindy Smith";
var answer = 'Yes I am!';
 
// Joining Strings Together
var fullName = "John" + " " + "Doe";
 
// Add a string to a variable
var myStr = “Hello, my name is ” +  myName;    
 
//Declaring many variables in one statement. 
var person = "Cindy Smith", carType = "Ford", price = 35000;
var person = "Cindy Smith", 
carType = "Ford", 
price = 35000;
 
//Variables created with the const keyword can not be changed. They are constant.
const PI = 3.141592653589793;

// Only lets you use the variable within the scope of where you declared the variable.
let ourName = "Nathan";

//Lets you see the value of the variable in the console. Great to debug your code and make sure things are working
console.log(ourName);

// Add HTML to a varable
// Using a back tick is the easiest way to add "QUOTES" into a sting.
var HTML = `<a href="http://www.GreenMarketing.ca"> Link </a>`; 

// You could also just use single quotes.
var HTML = '<a href="http://www.GreenMarketing.ca"> Link </a>'; 

// You can also use an escape character (\) BACK SLASH. 
//I think it makes the code harder to read so I prefer the first 2 options.
var HtmlLink = "<a href=\"http://www.GreenMarketing.ca\"> Link </a>";

Escape characters inside a sting.

Some chatacters dont work inside a sting and need to be escaped to work.

Quote  \’
Double Quote \”
Back Slash  \\
New Line  \n
Carriage Return
(Simular to new line)
 \r
Tab \t
Backspace \b
Form Feed
A form feed is a page-breaking. Forces the printer to start a new page.
\f

 

Find The Length Of A String

var myFirstName = "Nathan Ergang";
lengthOfFirstName = myFirstName.length;
console.log("My first name is " + myFirstName + ". That has " + lengthOfFirstName + " characters in it.");
// CONSOLE: My first name is Nathan Ergang. That has 13 characters in it.

Bracket Notion

BRACKET NOTION: Get a character within a specific index of the string.
ZERO BASED INDEXING: JavaScript starts counting from 0 not 1.

var myFirstName = "Nathan Ergang";
firstLetterOfTheString = myFirstName[0];
lastLetterOfTheString = myFirstName[myFirstName.length -1];
console.log("The first letter of the sting is " + firstLetterOfTheString + " and the last letter is " + lastLetterOfTheString + ".");
// CONSOLE: The first letter of the sting is N and the last letter is g.

Storing Data – Arrays

Arrays are a way to store multiple values in one variable. They are great for storing a list of items. You can access the values by referring to an index number in the array. Array indexes start with 0 so the first item will have an index of 0.

var array_name = [item1, item2, item3];  
 
var fruits = [banana, apple, orange, grape];
 
// Arrays can span multiple lines
var cars = [
  "Ford",
  "Tesla",
  "Volvo"
];
 
// Access the Elements of an Array
var name = cars[0];  // stores ford in variable name
console.log(fruits[0]);  // Prints out banana in the console
 

// Changing a value of an element in an array. You CAN modify an array with bracket notation unlike variables.
fruits[0] = "Water Melon";


// Nested Array / Multi Dimensional Array - An array inside an array
var multiDimensional = [   ["Universe 1", 34823], ["Universe 2", 19282]   ];
var universeCoordinate = multiDimensional[0][1];  
console.log(universeCoordinate);
//CONSOLE: 34823
 

Array Methods

toString() Converts an array to a string with each value separated with a comma.
join() Joins an array into a string but allows you to specify your own separator.
pop() Removes the last value from an array. It can also return the last element in the array.
push() Adds a new element to the end of an array. It can also return the length of the new array.
shift() Removes the first element of the array. It can also return the value that was shifted out of the array.
unshift() Adds a new value to the beginning of an array.
splice() Add new elements to an array at a specified point.
concat() Creates a new array by joining 2 arrays together.
slice() Slices out a section of an array into a new array. It does not remove any values from the source array. Can take up to two arguments. A start and an end point.
// PUSH: Add items to the end of an array
var animals = ["cat", "dog", "tiger", "bird"];
animals.push("rabbit");
console.log(animals);
//CONSOLE:   ["cat", "dog", "tiger", "bird", "rabbit"]


// UNSHIFT: Add items to the beginning of an array
var animals = ["cat", "dog", "tiger", "bird"];
animals.unshift("rabbit");
console.log(animals);
//CONSOLE:  ["rabbit", "cat", "dog", "tiger", "bird"]


// POP: Remove an item from the end of an array and store it in another variable
var animals = ["cat", "dog", "tiger", "bird", "rabbit"];
removedAnimal = animals.pop();
console.log("Animal Array = " + animals);
console.log("Removed Animal = " + removedAnimal);
/* 
CONSOLE:
Animal Array = cat,dog,tiger,bird
Removed Animal = rabbit
*/


// SHIFT: Remove an item from the start of an array and store it in another variable
var animals = ["cat", "dog", "tiger", "bird", "rabbit"];
removedAnimal = animals.shift();
console.log("Animal Array = " + animals);
console.log("Removed Animal = " + removedAnimal);
/* 
CONSOLE:
Animal Array = dog,tiger,bird,rabbit
Removed Animal = cat
*/


// GROCERY LIST ARRAY
var groceryList = [    ["Tomato Soup: ", 3],   ["Green Tea: ", 2],   ["Chips: ", 1],   ["Carrot: ", 4]];
groceryList.pop();
groceryList.unshift(["Eggs: ", 12]);
console.log(groceryList);
/* 
CONSOLE:
0: (2) ["Eggs: ", 12]
1: (2) ["Tomato Soup: ", 3]
2: (2) ["Green Tea: ", 2]
3: (2) ["Chips: ", 1]
*/
 

Conditional Logic – If Statements

If statements are used to make decisions in code. If this happens then do this. If not do this instead. The order matters once the first condition is met it does not check any other conditions.

Use the else if statement to specify a new condition if the first condition is false.
Use the else statement to specify a block of code to be executed if all other conditions are false.

If Statements

If (val > 10) {
// Value is greater than 10
}
else if (val < 5) {
// Value is smaller than 5
}
else {
// Value is between 5 and 10
}

 Comparison Operators

== Equal operator

= assigns
== compares 

=== Strict equal operator  

There is no variable type conversion.
Meaning a string does not equal an integer.
3 === 3   True
3 === ‘3’  False

!= NOT equal !== Strict NOT equal
> Greater than < Less than
>= Greater than or equal to <= Less than or equal to
&& AND operator

If (val <= 50 && val >=25) {
// Both these must be true
}

|| OR operator

If (val < 50 || val >20) {
// if val is 49 – 21
}

Conditional Logic – Switch Statements

The switch statement allows you to perform different actions based on different conditions. It then runs a block of code based off of those conditions.

The default keyword specifies the code that will run if there is no match.

The Break Keyword stops the execution inside the switch block. Used to jump outside of the switch statement and not make any further checks. The last condition doesn’t need a break as that happens automatically.

switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  default:
    day = "Saturday";
}

Functions

A function is a block of code that is designed to perform a task that can be used over and over again. Functions are very important in Javascript.

The function keyword: is used to define a function. It’s followed by it’s name and parentheses (). Function naming follows the same rules as variables. The code that gets executed when the function is called goes between the curly brackets {}. 

Parameters: Are variables listed inside the parentheses as a part of the function definition. Parameters allow you to input data into the function to produce different results.

//Defines the function
function myFunction(parameter1, parameter2) {
// code to execute
}

//Calls the function
myFunction(1,7);
 

The return statement: Stops code from executing inside the function. It also returns a value to the function caller. Every function in JavaScript returns undefined unless otherwise specified. This function doubles its input then returns the value to the caller so that can be read inside the console.

function double(input) {
return input * 2;
}
console.log(double(2));  // console will read out number 4
 
// GLOBAL SCOPE 
var globalVariable = 25;

function checkScope() {
	if(typeof globalVariable != "undefined") {  //If variable is NOT undefined
		console.log ("Variable is GLOBAL SCOPE and it's value is " + globalVariable);
	}
	else {
		console.log ("Variable is undefined!");
	}

}
checkScope();
// CONSOLE: Variable is GLOBAL SCOPE and it's value is 25



// LOCAL SCOPE EXAMPLE 1
var localVariable = null;

function checkSchope() {
	var localVariable = 500;
}
checkSchope();
console.log(localVariable);
// CONSOLE: null



// LOCAL SCOPE EXAMPLE 2
function checkScope() {
	var localVariable = 500;
	console.log(localVariable);  //500
}
checkScope();
console.log(localVariable); // VM76:6 Uncaught ReferenceError: localVariable is not defined
// CONSOLE: 500
// VM76:6 Uncaught ReferenceError: localVariable is not defined



// Without the var keyword inside a function it becomes global 
function checkScope() {
	localVariable = 500;
}
checkScope();
console.log(localVariable);
// CONSOLE: 500



// If you have both local and global variables with the same name. The local variable takes president  
var testGlobal = "Variable is GLOBAL";

function checkScope() {
	var testGlobal = "LOCAL variable takes over";
	console.log(testGlobal);
}
checkScope();
console.log(testGlobal);
// CONSOLE:
// "LOCAL variable takes over"
// "Variable is GLOBAL"
 

Loops

Loops are used to repeatedly run a block of code over and over again until a condition has been reached. This is often the case when working with arrays. You would want to loop though all the data and perform some kind of action on them. JavaScript offers several ways to run loops.

For Loops – A for loop is made 3 important parts.

Initialization: The starting point of the counter.
Test Statement: Set the end point of the counter. Test to see if the counter has been reached. If it has exit the loop. If not run the code inside the loop until it does.
Iteration Statement: Amount to increase or decrease your counter by.


for ([initialization]; [test condition]; [iteration statement]) {
   // Statement(s) to be executed if test condition is true
}

 

document.write("Starting Countdown.." + "<br>");       
for(var count = 10; count = 1; count--) {
document.write(count + " ");
}         
document.write("Blast Off!!!!!");

DOM – Document Object Model

What is DOM?
DOM or Document Object Model is an interface that allows programs and scripts to dynamically access and update the content of a website. It turns every element on the page into an object and allows you to access it with JavaScript or other languages. This is how you can change, add or delete HTML elements even after the page has loaded.

With DOM you can:

  • Change the content of an HTML element.
  • Change the styles or CSS of an HTML element.
  • Add, delete, hide or perform actions on HTML elements.
  • Change the value of properties.

DOM METHODS
The document object contains all objects on your page. Methods are actions you can do. on those objects.  If you want to access an HTML element on the page you always start with the document object then a method.

document.getElementById() Most common way to access an HTML element is with its ID.
document.getElementsByTagName() Access an element by tag name.
document.getElementsByClassName() Access an element by class name.
document.querySelectorAll(“p.intro”); Finds all HTML elements that match a specified CSS selector
document.createElement(element) Creates a new HTML Element.
document.removeChild(element) Remove an existing HTML element.
document.appendChild(element) Adds an HTML element
document.replaceChild(new, old) Replaces an HTML Element


DOM PROPERTIES
A property is a value you can set or get.

.innerHTML Allows you to get or change the content of an HTML element.
.attribute Allows you to change an attribute of a HTML element.
.style.property Allows you to change the style of an HTML element.
.setAttribute(attribute, value) Allows you to change an attribute value of an HTML element.

<p id="text_01"></p>
<img id="myImage" src="Happy.gif">

<script>
// Changes the content of the text_01 <p> tag
document.getElementById("text_01").innerHTML = "New Text!";

// Changes the style of the <p> tag. Changes the text color to blue
document.getElementById("text_01").style.color = "blue"; 

//Changes the Value of an Attribute. Swaps one image out for another.
document.getElementById("myImage").src = "sad.jpg";

// Finds all <p>  tags and stores them in a variable 
var pTags = document.getElementsByTagName("p");

// Find all <p>  tags with class name intro
var pTagsIntro = document.querySelectorAll("p.intro");
</script>

JavaScript Events

An event is something the browser does or something the user does. JavaScript can react to events and then let you run code after the event has been detected. Since JavaScript code is usually several lines long It’s more common to see events calling functions.

Examples of JavaScript Events:

  • Page finishes loading
  • Input field has changed
  • Something has been clicked
  • A key has been pressed
  • Window gets resized
  • When a form gets submitted
  • Get the full list of events here.

Example 1:
 

Example 2:

ADDING AN EVENT HANDLER TO AN HTML ELEMENT (Old Way)

<!--Syntax Example-->
<element event="JavaScript Code To Execute"></element>

<!--On click runs some code-->
<button onclick="this.innerHTML = Date()">The time is?</button>

<!--On click runs a function-->
<button onclick="displayDate()">The time is it</button>
<p id="showdate"></p>
<script>
function displayDate() {
  document.getElementById("showdate").innerHTML = Date();
}
</script>
 

JAVASCRIPT EVENT HANDLERS (New Way)

This is the better way of handling events because it keeps HTML clean. The JS Events and HTML are Separated. No need to modify the HTML document to get an event to work.

// Grabs the Html Element by it's ID and stores in a variable.
var button = document.getElementById("button");

// Adds a click event to the button and calls a function
button.addEventListener("click", buttonClick);

// The action that happens when button is clicked
function buttonClick(){
  console.log("Button was clicked");
}
 
// DIFFERENT MOUSE ACTIONS -------------------------------------------------------------------------------
var button = document.getElementById("button");
var box = document.getElementById("box");
 
button.addEventListener("click", runEvent);
button.addEventListener("dblclick", runEvent);   // Only fires on double click
button.addEventListener("mousedown", runEvent);  // as soon as you click down. No need to lift up
button.addEventListener("mouseup", runEvent);  // Nothing happens till mouse is released
 
//Only for that element itself not it's children
box.addEventListener("mouseenter", runEvent); // Mouse Enters Box
box.addEventListener("mouseleave", runEvent); // Mouse Leaves Box
 
// Includes children inside the box
box.addEventListener("mouseover", runEvent); // Mouse Enters Box
box.addEventListener("mouseout", runEvent); // Mouse Leaves Box
box.addEventListener("mousemove", runEvent); // Inside the box moving the mouse
 
function runEvent(e){
  // Sends data to console about event type
  consule.log("EVENT TYPE:"+ e.type);
  // Changes the color of the box based on mouse position  
  box.style.backgroundColor = "rgb(" + e.offsetX + "," + e.offsetY + ",40)";  
}
 

JAVASCRIPT EVENT PROPAGATION

This is the blanket term for both event bubbling and capturing. This refers to the order in which event handlers are called.

1. EVENT BUBBLING (Default):

When capture = false
Events ripple up from child element all the way to the top of the document. Starts with the element that triggered the event then moves up the DOM tree to the parents in the hierarchy. If this parameter is omitted the default value is false.

2. EVENT CAPTURE:

When capture = true
With event capture it run the function on the way down. Events go from top of the document (The window object) all the way down to the element that was clicked.


document.addEventListener('keyup', function (event) {

    if (event.target.classList.contains( 'className' ) ) {
            //  Event Action Here
    }

}, false);



// EVENT BUBBLING
document.addEventListener('click', listener, false); 
function listener(e) {
// Do Something
}
 

Debugging

JavaScript Objects – OOP: Object Oriented Programming

Procedural Programming:

Procedural programming, also known as inline programming takes the top-down approach. Its basicly a list of instrctions for the computer to follow. It’s a style of programming that uses variables to store data and functions to modify that data.

Usually simple & straight forward for small scripts but often ends in spaghetti code with large programs. This happens because there is an Inter dependency between functions. This can become problematic and break things in large programs.

OOP: Object Oriented Programming
OOP or Object Oriented Programming was invented to solve this problem. Learning OPP is an essential skill for every developer.

It’s a popular style of programming centered around encapsulating data and behavior into objects rather than variables & functions.

With OPP you combine related functions and variables into a unit called an object. Variables inside an object are referred to as properties. Function inside an object are referred to as methods.

EXAMPLES OF OBJECTS:
OBJECT: Car
PROPERTIES:
Model: “Tesla”,
Color: “Red”,
LicencePlateNo: “FG 4589”,
METHODS:
stop();
start();
move();
changeGear();
OBJECT: Local Storage
POPERTIES:
length: 0,
METHODS:
clear();
getItem();
removeItem();
SetItem();
OBJECT: Person
POPERTIES:
firstName: “Nate”,
lastName: “Ergang”,
age: 30,
METHODS:
wakeUp();
eat();
sleep();

4 PILLARS OF OOP

1 ENCAPSULATION:
Encapsulation is the grouping of related variables and functions together into objects to reduce complexity and increase re usability.
2 ABSTRACTION:
Abstraction hides the details and complexity and only shows the essentials. All the inner working of the object are hidden from the outside. This makes the interface of the object simpler.

Abstraction is a process where you hide the implementation details of the object and provide the functionality. Code from outside the object cant touch private methods and properties. You don’t need to create abstractions for every use. Use your judgment to decide when it’s necessary.

3 INHERITANCE:
Allows you to eliminate redundant code.
Define common methods and properties in a generic object. Then have other objects inherit those properties and methods from the parent object. That way you don’t have to duplicate code.
4 POLYMORPHISM:
Polymorphism: Means many forms.
Allows methods inherited from the parent object to behave differently in the child objects. Without having to use switch case statements. It’s the practice of designing objects to share behaviors but be able to override them as needed with something more specific to that object.

Creating Objects

// Object is created with curly braces
const circle = {};
 
// Doesn't duplicate well. You have to copy the code.
// An object is a collection of key value pairs
const circle = {
    //Properties - Holds values
    radius: 1,
    location: {x:1, y:1},
    //Methods - Define logic & behavior
    draw: function() {       
        console.log("Draw Circle!");
    }
};
circle.draw();  //Call draw method
 

Multiple Instances of Objects

2 Ways to create objects with functions. Use these if you plan to create multiple instances of the same object.

function createCircle(radius) {
  return {
      //radius: radius,
      //ES5 New Feature (Short hand)  if key and value are the same
      radius,  
      location: {x:1, y:1},
      draw: function() {console.log("Draw circle!");}
  };
}
// Call function to create new circle object
const circle = createCircle(1);
circle.draw();
 
// Constructor = function used to create an object
// Constructor Functions use this and new keywords
function Circle(radius) {
  this.radius = radius;
  this.draw = function() {console.log("Draw circle!");}
  // Shows what this is in console    This: Circle {}
  console.log("This:", this); 
}

// When we use a new operator to call a function it will create an object.
const anotherCircle = new Circle(1); 
anotherCircle.draw();
 

HTML 5 Canvas

More coming soon!

Staging The DNS On Windows & Mac

Staging The DNS On Windows & Mac

Staging The DNSHow Can I Test My Website Before Switching DNS? Avoid The Painfully Long Waiting Period After Pointing A Domain Name To A New Host. When you change the DNS settings of a domain name there is a painfull 24 - 48 hour waiting period. If you want to skip...

Best Word Press Plugins 2019

Best Word Press Plugins 2019

Best WordPress Plugins In 2019 The Divi Page Builder & ThemeDivi is the only theme I use to build websites for several reasons.   You can build websites visually. Perfect for the designer or for clients that want to make changes but don't know how to code. Using...

What Did You Think Of Our Javascript Fundamentals For Absolute Beginners Tutorial?

Facebook Video instagram