5 Basic Javascript Concepts

Ogunmefun Anjolaoluwa
6 min readApr 13, 2022
A screen showing blocks of code
Photo by Markus Spiske on Unsplash

Javascript!… Without argument, we can easily agree that it is a buzzword among developers for being one of the most popular programming languages of our time. It has gained popularity for its simplicity, versatility, and speed (to mention a few). About 96% of websites today have Javascript powering their client-side and despite originally being designed as a client-side language, JavaScript has now made its way to the server-side of websites (thanks to Node. js).

Javascript(JS) is a very broad programming language and has loads of interesting concepts that power it. This article is focused on 5 basic concepts that are important to writing effective JS code.

1. Use strict

Strict mode allows you to place a program or a function in a strict operating context. Its major advantage is that it makes debugging easier. Code errors that would have otherwise been ignored or would have failed silently will now generate errors or throw exceptions. This, therefore, directs you quickly to the probable source of error.

In a JS file, the strict mode is enabled by typing the string "use strict” and putting it at the top of the file or function

function myFunction(){"use strict"//code to run};

Features of use strict

i. Using a variable before declaring it now throws an error. Thereby, preventing accidental globals and syntax errors.

ii. It prevents using reserved Javascript words as variable names

iii. In strict mode, you cannot delete functions, variables, or function arguments.

"use strict"var moo = 1;
delete moo;
function foo(){};
delete foo;
function fcoo(arg)[
delete arg;
};
//output: SyntaxError: Delete of an unqualified identifier in strict mode.

Whatever context “use strict” is being used: globally at the top of the file, or locally in a function, the code blocks that follow are put in a strict operating context.

2. Hoisting

Hoisting is JS default behavior of moving variable and function declarations to the top of its enclosing scope.

"use strict"
console.log(a);
var a = 2;
//output: undefined

I would expect the example above to throw an error in the strict mode because I’m trying to access a variable before it’s declared but instead, I get undefined as the result.

When JS sees a line like var a = 2 , it splits it into two lines.

The first part is the variable declaration var a and it is placed at the top of the file or function

The second part assigns the variable its value i.e a = 2 . JS interprets the above example as;

"use strict"
var a ;
console.log(a);
a = 3

At the point of logging the value of a , the variable has only been declared. In JS a declared variable that hasn’t been initialized by default is undefined.

The rule of hoisting also applies to functions. The function declaration is moved to the top of its enclosing scope.

myName("Laura");

function myName(name) {
console.log("My name is " + name);
}
//output: "My name is Laura"

3. Destructuring

Destructuring is a way of extracting values into variables from data stored in an object or array. It is a short and effective way of pulling out values.

//OBJECT DESTRUCTURINGconst person = {
first: "Laura"
last: "Cheng"
age: 20
};
//Don'tconst f = person.first;
const l = person.last;
const a = person.age;
// Doconst{ first:f, last:l, age:a } = person;
OR

const {first, last, age} = person;
//ARRAY DESTRUCTURINGconst fruits = ["mango", "apple", "orange", "pineapple"];//Don'tconst mango= fruits[0];
const apple= fruits[1];
//Doconst [mango, apple, ...others] = fruits//rest[0] = "orange"
//rest[1] = "pineapple"

Usually, if the array is longer than the list at the left, the “extra” items are omitted. But If we’d like also to also extract the remaining items, we can add one more parameter that gets “the rest” using three dots "..." . The value of othersis the array of the remaining array elements.

4. Callback Function

A callback function is a function A that gets passed into another function B as an argument that B then calls. A callback executes code in response to an event.

Callbacks can either be synchronous or asynchronous. Synchronous operations are performed one at a time. In other words, you need to wait for a task to finish before you can move to the next one. While in asynchronous operations, you can move to another task before the previous one finishes. That is, the tasks are not sequential.

A synchronous callback is executed during the execution of the parent function.

function printName(name) {
console.log("my name is " + name);
}
function greeting(name, fnc) {
console.log("welcome " + name);
fnc(name);
}
console.log(greeting("Laura", printName));//output
//welcome Laura
//my name is Laura

An asynchronous callback is executed after the parent function has been executed.

Suppose that we need to write a script that fetches data from a remote server and processes it after we get a result. However, making a request to a remote server takes time depending on the network speed. We can do that by, passing the process() function to the request() function and execute the process() function inside the request() function once the request completes, like this:

function process(data) {
console.log(`Processing ${data}`);
}
let url = 'https://www.someserevertovisit.com'
function request(url, callback) {
setTimeout(() => {
// script to request data from server
console.log(`Requesting ${url} ...`);

// process the result
callback(url);
}, 2000);
}
console.log(request(url, process));//output
// Requesting https://www.someserevertovisit.com ...
// Processing https://www.someserevertovisit.com

When a callback is used to continue code execution after an asynchronous operation, the callback is called an asynchronous callback function.

5. Promise

Promises are used for Javascript asynchronous processes. They are useful to avoid endless callback chains, they provide improved code readability and better Error Handling.

A promise has 3 possible states:

i. Pending — the initial state.

ii. Resolve — operation completed successfully.

iii. Reject — operation failed.

A promise is created using the promise constructor

const promise = new Promise((resolve, reject) => {
// code to carry out operation
// ...
// return the state
if (success) {
resolve(value);
} else {
reject(error);
}
});

The promise constructor accepts a callback function that performs an asynchronous operation. This function is sometimes referred to as an executor. The executor accepts two arguments: resolve and reject.

If the promise completes successfully, the executor will call the resolve() function. But in the case of an error, the executor will call the reject() function. For example;

let done = trueconst isItDone = new Promise((resolve, reject) => {
if (done) {
const completed= 'The job is complete'
resolve(completed)
} else {
const incomplete= 'Still working on the job'
reject(incomplete)
}
})

In this example, the promise checks the done global constant, and if it evaluates to true, the promise enters the resolved state: otherwise, the reject callback is executed, putting the promise in a rejected state.

Consuming a Promise: then, catch, finally

  1. The then() method

To get the value of a promise when it’s resolved or rejected, you call the then() method of the promise object.

promise.then(onFulfilled,onRejected);

then() method takes two functions as parameters.

The first function is executed if the promise is resolved and a result is received. While the second function is executed if an error is received. (this second function is optional and there is a better way to handle error using the .catch() method)

2. The catch() method

This method is used to get the error only when the state of the promise is rejected.

The example below simulates both the then() and catch() method in action.

let done = trueconst isItDone = new Promise((resolve, reject) => {
if (done) {
const completed= 'The job is complete'
resolve(completed)
} else {
const incomplete= 'Still working on the job'
reject(incomplete)
}
})
const checkIfItsDone = () => {
isItDone
.then(result => {
console.log(result)
})
.catch(err => {
console.error(err)
})
.finally(_ => {
console.log("End of promise")
})
}

3. The finally() method

This method when used is always called at the end of the promise whether it resolves or rejects. It shines in a situation where you want to execute the same piece of code regardless of the promise outcome.

Javascript concepts are a hand full and cannot be exhausted in one article. There’s more to be explained in following articles. I hope you found this piece useful.

--

--

Ogunmefun Anjolaoluwa

The little girl who grew to become a Frontend Developer, who’s not so little anymore