JavaScript Data Structuring

An ES6 feature that allows you to unpack array or an object and assign each value to a variable.

// Simple array
const arr = [2, 3, 4];
const [x, y, z] = arr; // creates 3 variables: x=2, y=3, z=4.

const [a, ,b] = arr; // misses out middle array value (a=2, b=4)

// switching variables
let first = "starter";let second = "main";
[first, second] = [second, first]; // first = main, second = starter

// nested arrays
const nested = [2, 4, [5, 6]];
const [, ,[j, k]] = nested; // j = 5, k = 6

// default values
const [p=1, q=1, r=1] = [8, 9]; // p=8, q=9, r=1

Destructuring Objects

Use curly braces to destructure objects. You use the property names as variable names.

const {propertyName1, propertyName2} = myObject; // desctructuring using property names.

const {propertyName1: myName, propertyName2: myName2} = myObject // destructuring with custom variable names

// setting default values (in case the property doesn't exist)
const {menu = [], starters: starterMenu = []} = myObject;

Mutating Objects

Surround the code with brackets to create a code block.

let a = 111;
let b = 999;
const obj = { a: 23, b: 7. c: 14 };
({ a,b } = obj); // not allowed to use const or let as variables are already declared - add brackets to prevent error and create a code block.

Nested objects

const { fri: { open: o, close } } = openingHours;
// fri is the property name of the first object which has open and close nested object. This syntax will create new variables "o" and "close" which will be Friday opening and closing hours

Destructuring objects with functions/methods

you can destructure objects passed in functions using curly brackets within the function parameters. You can also set default values as before.

restaurant = {
 name: "My Restaurant";
 // this method will destructure a passed object into four variables (using property names)
 orderDelivery: function ({starterIndex = 0, mainIndex = 1, time, address}) {
   console.log("delivery address:" + address);
 }
}

restaurant.orderDelivery({
 // create an object:
 time: '22:30',
 address: '29 This Street, This Town',
 mainIndex: 1,
 starterIndex: 2
});

Spread Operator

Scenario: Create a new array that has two values and then all the values of another array

const = oldArray = [3, 4, 5];
const = newArray = [1, 2, ...oldArray]; // newArray equals 1,2,3,4,5

Spread operator descructures a literal array but does not create new variables for each value.

Can be used to create shallow copies of arrays or merging arrays:

const copiedArray = [...originalArray]; // copy array
const firstAndSecondArray = [...firstArray, ...secondArray]; // merged arrays

Can also be used on any iterables (ie can break down a strings, maps, sets).

const str = 'word';
const letters = [...str]; Creates an array "w","o","r","d"

The spread operator can also be used as the parameter in a function to deconstruct an array and then pass the individual arguments.

Can be used to copy objects too as before.

Rest Pattern

Rest pattern does the opposite of the spread operator. Used to collect multiple elements and condense them into an array.

Uses the spread operator but on the left side of the equals operator

const [a, b, ...others] = [1,2,3,4,5]; // a = 1, b = 2, others = [3,4,5]

REST ELEMENT MUST BE THE LAST ELEMENT OF THE ARRAY. THERE CAN BE ONLY ONE.

Can be used in objects to pick properties out of existing objects.

const { sat, ...weekdays } = restuarant.openingHours; // creates an object of sat and an object of weekdays which includes all the properties of the remaining days less saturday.
Use case:

Can be used in functions when any number of arguments can be passed:

// rest parameter
const add = function (...numbers) {
  let sum = 0;
  for( let i = 0; i<numbers.length; i++) sum += numbers[i];
  return sum;
}

// can pass any number of arguments
add(2,3);
add(1,2,5,6);
const x = [23,5,7];
add(...x); // spread parameter to pass each value of the array.

The above example allows you to pass either an array or multiple single arguments through the function parameters.

Additional use in method

restaurant = {
 orderPizza = function(mainIngredient, ...otherIngredients){
  // will create a variable of first value of the arguement, and then an array of all the other arguments.
 }
};

The spread and the rest look exactly the same but work in opposite ways depending on where they are used.

Spread: Used where we would otherwise write values seperated by a comma

Rest: Used where we would otherwise write variable names separated by commas.

JavaScript overview

High-Level

Low-level languages like C need a dev to manage resources manually. JS is high-level so does not have to worry as system resource management happens automatically (abstractions).

+ easy to use and learn
– not as fast or optimised

Garbage-collected

Automatically clears unused objects from memory

Interpreted or Just-in-time compiled

ones and zeros (machine-code) via compiling / interpretation via the javascript engine. The engine compiles the source code to machine code and then immediately executes it without putting it in a portable file. Faster than compiling it line by line.

STEPS:

  • Parsing (AST) goes through the code and turns it into a tree
  • Compilation – turns it into machine code
  • Execution – (happens in the call stack) – Code is reoptimised during execution.

Multi-paradigm

More than one way to skin a cat. Imperative / declarative.

  • Procedural programming (linear)
  • Object-oriented programming (OOP)
  • Functional programming (FP)

Prototype-based object-oriented

Template/blueprint.

First-class functions

Functions used as variables. Can be passed to other functions.

Dynamic

Dynamically typed. Variable datatypes not assigned manually, js assigns them. A bit buggy – Typescript resolves

Non-blocking event loop

Concurrency model – JS engine handles multiples tasks at the same time although runs in one single thread. Event loops avoid long running tasks blocking.

JS ENGINE

Engine executes JS code. All browsers have their own engines. Chrome uses V8 (also powers node JS) for example.

All engines have a call stack and a heap.

CALL STACK
Is where code is executed.

HEAP
Is where objects are stored.

Javascript runtime in the browser

Runtime = is everything in the browser required to run javascript: engine, web APIs (accessed through global window), callback queue (click, timer, data)

Execution Concept

  • Variable environment
  • scope chain
  • this keyword

3 types of Scope

GLOBAL, FUNCTION, BLOCK (ES6)

Global Scope

These variables are declared outside of function and block and are accessible anywhere.

Function Scope (local scope)

These variables only accessible inside function.

Block Scope

Everything within curly braces (if or while loops). Only let or const variables (not var wehich is function-scoped). Functions are block scoped (in strict mode)

Scope Chain

Variable Lookup. A scope has access to variable from all outer (parent) scopes.

Hoisting

Hoisting makes some types of variables accessible/ usable in the code before they are actually declared (lifted to the top of the scope)

Hoisted: function dec & var, function expressions and arrows (depends on declared with let or const)

TEMPORAL DEAD ZONE

Javascript Fundementals (Part 1)

The Complete JavaScript Course 2025

High-level object-oreinted multi-paradigm programming language

VERSIONS:

ES6 is Modern Javascript (2015)

Values and Variables

  • Never use: function. new or name as variables. Prefix with _ or $ to use.
  • useCamelCase

Data Types

Every value is either OBJECT or PRIMITIVE

PRIMITIVE DATATYPES:

  • Number (floating point numbers)
  • Strings (sequence of characters
  • Boolean (true / false)
  • Undefined (empty value)
  • Null (empty value)
  • Symbol (ES2015) – Unique cannot be changed
  • BigInt – Massive numbers

Javascript has dynamic typing – it automatically assigns data type.

typeof – used to display what data type the variable is.

Declaring variables

var is legacy, use let or const. Use const where possible.

Use let if the variable can change.

Use const if the value of the variable cannot be changed (immutable) (also cannot be empty).

Operators

math (+ – / * x**y), assignment (= += -= *= ++ –), comparison (<> ===)

OPERATOR PRECEDENCE

Precedence Associativity Individual operators Notes
18: grouping n/a Grouping
(x)
[1]
17: access and call left-to-right Member access
x.y
[2]
Optional chaining
x?.y
n/a Computed member access
x[y]
[3]
new with argument list
new x(y)
[4]
Function call
x(y)
import(x)
16: new n/a new without argument list
new x
15: postfix operators n/a Postfix increment
x++
[5]
Postfix decrement
x--
14: prefix operators n/a Prefix increment
++x
[6]
Prefix decrement
--x
Logical NOT
!x
Bitwise NOT
~x
Unary plus
+x
Unary negation
-x
typeof x
void x
delete x [7]
await x
13: exponentiation right-to-left Exponentiation
x ** y
[8]
12: multiplicative operators left-to-right Multiplication
x * y
Division
x / y
Remainder
x % y
11: additive operators left-to-right Addition
x + y
Subtraction
x - y
10: bitwise shift left-to-right Left shift
x << y
Right shift
x >> y
Unsigned right shift
x >>> y
9: relational operators left-to-right Less than
x < y
Less than or equal
x <= y
Greater than
x > y
Greater than or equal
x >= y
x in y
x instanceof y
8: equality operators left-to-right Equality
x == y
Inequality
x != y
Strict equality
x === y
Strict inequality
x !== y
7: bitwise AND left-to-right Bitwise AND
x & y
6: bitwise XOR left-to-right Bitwise XOR
x ^ y
5: bitwise OR left-to-right Bitwise OR
x | y
4: logical AND left-to-right Logical AND
x && y
3: logical OR, nullish coalescing left-to-right Logical OR
x || y
Nullish coalescing operator
x ?? y
[9]
2: assignment and miscellaneous right-to-left Assignment
x = y
[10]
Addition assignment
x += y
Subtraction assignment
x -= y
Exponentiation assignment
x **= y
Multiplication assignment
x *= y
Division assignment
x /= y
Remainder assignment
x %= y
Left shift assignment
x <<= y
Right shift assignment
x >>= y
Unsigned right shift assignment
x >>>= y
Bitwise AND assignment
x &= y
Bitwise XOR assignment
x ^= y
Bitwise OR assignment
x |= y
Logical AND assignment
x &&= y
Logical OR assignment
x ||= y
Nullish coalescing assignment
x ??= y
right-to-left Conditional (ternary) operator
x ? y : z
[11]
right-to-left Arrow
x => y
[12]
n/a yield x
yield* x
Spread
...x
[13]
1: comma left-to-right Comma operator
x, y

Modifying local Hosts file

  • Launch Terminal, type sudo nano /private/etc/hosts and press Return. You’ll need to also enter your admin password to execute it, as with all sudo commands.
  • You will now have the hosts file open in the Nano editor. Use the arrow keys on your keyboard, to navigate and edit the file.
  • Like with the Windows method above you should just add the desired IP followed by the host name (or domain name).
  • Press Control-O to save the file.
  • Use your Web browser to test the changes and flush the cache with dscacheutil -flushcache if they still haven’t taken into effect.

Increasing Maximum Upload File Size in WordPress

If WordPress has been installed via Softilicious on the shared server then you may find that there is a 12MB upload limit imposed. This can affect your ability to import sites using the All-In-One WP Migration plug-in.

To fix this you can edit the php.ini file through cPanel.

  • Open cPanel
  • Open MultiPHP INI Editor
  • Scroll down to find the PHP directive “post_max_size” and change this to 128M (for example)
  • Do the same for the “upload_max_filesize” directive
  • Click Apply

Adding AOS scrolling animation to WordPress

Add aos.scss to sass/assets folder and import in child-theme.scss

Add aos.js to src/js/

Add path to gulpfile.js

Add AOS.init to custom-javascript.js:

AOS.init({
delay: 150, // values from 0 to 3000, with step 50ms
duration: 1000,
mirror: true
});

Installing BX Slider on WordPress

To install BX Slider on WordPress requires 3 stages:

1. Create the bxslider.js file and add to Gulp Script Compiler

  • Get the js file from the BX Slider GitHub project source
  • Copy and paste to a new file in src/js/bxslider.js
  • Open gulpfile.js
  • add new path to the scripts variable under gulp.task( ‘scripts’ … paths.dev + ‘/js/bxslider.js’

2. Add CSS

  • Get CSS from source. Copy and paste to new file sass/assets/bx-slider.scss
  • Find and replace all instances of images/ with the name of your images folder (ie img)
  • Edit sass/child-theme.scss to include the bx-slider Sass

3. Copy images to Image folder

  • Save bx-loader.gif and controls.png from Project source to your images folder

Edit your custom js to trigger

  • Add the jQuery code:
$("#testimonial-slider").bxSlider({

adaptiveHeight: true,

auto: true,

pause: 8000,

mode: "fade",

pager: false,

controls: false

});

 

Customising WordPress Admin Backend

  1. Add admin.php to inc folder
  2. Add login.css to css folder
  3. Require admin.php in functions.php

1. Add admin.php to inc folder

<?php
/*
This file handles the admin area and functions.
You can use this file to make changes to the
dashboard. Updates to this page are coming soon.
It's turned off by default, but you can call it
via the functions file.

Developed by: Eddie Machado
URL: http://themble.com/pedrev/

Special Thanks for code & inspiration to:
@jackmcconnell - http://www.voltronik.co.uk/
Digging into WP - http://digwp.com/2010/10/customize-wordpress-dashboard/

*/


/************* CUSTOM LOGIN PAGE *****************/

// calling your own login css so you can style it

//Updated to proper 'enqueue' method
//http://codex.wordpress.org/Plugin_API/Action_Reference/login_enqueue_scripts
function custom_login_css() {
wp_enqueue_style( 'custom_login_css', get_stylesheet_directory_uri() . '/css/login.css', false );
}

// changing the logo link from wordpress.org to your site
function custom_login_url() { return home_url(); }

// changing the alt text on the logo to show your site name
function custom_login_title() { return get_option( 'blogname' ); }

// calling it only on the login page
add_action( 'login_enqueue_scripts', 'custom_login_css', 10 );
add_filter( 'login_headerurl', 'custom_login_url' );
add_filter( 'login_headertitle', 'custom_login_title' );


/************* CUSTOMIZE ADMIN *******************/

/*
I don't really recommend editing the admin too much
as things may get funky if WordPress updates. Here
are a few funtions which you can choose to use if
you like.
*/

// Custom Backend Footer
function custom_admin_footer() {
_e( '<span id="footer-thankyou">Developed by <a href="http://samwell.me" target="_blank">Duncan Samwell</a></span>', 'understrap' );
}

// adding it to the admin area
add_filter( 'admin_footer_text', 'custom_admin_footer' );


// Add sidebar (widgets) and Menus editing capabilities to Editor role
$role = get_role('editor'); 
$role->add_cap('edit_theme_options');
?>

2 Create a login.css

/******************************************************************
Site Name:
Author:

Stylesheet: Login Stylesheet

This stylesheet is loaded (if admin.php is setup in your
functions file) on the login page. This way you can style
the login page. It won't affect any other page, admin or front-end.

For more info, check out the codex:
http://codex.wordpress.org/Creating_Admin_Themes

******************************************************************/
/* the form box */
body.login {
background: rgb(113, 0, 33); /* Old browsers */
background: -moz-linear-gradient(
left,
rgba(113, 0, 33, 1) 1%,
rgba(139, 0, 40, 1) 50%,
rgba(113, 0, 33, 1) 100%
); /* FF3.6+ */
background: -webkit-gradient(
linear,
left top,
right top,
color-stop(1%, rgba(113, 0, 33, 1)),
color-stop(50%, rgba(139, 0, 40, 1)),
color-stop(100%, rgba(113, 0, 33, 1))
); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(
left,
rgba(113, 0, 33, 1) 1%,
rgba(139, 0, 40, 1) 50%,
rgba(113, 0, 33, 1) 100%
); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(
left,
rgba(113, 0, 33, 1) 1%,
rgba(139, 0, 40, 1) 50%,
rgba(113, 0, 33, 1) 100%
); /* Opera 11.10+ */
background: -ms-linear-gradient(
left,
rgba(113, 0, 33, 1) 1%,
rgba(139, 0, 40, 1) 50%,
rgba(113, 0, 33, 1) 100%
); /* IE10+ */
background: linear-gradient(
to right,
rgba(113, 0, 33, 1) 1%,
rgba(139, 0, 40, 1) 50%,
rgba(113, 0, 33, 1) 100%
); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#710021', endColorstr='#710021',GradientType=1 ); /* IE6-9 */

/*
This is the WordPress logo in the admin area.
You'll have to load your own images and mess
with the width and height.
*/
/*
You'll have to override some of the default styles
but since we're referencing the id, it should be easy.
*/
/* login button*/
}
body.login h1 a {
background: url(../img/broadland-consultants-logo-trans.png) no-repeat top
center;
/* make sure to replace this! */
width: 310px;
height: 220px;
text-indent: -9999px;
overflow: hidden;
padding-bottom: 0;
display: block;
margin-bottom: 10px;
}
body.login form {
margin-top: 0;
margin-left: 8px;
padding: 26px 24px 46px;
font-weight: normal;
background: #8b0028;
border: 1px solid #8b0028;
color: #8b0028;
-webkit-border-radius: 3px;
-khtml-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
box-shadow: 0 0 15px 3px rgba(0, 0, 0, 0.2);
}
body.login form .input {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue",
sans-serif;
font-weight: 200;
font-size: 24px;
width: 97%;
padding: 3px;
margin-top: 2px;
margin-right: 6px;
margin-bottom: 16px;
border: 1px solid #8b0028;
background: #fbfbfb;
outline: none;
-webkit-box-shadow: inset 1px 1px 2px rgba(200, 200, 200, 0.2);
-moz-box-shadow: inset 1px 1px 2px rgba(200, 200, 200, 0.2);
box-shadow: inset 1px 1px 2px rgba(200, 200, 200, 0.2);
}

body.login label {
color: #ccc;
}

body.login #nav a,
body.login #backtoblog a {
color: #fff;
}

#login {
padding: 5% 0 0;
}

3 Require admin.php in functions.php

Add the require statement in functions.php

require get_stylesheet_directory() . '/inc/admin.php';

Useful WordPress Functions: Global Options

/*===================================================================================
* Add global options

Courtesy of Raelene Morey
https://gist.github.com/raewrites/bb060a35594d546464d2

Use get_option() function to display info ie: echo get_option(company_phone)
* =================================================================================*/

/**
 *
 * The page content surrounding the settings fields. Usually you use this to instruct non-techy people what to do.
 *
 */
function theme_settings_page(){ 
	?>
	<div class="wrap">
		<h1>Contact Info</h1>
		<p>This information is used around the website, so changing these here will update them across the website.</p>
		<form method="post" action="options.php">
			<?php
			settings_fields("section");
			do_settings_sections("theme-options");
			submit_button();
			?>
		</form>
	</div>
	
	<?php }

/**
 *
 * Next comes the settings fields to display. Use anything from inputs and textareas, to checkboxes multi-selects.
 *
 */

 // Business Name
function display_company_name_element(){ ?>
	
	<input type="text" name="company_name" placeholder="Official Company Name" value="<?php echo get_option('company_name'); ?>" size="35">

<?php }

 // Business Tagline
function display_company_tagline_element(){ ?>
	
	<input type="text" name="company_tagline" placeholder="Company Tagline" value="<?php echo get_option('company_tagline'); ?>" size="135">

<?php }

// Address
function display_company_address_element(){ ?>
	
	<input type="text" name="company_address" placeholder="Enter company address" value="<?php echo get_option('company_address'); ?>" size="135">

<?php }


// Phone
function display_company_phone_element(){ ?>
	
	<input type="tel" name="company_phone" placeholder="Enter phone number" value="<?php echo get_option('company_phone'); ?>" size="35">

<?php }

// Fax
function display_company_fax_element(){ ?>
	
	<input type="tel" name="company_fax" placeholder="Enter fax number" value="<?php echo get_option('company_fax'); ?>" size="35">

<?php }

// Email
function display_company_email_element(){ ?>
	
	<input type="email" name="company_email" placeholder="Enter email address" value="<?php echo get_option('company_email'); ?>" size="35">
	
<?php }

// Elevate Platform URL
function display_company_login_element(){ ?>
	
	<input type="url" name="company_login" placeholder="Paste Elevate Pltform login URL address" value="<?php echo get_option('company_login'); ?>" size="35">
	
<?php }

// Facebook
function display_company_facebook_element(){ ?>
	
	<input type="url" name="company_facebook" placeholder="Paste Facebook URL address" value="<?php echo get_option('company_facebook'); ?>" size="35">
	
<?php }

// twitter
function display_company_twitter_element(){ ?>
	
	<input type="url" name="company_twitter" placeholder="Paste twitter URL address" value="<?php echo get_option('company_twitter'); ?>" size="35">
	
<?php }

// LinkedIn
function display_company_linkedin_element(){ ?>
	
	<input type="url" name="company_linkedin" placeholder="Paste LinkedIn URL address" value="<?php echo get_option('company_linkedin'); ?>" size="35">
	
<?php }

// Google+
function display_company_google_element(){ ?>
	
	<input type="url" name="company_google" placeholder="Paste Google+ URL address" value="<?php echo get_option('company_google'); ?>" size="35">
	
<?php }

/**
 *
 * Here you tell WP what to enqueue into the <form> area. You need:
 *
 * 1. add_settings_section
 * 2. add_settings_field
 * 3. register_setting
 *
 */

function display_custom_info_fields(){
	
	add_settings_section("section", "Company Information", null, "theme-options");
    add_settings_field("company_name", "Official Company Name.", "display_company_name_element", "theme-options", "section");
	add_settings_field("company_tagline", "Official Company Tagline.", "display_company_tagline_element", "theme-options", "section");
	add_settings_field("company_address", "Company Address", "display_company_address_element", "theme-options", "section");
	add_settings_field("company_phone", "Company Phone No.", "display_company_phone_element", "theme-options", "section");
	add_settings_field("company_fax", "Company Fax No.", "display_company_fax_element", "theme-options", "section");
    add_settings_field("company_email", "Company Email address", "display_company_email_element", "theme-options", "section");
    add_settings_field("company_login", "Company Elevate Platfom login URL", "display_company_login_element", "theme-options", "section");
	add_settings_field("company_facebook", "Company Facebook URL", "display_company_facebook_element", "theme-options", "section");
    add_settings_field("company_twitter", "Company Twitter URL", "display_company_twitter_element", "theme-options", "section");
    add_settings_field("company_linkedin", "Company LinkedIn URL", "display_company_linkedin_element", "theme-options", "section");
    add_settings_field("company_google", "Company Google+ URL", "display_company_google_element", "theme-options", "section");

    register_setting("section", "company_name");
    register_setting("section", "company_tagline");
	register_setting("section", "company_address");
	register_setting("section", "company_phone");
	register_setting("section", "company_fax");
	register_setting("section", "company_email");
	register_setting("section", "company_login");
    register_setting("section", "company_facebook");
    register_setting("section", "company_twitter");
    register_setting("section", "company_linkedin");
    register_setting("section", "company_google");
	
}

add_action("admin_init", "display_custom_info_fields");

/**
 *
 * Tie it all together by adding the settings page to wherever you like. For this example it will appear
 * in Settings > Contact Info
 *
 */

function add_custom_info_menu_item(){
	
	add_menu_page("Contact Info", "Contact Info", "edit_pages", "contact-info", "theme_settings_page", null, 99);
	
}

add_action("admin_menu", "add_custom_info_menu_item");


// Add editor capability to save options for this particular menu item
add_filter( 'option_page_capability_section', 'bc_settings_permissions', 10, 1 );
function bc_settings_permissions( $capability ) {
    return 'edit_pages';
}


// Function to show the social media settings

function social_media_footerlinks($platform) {
    if ( get_option('company_' . $platform)) {
        echo "<div class='" . $platform . "'><a href='" . get_option('company_' . $platform) . "' target='_blank'><span class='fa fa-" . $platform . "'></span></a></div>";
    }
}