JavaScript – The Basics For Beginners

JavaScript is a high-level scripting language primarily used to make web pages dynamic. It’s the only native programming language available in browsers for HTML pages.

JavaScript Syntax

//get element
	const button = document.querySelector('button');
	//calculates total
	function calcTotal( num1, num2 ){
		return num1 + num2;
	}
	button.addEventListener('click', function(){
		//calculate total
		alert( calcTotal( 123, 105 ) );
	});

How JavaScript Works

JavaScript is an interpreted language meaning that your JavaScript code is passed to an engine which converts human-readable code into machine code. 

Each browser has its own JS engine. For example, Chrome uses the V8 engine.

JavaScript is also dynamically typed, i.e. you don’t declare type like int, string, float etc when defining variables, type is defined at runtime.

How To Use JavaScript in HTML

Primarily, JavaScript is used within HTML documents.

<!DOCTYPE html>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <!---Page content-->
     <button onclick="const total = 123; send(total)">Send</button>
    <!---Reference to a Javascript file-->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        //Some JavaScript code here
        alert('JavaScript is cool')
    </script>
</body>
</html>

JavaScript can be embedded in HTML documents using 3 methods:

External script

You can create a separate JavaScript file with a .js extension and link to it in an HTML page using the <script> tag’s src attribute. Typically, this is the recommended way of including JavaScript in your HTML.

Internal script

You can write code directly inside the <script> tag.

Inline Element JavaScript

Inline JavaScript is attached to event attributes on an HTML element.

<button onclick="const total = 123; send(total)">Send</button>

Variables

A variable is a container of a piece of data. The data can be anything from numbers, words (strings), objects, arrays, functions, other variables etc. Here’s an example (he // are comments and don’t get executed):

// Storing number
var number = 5;
/Assigning multiple variables at once
var num1 = 12, num2 = 13, color = 'blue';

Variable names :

  • Have no spaces
  • Don’t begin with numbers
  • Are case sensitive, i.e Age and age are not the same
  • You cannot the same identifier name (applies to let & const)

Variable naming conventions and tips:

  • Camel case when joining words, e.g myAge, totalCost
  • Don’t use long variable names.
  • Variable names must be self-explanatory for better understanding.
  • Avoid starting with underscores as they are used in the core JavaScript names

var, let & const

JavaScript has 3 keywords to define variables:

var

var is the traditional keyword used to define variables in JS. When a variable is defined globally it can be accessed anywhere (see Scopes below)

var car = 'Toyota';

//Change the car name to Nissan
car =  'Nissan';

// Use it inside a function
function mycar(){
    return 'My car is '+car;
}

const 

const is used to define a variable that cannot be changed or reassigned.

const key = 'cxsxjsccskpowqjwkn';

//reassigning a constant throws error
key = 'mncscncs';

let

let is similar to var but is scoped inside a block, i.e cannot be accessed outside a block statement. Take a look below:

{
  let color = 'red';
}
//color is not defined
console.log(color);

if (true){
  //Variable only available in this block
   let total = 124;
}
console.log(total);
//cannot be used outside

The variable above is only available inside the block { } not outside.

Block statements or code is enclosed in curly braces like if…else, for loops, try…catch, { }, etc.

const also behaves in a similar way

Printing/ displaying output

You can print something in JavaScript using 2 basic methods: console.log() or alert(). Here’s how;

//Writes in the browser console.
console.log('Javascript is fun');

//Writes to an alert box that pop-ups in the browser window
alertt('Javascript is fun');

The console.log function writes output to the browser console. You access this console by right-clicking in the browser-> select Inspect Element-> Console tab.

javascript console browser
Javascript console

The alert() function shows a popup box with whatever output is given.

Comments

Comments describe or document what a piece of code does. Comments are not executed. There are 2 types of comments – inline and block-level comments. Take a look below:

// Inline comments span one line only
    /*
        Block level comments span
        multiple lines
    */

Data Types

Data is not the same and is classified into different categories (types). JavaScript has 7 primitive data types.

Strings

Strings are the most basic data types available in most languages. A string stores text as a sequence of words, numbers, spaces, or symbols.

Strings are enclosed in quotes; single or double quotes, or backtick. You concatenate (join) strings with variables using + or wrap variables (or expressions) in curly brackets when using backticks. Here’s how:

let userName = 'Peter';
//using regular + to join strings and expressions
console.log('Welcome '+userName+' to our website');
//using backtip
console.log(`Welcome ${userName} to our website`);

userName is replaced with Peter when printed.

Numbers

A number can be an integer (whole numbers) or decimal (floating). Take a look below:

//integer, whole number
let number = 5;
//Floating decimal
let dec = 0.55;

Booleans

A Boolean is a value either true or false.

Null

Null is absence of value

Undefined

Undefined (like null) means devoid of value, i.e empty. A variable without value returns undefined.

//boolean
let isLoggedIn = true;
//undefined
let user = undefined;
//null
let obj = null;

BigInt

The bigint data type is used to store very large whole numbers that cannot be supported by number above (-9,007,199,254,740,991 and +9,007,199,254,740,991). It’s created by appending n to the number.

//boolean
let largeNumber = 9007199254740991n;

Read more about bigint

Symbols

A symbol type is used to create unique object key identifiers.

let key = Symbol("key");

Read more on Symbols

Other data types

Objects are key-value pairs of data. Objects are more than types but data structures.

Arithmetic Operators

  • +: Addition
  • -: Subtracting
  • *: Multiplication
  • /: Division
  • %: Modulo
  • **: Exponent (to the power of)
//Assignment
	let num1 = 3;
	//Re-assigning variable
	//Addition. Output: 4
	num1 = num1 + 1;
	//Subtraction. Output: 3
	num1 = num1 - 1;
	//Multiplication. Output: 9
	num1 = num1 * 3;
	//Division. Output: 3
	num1 = num1 / 3;
	//Exponent. 3 to the power 2. Output: 9
	num1 = num1 ** 2;
	//Modulo. Remainder of Output: 1
	num1 = num1 % 2;
//expected output: 1
	console.log(num1)

Assignment Operators

  • = Assign a value
  • +=: Addition assignment
  • -=: Subtraction assignment
  • *=: Multiplication assignment
  • **=: Exponent assignment. The power of 
  • %=: Modulo or remainder assignment

The above code can be shortened with assignment operators like so:

//Assignment
	let num1 = 3;
	//Re-assigning variable
	//Addition. Output: 4
	num1 += 1;
	//Subtraction. Output: 3
	num1 -= 1;
	//Multiplication. Output: 9
	num1 *= 3;
	//Division. Output: 3
	num1 /= 3;
	//Exponent. 3 to the power 2. Output: 9
	num1 **= 2;
	//Modulo. Remainder of 9/2 Output: 1
	num1 %= 2;

	console.log(num1)

JavaScript Data Structures

A data structure is a structured way of storing data in a program. The main data structures in JavaScript are variables, arrays, and objects.

Arrays

An array is a collection of data accessed by an index. The index count starts at 0, i.e. the first data entry starts at 0 not 1. Take a look below:

let fruits = ['banana', 'orange', 'apple'];
//get the second entry - banana
console.log( fruits[1] );

Arrays can store most data types like strings, numbers, objects, undefined, etc. They can store objects, functions, and other arrays transforming them into multidimensional arrays. Here’s a more advanced array.

const students = [
	new Date(),
            { name: "Alice", age: 25, grades: [85, 90, 92] },
            { name: "Bob", age: 22, grades: [78, 82, 88] },
            { name: "Charlie", age: 23, grades: [95, 99, 100] }
        ];
//get Charlie's age
//expected output: 22
console.log( students[2].age ); 

Arrays can be modified. You can add and remove data from the array using the .unshift() and .pop() function methods.

let colors = ['red', 'blue', 'green'];
//Add at the start
colors.unshift('white');
//Add to the end
colors.push('black');

console.log(colors)

//Removes the last element - black
colors.pop();
//Removes the first element - white
colors.unshift();

Objects

An object is a key-value pair collection of data.  You access data by using a bracket or dot method. Take a look below: 

let user = {
		name: 'Peter',
		age: 30,
		student: true
	}

Object key names usually follow the naming conversion of variables. Object keys can be enclosed in quotes which allows you to use other characters like spaces and hyphens (dashes)

Just like arrays, object values can contain any data type. Objects can store arrays, objects, and functions. 

More on objects below.

Functions

A function is a container (block) of a piece of code or set of commands (program). The function can be called anywhere in the program where it executes the commands contained inside or returns a value. Here’s an example:

//Function definition
	function add(){
		return 5 + 6;
	}
	//Call or invoke the function. Will print 11
	console.log( add() ) ;

The function block of code is called a function definition. The function is called by appending parentheses to the function name.

Function Parameters & Arguments.

Function parameters are ways of passing external data to be processed in the function.  Data is passed as arguments when the function is called. We can add parameters to the function above like so:

//Function definition with two parameters
	function add( num1, num2){
		return num1 + num2;
	}
	//Call or invoke the function with arguments
	// prints 16
	console.log( add(9, 7) );

We can add default parameter values when none are supplied. Here’s how:

function add( num1 = 0, num2 = 0){
		return num1 + num2;
	}
//No arguments supplied. prints 0
console.log( add() );

anonymous function

Anonymous functions are functions without a named identifier. They are typically used as callback functions. See events below

const myFunct = function(){
   //Function body
}
const button = document.querySelector('button');
//anonymous function callback
button.addEventListener('click',function(){
        alert( 'Button clicked!' );
    });

Scopes

Scope is where a variable is accessible, i.e. local or global scope. When you declare a variable at the top of your script it can be accessed globally. However, if it is contained in a function, it can only be used inside that function. Here’s an example:

/this variable is global and can be accessed anywhere
    const common = 'global'
    function myFunc(){
        var local = 'local';
        console.log(`You can only access ${local} here!.`);
        console.log( `${common} is accessible anywhere` );
    }
    //undefined. cannot be accessed outside
    console.log( local )

Variables starting with let and const are block-scoped. They are only accessed within blocks enclosed with curly brackets, thus if you declare a variable using let or const inside loops, if statements or blocks it will only be used inside that block. var is not scoped to blocks.

{
        const num = 45;
        let num2 = 33;
        var num3 = 22;
}
    //num1, num2 is not defined
    console.log(num1, num2, num3 );

if( true ){
        let fruit = 'orange';
    }
    //Fruit is not defined
    console.log( fruit )

Conditional Logic

Like other programming languages, Javascript uses if and else statements for logic.

if…else

The if statement proceeds an operation if a specified condition is true. The program continues to the else block if the condition is false. Take a look below:

let number = 5;
    if( number > 0 ){
        //do some operations here
        console.log( `${number} is greater than 0` );
    }
    else{
        console.log( `${number} is less than 0` );
    }

else if

If you want to do further conditional checks, you can use the else if statement. Here’s an example:

let number = 5;
    if( number > 0 ){
        //do some operations here if condition is true
        console.log( `${number} is greater than 0` );
    }
    else if( number < 0){
        //do some operations here if condition is true
        console.log( `${number} is less than 0` );
    }
    else{
        //fall back if nothing is true
        console.log( `${number} unkown` );
    }

Switch

Multiple else if statements can become cumbersome. Switch statements offer an intuitive way of checking multiple conditions. The above conditions can be checked using a switch like so:

let number = 5;
    switch( true ){
        case number > 0:
            console.log(`${number} is greater than 0`);
        break;
        case number < 0:
            console.log( `${number} is less than 0` );
        break;
        default:
            console.log(`${number} unkown` );
    }

Each case expression is checked against the switch value in brackets and runs the block if the condition is true.

Logical Operators

Logical operators are used to evaluate the truthiness of two values..

  • == : tests if two values are equal
  • === tests if two values and their types are equal or identical
  • !== tests if two values are not identical to each other
  • < and > tests if one value is less than or greater than another.
  • <= and >=  tests if one value is less than or equal to, or greater than or equal to, another.

Conditional operators && and ||

&& (AND) – all evaluations must be true. For example:

let number = 5;
    if( number > 0 && number < 10){
        console.log( `${number} is greater than 0 and less than 10` );
    }

Both expressions are true and the code executes.

|| (OR) – one expression must evaluate to true. For example:

let number = 5;
    if( number == 5 || number < 0){
        console.log( `${number} is actually 5` );
    }

Looping

In programming, looping is where all multi-processing is done. Loops make multiple and repetitive tasks easier.

for loop

A for loop is used to loop arrays, i.e. access all elements in an array.

let arr = [5, 7, 9, 11];
    for (var i = 0; i < arr.length; i++) {
        console.log( arr[i] );
        //Expected output:
        //5
        //7
        //9
        //11
    }

A for loop has 3 parts:

  • Initialize – where to start counting from. 0 is the first entry in an array
  • Condition – keep running the loop as long as this condition is true; terminate if false.
  • Increment – increments the initialiser and proceeds to the next array entry if condition is still true.

The loop above starts at 0, checks if the initialiser is less than 4 (arr.length), and proceeds to next value if true.

The .length property returns the array’s length which is 4, i.e they are 4 entries in the array

while

The while loop keeps running as long as the condition is true.

let num = 0;
    while( num < 3){
        num++;
        console.log( num );
    }

In the above, the loop keeps running as long as num is less than 3. Every time the loop runs it increments the num variable eventually reaching 3; which is not less than 3 (false).

Beware of infinite loops. A computer can overheat and crash if the loop doesn’t terminate.

for…in

The for...in loop is used to loop objects. It iterates over the object’s properties returning the key which can be used to access property values.

let user = {
        name: 'Peter',
        age: 30,
        student: true
    }
    for( let x in user ){
        console.log( x+':'+user[x] );
    }

for…of

For...of loops or iterates over arrays. You can use it instead of the for loop to access array elements.

let arr = [5, 7, 9, 11];
for(const elem of arr){
    console.log( elem );
}
// expected output:
// 5
// 7
// 9
// 11

Object Properties & Methods

Basically, almost all things in JavaScript are objects. For example, an array is actually an object. Take a loo below:

let arr = [5, 7, 9, 11];
//typeof will return object
console.log( typeof arr);

The typeof keyword returns the value type the variable holds. For strings it returns string, numbers number, for true/false boolean.

An object property is a piece of data contained in an object. Like a variable, you access whatever value it holds.

A method on the other hand is a property function. A method, like a regular function, does an action or process. Take a look below.

const inventory = {
        car:12, // property
        truck: 3, //property
        totalInventory:function(){
        	console.log(this.car + this.truck );
        } // method
    }

The object keys, car and truck are properties while .totalInventory() is a method of the inventory object.

Note that the word method is used in object contexts to refer to a function belonging to an object. Since most things in JavaScript are objects, methods is used more often to refer to functions of object.

Objects can be created in many ways. The basic two are object literal and constructors. Here’s an example:

//object literal
    const inventory = {
        car:12,
        truck: 3,
        totalInventory:function(){
        	console.log(this.car + this.truck );
        }
    }
    //object constructor
    function Inventory(){

        this.car = 12;

        this.truck = 3;

        this.totalInventory = function() {
            console.log( this.car + this.truck );
        }
    }
    //instantiate the object
    const inventory = new Inventory();
    inventory.totalInventory();
    //Expected output: 15

For the constructor name it’s best to use uppercase for the first letter for convention reasons 

Changing properties & methods

You can change declared object properties like so

//changing props & methods
inventory.car = 33;
inventory.truck = 24;
inventory.totalInventory = function(){  //new things here }

Deleting properties & methods

To delete a property you can use the delete keyword

//changing props & methods
delete inventory.car;

The “this” keyword

The this keyword refers to the current object. It’s used inside the object properties and methods to refer to the object itself. Using the example above, this.car and this.truck refers to the current properties. this is handy as it dynamically refers to the object itself rather than an explicitly defined name like inventory above, for example, which can be altered. 

The DOM

The Document Object Model is a structured hierarchy of all HTML elements in a page document. It can be represented as a tree of DOM elements.

Document object model tree diagram

Root: The html element is the root element with child elements inside.

Child: An element inside another element. The container element is the patent

Siblings: Elements on the same level of the DOM hierarchy

The window

The window is the browser window – browser tabs, scroll bars etc. JavaScript has a global window variable which basically has all global properties and methods , e.g alert() can be written as window.alert(). All global methods and properties can be prefixed with the window variable, however, it’s not necessary. Here are some common window properties:

  • window.innerHeight – returns the full page height without browser tabs or scroll bars
  • window.innerWidth – returns the full page width without browser tabs or scroll bars
  • window.location– returns an object with location properties like full page url, host, protocol etc
  • window.scrollY – the current page position from the top in pixels.

Useful window methods:

// Displays a popup box with a message.
window.alert( 'Hello World' ) ;

//Opens a new window.
window.open();

//Closes current window
window.close();

//Resize a window to the given dimensions
window.resizeTo( 800, 600);

//Runs some code after every given milliseconds
//updates the seconds in real time. 1000 milliseconds = 1 second
window.setInterval(function(){
	console.log( new Date().getSeconds() )
}, 1000);

//Runs some code after some given time.
//Wait 3 seconds and run the code
window.setTimeout(function(){
	console.log( `3 second delay reached!`)
}, 3000);

Note; the window. prefix is not necessary.

You can add your own properties and methods to the window object. In fact, every variable declared with var is attached to the window object. However, you need to be careful when adding properties to window as you can override native JavaScript and other people’s properties and methods.

DOM Manipulation – document

JavaScript allows us to modify DOM elements like adding and deleting HTML elements.  The document object contains some useful properties and methods for manipulating HTML.

To manipulate an element we must first select it using document.querySelector()

The function accepts a CSS selector string, i.e a selector name like div, id, or class. It returns a DOM object that can be used for other manipulations.

Here’s an example HTML to manipulate; add the codes that follow below in the JavaScript tab and see the changes

See the Pen Javascript sample by Denver Kunaka (@Denver-Kunaka) on CodePen.

Get the div with class panel__content:

const content = document.querySelector('.panel__content');

Adding elements

We use the . appendChild() method to add elements in the DOM. It appends it to the end inside a given element.

You first create the element you want to add using the document.createElement() method. The function returns a DOM object which can be used for other DOM manipulations

//Create an element first
const para = document.createElement("p");
//Add text inside p
para.textContent = "I Love Javascript'";
//Append an element p in the div.panel__content
content.appendChild( para );

Adding HTML

The .innerHTML property is used to add custom HTML. Here’s how:

para.innerHTML = `<strong>The little brown <a href="google.com">fox</a> jumps over the lazy dog</strong>`;

Setting & Getting Attributes

You set attributes using the .setAttribute() method and get them with .getAttribute(). The .setAttribute() accepts two arguments; the attribute name and value. 

//set the id attribute
    para.setAttribute('id','my-paragraph');
    //get attribute
    para.getAttribute('id');

The getAttribute() takes the attribute name you want to get. It returns null if the attribute doesn’t exist.

Manipulating CSS

Javascript also allows us to add CSS to elements.The style property on a DOM element contains all CSS properties that you can set or get.

para.style.padding = '16px';
    para.style.background = 'blue';
    para.style.fontSize = '18ox';
    para.style.color = 'white';;

Note fontSize is camel-cased instead of kebab-case; font-size. The kebab-case is an invalid syntax. If you want to use the typical CSS syntax use the brackets instead of the .dot notation.

para.style[‘font-size’] = ’24px’

Removing elements

You remove elements using the .remove() method.

//remove the p element
para.remove();

JavaScript Events

Events are what makes JavaScript dynamic. Events are activities or actions happening in a web page, e.g clicking, key-presses, scrolling, etc.

There are basically two methods to listen to events and handle what happens when the events occur–-.addEventListiner() and the event properties attached to the DOM element. The former offers more control over event handling.

//get the DOM element object
    const h3 = document.querySelector('h3');
    //Using addEventListener
    h3.addEventListener('click',function(){
        alert( 'Title clicked!' );
    });

    //Using event properties
    h3.onclick = function(){
        alert( 'Title clicked!' );
    }

The .addEventListener() method typically requires two arguments; the event name and the callback function that runs when the event is triggered. See a list of all Javascript events.

For the handler (callback function) you can use an anonymous function or named function.

//Event handler
function myHandler(){
        alert( 'Event triggered');
    }
 //Add event
 h3.addEventListener('click', 'myHandler');

The addEventListener() method passes an event argument to the callback function which contains some properties and methods pertaining to the event.

const link = document.querySelector('a');
    link.addEventListener('click',function(event){
        //returns the element that triggered the event; which is a
        console.log( event.target );
        // returns the event name which is click
        console.log( event.type );
        //cancels the default link behaviour, i.e opening the linked paged
        event.preventDefault();
    });

In the example above, a click event is fired when a link is clicked. The event.preventDefault() cancels default element behaviours . In this case, it cancels the default behaviour of links, i.e opening a new link.

this in the callback function refers to the element that triggered the event similar to event.target.

JavaScript Best Practices

  • Put JavaScript scripts at the bottom (just before the closing body tag) to prevent blocking the page from rendering.
  • Use descriptive variable and function names e.g totalStock, user
  • Avoid infinite loops overheats a computer
  • Avoid too much nesting of arrays (multidimensional arrays)
  • Create functions for common, repetitive tasks.
  • Namespace your variable or function names to avoid clashes with other third-party code, e.g you can prefix your names with a set of words like tpTotalStock, tpUser- tp can be your company prefix
  • Create function objects to encapsulate variables instead of declaring them globally which can result in name clashes with other code.
  • Keep it simple; avoid complicated and over-the-top code that is hard to understand.