Javascript

Please Do the Following 👇Before Picking a JavaScript Framework

I remember months ago, I picked up React, I struggled with some concepts like separation of concerns (creating different UI components), understanding React hooks, etc, I was frustrated at a point and I wanted to blame it on the framework 😂😂. After researching articles and watching a few videos, I discovered I was struggling to understand the difference between Vanilla JS and a Framework

So before you pick a JavaScript framework, make sure you understand the basics of HTML, CSS, JavaScript, and some advanced JavaScript features that I would be talking about in this post.

This post wouldn’t go into so many details but I would try to explain them in simpler terms, I would add references to other guides if you would like to study a bit further.

This post is going be in series because I won’t be covering all these advanced features of JavaScript in a single post.

1. Declaring Variables in ES6
2.Template Strings
3.Arrow Functions
4. ES6 Objects and Arrays (Destructuring Assignment, Object Literal Enhancement & Spread Operator)
5. ES6 Modules and Transpiling ES6 (Webpack and Babel)
7. Promises
8.Classes
9. Functional Programming(Pure Functions & Higher-Order Functions)

 

1.Declaring Variables in ES6

Before ES2015;

i. The only way to declare a variable was with the var keyword but we have new keywords now like let and const.
ii.JavaScript had only two types of scope, Global Scope, and Function Scope.

Global Scope
Variables declared Globally (outside any function) have Global Scope.

var fruit = "Strawberry";

function makeSmoothie() {
  // code here can also use fruit
}

Function Scope
Variables declared Locally inside a function.

// code here can NOT use fruit

function makeSmoothie() {
  var fruit = "Orange";   // code here CAN use fruit 
}

Before ES2015 JavaScript, variables declared with the var keyword can not have Block Scope.

Variables declared with the let keyword can have Block Scope.

Let
Let (lexical variable scoping) allows you to declare variables that are limited to the scope of a block statement, or expression (if/else) on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Using let protects the value of the global variable.

var topic = "Mathematics";

if (topic) 
{ let topic = "Biology"; 
console.log(topic) ; // Biology 
} 
console.log(topic); // Mathematics</syntax-highlighted class="cm-s-mozilla">

Here the value of the topic is not reset outside of the block and has been redeclared.

Const
A constant is a variable that cannot be changed and it defines a constant reference to a value.
i. Variables defined with const behave like let variables, except they cannot be reassigned and redeclared:
ii. const also works on objects and arrays.

/*
i. We cannot reset the value of a constant variable, and it will generate
 a console error if we try to overwrite the value: 
*/ 
var name = "Joy"; 
name = "Mark"   // Uncaught TypeError: Assignment to constant variable.

//ii. You can change the properties of a constant object: 
var person= { 
   name:"Mark Jones", 
   favorite_food:"Spaghetti" 
   }; 
person.favorite_food = "Oatmeals"; 

//iii. But you can NOT reassign a constant object, this will throw an error 
var person= {name:"Mark Jones", favorite_food:"Spaghetti"}; 
var person= {name:"Mary Obi", favorite_food:"Jollof Rice"}; // ERROR

// The same applies to arrays 
var car = []; // It's possible to push items into the array 
car.push("Volvo"); // ["Volvo"]

2. Template Strings

Template strings provide us with an alternative to string concatenation. It introduces a completely different way of solving these problems.

Template Strings use back-ticks ``rather than the single or double quotes, we’re used to with regular strings. 

Template Strings can contain placeholders for string substitution using the ${ }syntax.

Traditional string concatenation uses plus signs or commas to compose a string using variable values and strings:

var lastName=" Mark";
var firstName="Jones";
console.log("My name is" + " " + lastName + "  " + firstName ) //  "My name is Mark Jones"

A template string could thus be written as follows:

console.log(`My name is ${lastName} ${firstName}`) // "My name is Mark Jones"


3. Arrow Functions

With arrow functions, you can create functions without using the function and the return keyword.

// Old
var num = function(a,b) {
return a * b;
}
// Arrow functions
var num = (a,b) => a *b ;

console.log(num(4,7));   // 28

 

4. ES6 Objects and Arrays

ES6 allows you to work with objects and arrays with the following features.
i. Destructuring
ii. object literal enhancement and the
iii. Spread operator.

Destructuring

i. Object destructuring

The destructuring assignment allows you to unpack values from arrays, or properties from objects, into distinct variables.

Consider this pizza object, we can scope toppings locally and change it’s variables too.

var pizza = {
 types: ["meat", "cheese", "Buffalo"], 
toppings: ["Gorgonzola", "artichoke hearts", "prosciutto", "red onion"]
}

var {toppings} = pizza

toppings = ["BBQ sauce", "grilled chicken", "scallions", "cheddar cheese"]

console.log(toppings) // Array(4) [ "Gorgonzola", "artichoke hearts", "prosciutto", "red onion" ]

ii. Function destructuring

Here we would unpack fields from objects and pass them as a function parameter

var Person = {
   user_id: "XYX-OOO-674578-34",
  fullName: {
    firstName: 'Mac',
    lastName: 'Lewis'
},
    Age: 45,
   favoriteFood: 'Oatmeals'
};

//Instead of using dot notation syntax to dig into objects, we can destructure the values that we need out of Person:

function displayId({user_id}) {
  return user_id;
}

function displayFullName({fullName: {firstName: firstname,lastName: lastname}}) {
  return ` User full name is ${firstname} ${lastname}`;
}
function userFood({favoriteFood,fullName: {firstName: firstname}}) {
  return ` ${firstname} favorite food is  ${favoriteFood}`;
}


console.log(displayId(Person));   //XYX-OOO-674578-34
console.log(displayFullName(Person));  //User full name is Mac Lewis
console.log(userFood(Person)); // Mac favorite food is  Oatmeals

iii. Destructuring Arrays

//Assigning the first value of an array to a new variable

var [greetings]= ["Hello", "Hi", "How are you?","Bonjour"]

console.log(greetings) //Hello

//using list  matching  using  commas, eg we want to access the third and last value  
var [,,,salutation] = ["Hello", "Hi", "How are you?","Bonjour"]
var [,,question] = ["Hello", "Hi", "How are you?","Bonjour"]

console.log(salutation)  //Bonjour
console.log(question)  // How are you?

//Combined Array and Object Destructuring
/*
Say you want the third element in the array pizza below, 
and then you want the toppings property in the object, 
you can do the following
*/
const pizza = [
  { type: "Margherita", toppings: ["tomatoes", "sliced mozzarella", "basil","extra virgin olive oil"]},
  { type: "Marinara", toppings: ["garlic","oregano"]},
  { type: "Chicago", toppings: ["sausage", "pepperoni", "onion"]}
];

const [,, {toppings}] = pizza;
console.log(toppings);  //Array(3) [ "sausage", "pepperoni", "onion"]
object literal enhancement

Object literal enhancement is the opposite of destructuring. It is the process of restructuring or putting back together.
i. we can grab variables from the global scope and turn them into an object

var name = "Joy Adams"
var age = 34

const Person = {name,age}

console.log(Person)  //Object { name: "Joy Adams", age: 34 }

ii. With object literal enhancement, you can also create object methods

var name = "Joy Adams";
var age = 34;
//create a method that returns the person age
var returnAge = function() {  
 return `${this.name} is ${this.age} old`
};

var Person={name,age,returnAge}
console.log(Person.returnAge())  //Joy Adams is 34 old
The Spread Operator

The spread operator uses three dots (…) that can perform the following tasks.
i. combining the contents of arrays and objects.
ii. It can be used to get some, or the rest, of the items in an array
iii. To collect function arguments as an array

//combine arrays
var primary_colors = ["red", "blue", "yellow"]
var secondary_colors = ["green", "orange"]

var colors = [...primary_colors, ...secondary_colors]

console.log(colors) //Array(5) [ "red", "blue", "yellow", "green", "orange" ]

//combine objects
var morning = {  breakfast: "oatmeal",  dessert: "orange smoothie and French fries"};
var lunch = "Nigerian Jollof Rice";
var dinner = "mac and cheese";
var foodTimetable = {  ...morning, lunch, dinner}

console.log(foodTimetable)   //Object { breakfast: "oatmeal", dessert: "orange smoothie and French fries", lunch: "Nigerian Jollof Rice", dinner: "mac and cheese" }


//Get some items in an array
var courses = ["Economics", "Biology", "Mathematics", "Chemistry"]
var [Commerce, ...Science] =  courses
console.log(Science)   //Array(3) [ "Biology", "Mathematics", "Chemistry" ]


//collect function arguments as an array
function directions(...args) {
        var [city1, ...city2] = args
      return `I'm driving through ${args.length} towns and going to  ${city2}`
    }

directions("Port Harcourt", "Lagos City")
//"I'm driving through 2 towns and going to  Lagos City"


function ingredients(...args) {
        var [...foodstuff] = args
      return `I want to make Nigerian Jollof rice with the following ${args} ingredients`
    }
ingredients("Rice", "Pepper","Vegetable","beef")
//"I want to make Nigerian Jollof rice with the following Rice,Pepper,Vegetable,beef ingredients"

5. ES6 Modules and Transpiling ES6 (Webpack and Babel)

ES6 Modules

A JavaScript module is a piece of reusable code that can easily be incorporated into other JavaScript files.

index.html
main.js
modules/
    pizza.js
    cake.js

Your directory structure looks like the following. we want to incorporate pizza.js and cake.js into the following files ( main.js)

The directory’s two modules are described below:

  • pizza.js — contains:
    • name: an array showing different pizza types
    • makeMargherita (): A method for making Margherita pizza
  • cake.js — contains:
    • name: an array showing different cake types
    • makeVanilla(): a method for making Vanilla cake
    • makeChocolate(): a method for making a Chocolate cake

Exporting module features

modules/pizza.js

var name = [" Magherita", "Pepperoni", "Cheese"];

function makeMagherita() {
return "please make a vanilla cake";
}
modules/cake.js

var name = [" chocolate", "vanilla", "red velvet"];

function makeVanilla() {
  return "please make a vanilla cake";
}

function makeChocolate() {
  return "please make a chocolate cake";
}

A more useful way of exporting all the items you want to export is to use a single export statement at the end of your module file.

modules/cake.js
export { name, makeVanilla,makeChocolate};
modules/pizza.js
export { name, makeMargherita };

Importing features into your script

Modules can be consumed in other JavaScript files using the import statement. Modules with multiple exports can take advantage of object destructuring.

main.js


import { name, makeVanilla,makeChocolate } from './modules/cake.js';
import { name, makeMargherita, makePepperoni } from './modules/pizza.js';

var margheritaPizza = makeMargherita();
let vanillaCake = makeVanilla();

Applying the module to your HTML

To add a module to an HTML file, you need to includetype=" module"in the <script>element, to declare this script as a module:

index.html

<script type="module" src="main.js"></script>modules/
Transpiling ES6

Not all web browsers support ES6, and the only way to be sure that your ES6 code will work is to convert it to ES5 code before running it in the browser. 

Transpiling simply means taking out ES6 code and converting it into ES5 so it can be read by all browsers.

Let me show you an example, ES6 code before Babel transpiling ( you can try it out here)

//combine objects
var morning = {  breakfast: "oatmeal",  dessert: "orange smoothie and French fries"};
var lunch = "Nigerian Jollof Rice";
var dinner = "mac and cheese";
var foodTimetable = {  ...morning, lunch, dinner}

console.log(foodTimetable)

After we run the transpiler on this code, here is what the output will look like

"use strict";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

//combine objects
var morning = {
  breakfast: "oatmeal",
  dessert: "orange smoothie and French fries"
};
var lunch = "Nigerian Jollof Rice";
var dinner = "mac and cheese";

var foodTimetable = _objectSpread(_objectSpread({}, morning), {}, {
  lunch,
  dinner
});

console.log(foodTimetable);

Since not all browsers support all ES6 features you need to transpile your ES6 code into a compiler such as Babel or module bundler like Webpack.

I wouldn’t go into so many details about Babel or Webpack, but you could always visit the website to learn more.

 

In the next post, we will have a look at promises, classes, and functional programming.
I hope you enjoyed the article, share your thoughts in the comment section below.

References

 

 

 

 

2 Comments

  • Thanks for this ma’am. Do I need to go in depth in css before taking React js for native app development?.

    • Hello Frank, I have not worked on a react native project before , just used react for the web but based on my learning experience, I did the following
      1. Learnt this first Typography, Layout, Colors, and Backgrounds (the fundamentals)
      2. Creating responsive web design (media queries)
      3. CSS Grid and Flex box.

Leave a Reply

Your email address will not be published. Required fields are marked *