JavaScript -Fundamentals

Uditha Janadara
5 min readFeb 25, 2021

What is JavaScript

Java Script is a Programming language that is used in web development. it responsible for dynamic content of a web page. JavaScript is supposed to run in a web browser, but it is possible to run outside the browser using node js runtime environment. So it means Java Script can use for both frontend and backend development.

Features of Java Script

JavaScript is a loosely typed programming language. it means you don’t need to specify what kind of data you are going to store in variables.

JavaScript is a single threaded programming language. programs are run using a single thread.

JavaScript works asynchronously. It continue the program execution without waiting for I/O operations.

JavaScript is an interpreted language. programs do not compile before it runs instead interpreter convert the program into machine code at the runtime.

JavaScript variables

JavaScript variables can define using several keywords. Each keyword has its own scope.

Windowvariables declared using window keyword have a global scope. those variables can access from anywhere from the webpage. it is not recommended to declare variables with global scope in JavaScript.

Var if a variable declared using var keyword outside a function, it has global scope. if declared inside a function it has functional scope. variables with functional scopes do not visible to outside the function.

(In strict mode, Var let you to redeclare the variables)

Let Variables declared using let keyword have block scope. those variables are visible only inside the block.

const const variables have block scope. you can not re declare those variables and can not change the variable value using re assignment.

JavaScript ‘this’ keyword

How this Keyword behave in Java Script?

In a Method this refer to the owner of the method

Ex: person = { firstName: "hello", lastName: "world", getFullname: function(){return this.firstName + this.lastName}};

above person object have getFullname method. this keyword inside the function refer the its owner, person object.

this keyword Aloneif this keyword use alone, it refer the global object. In a browser global object is [object window].

Ex: var x  =this;

in that case, this refer the [object window] .

also in strict mode, this refer to the global object when it use alone.

In a function In a function, this refer the global object(by default).

Ex: function  myFunction(){    return this;}

above function returns object window, the global object.

In a strict Functionstrict mode does not allow to default binding. So in a strict function, this will be undefined.

Ex: "use strict";function  myFunction(){    return this;}

In event handlersthis refer to the html element that receive the event.

Ex: <button onClick="this.style.display = 'none'"></button>

above example, this keyword refer to the button element.

JavaScript asynchronous behavior

Like mentioned earlier, JavaScript run on a single thread and it behave asynchronously.

Ex: function myFunction(){    let value = 0;    setTimeout(function(){        value = 10;         }, 2000);    console.log(value);}myFunction();

what will be the output of above function?

it will return the 0 to console.

why?

Because of the asynchronous behavior of JavaScript. in the above example, it does not wait for setTimeout function and continue the execution.

JavaScript Callbacks

In JavaScript, you can pass a function as an argument to another function. Those functions are called callback functions.

EX: function myFunction(callBack){        callBack();}function myCallback(){    alert("I am the callback");}myFunction(myCallback);

In the above example, myCallback has passed as an argument to myFunction. myCallback function will execute after the myFunction has finished its execution.

JavaScript callbacks are typically use with asynchronous functions.

Ex: function myFunction(callBack){

setTimeout(callBack(), 1000);
}

function displayMessage(){

alert("I will display after one second!");

}

myFunction(displayMessage);

Above example, displaymessage is a callback function and it has used with setTimeout function.it specify the time out to execute the callback function.

JavaScript Promises

The promise is an object that returns a single result by asynchronous operations in JavaScript. It represents the failure or success of the operation. JavaScript promise contains,

· callbacks (success and error)

· Producing code

· Consumer code

Ex: function checkEvennumber(number) {    let remainder = number % 2;    return new Promise(function (resolve, reject) {        if (remainder === 0) {            resolve("OK");        } else {            reject("No");        }    });}checkEvennumber(20).then(    function (message){alert(message);},    function (error){alert(error);}    );

Above promise object has the resolve and reject callbacks. resolve callback returns the success result of the producing code and reject callback returns the failure of the producing code.

Note: when initializing promise object, those callbacks can have different callback names, but they should be passed in the correct order.

Ones the asynchronous operations has completed, it returns the promise.

In the consumer code it calls another function according to the returned promise. Actually the callback functions passed to the promise are referred those functions in consumer code.

async functions

async functions are supposed to return a promise.

async function myFunction() {

return “I am a promise”;
}

myFunction().then(
function(value) {alert(value);},
function(error) {alert(error);}
);

await

The await keyword only used inside an async function.

Using await keyword will wait for a promise. Visually we cannot see promises in here, but they perform internally. It makes program operations virtually synchronous. But internally they perform asynchronously.

function getValue(){
return new Promise(function (resolve,error) {
setTimeout(function () {
let value = 10;
resolve(value);
}, 2000);
});
}

function setValue(value){
return value + 50;
}

function getNewValue(value){

return value *100;
}

async function print(){
let value = await getValue();
value = await getNewValue(value);
value = setValue(value);
return value;
}


print().then((function (value){
console.log(value);
}));

In the above example, using await keyword it makes program execution virtually synchronous. async function will return the output after executing in given order.

Arrow functions

Arrow functions are used to write functions in shorter syntax.

Ex: hello = function myfunction(){    return "hello";}

using arrow function:

hello = () => {return “Hi”}

It makes the function syntax shorter.

Also if the function contains one statement and it returns a value, brackets and return keyword not required.

hello = () => “Hi”;

Arrow function with parameter

welcome = (name,module) => “Hi “ + name +” welcome to “ + module;

if function contain only one parameter, parentheses are not required.

hello = name => “Hi “ + name;

Now you have a basic idea about JavaScript. Lets discuss furthermore about JavaScript from upcoming articles.

Thanks for reading.

--

--

Uditha Janadara

Undergraduate Software Engineer at Sri Lanka Institute of Information Technology