JavaScript

JavaScript is a programming language. For your information, please note, it’s not a frontend or backend language. It’s just a programming language like others. It has frameworks for frontend and backend both. Here are the most popular frontend frameworks are VueJS, ReactJS, and AngularJS, while NodeJS and ExpressJS are the most popular backend frameworks.

However, javaScript, it’s the most dynamic and useful language ever. Though the language is so broader and complex, all lessons are organized here in a more specific way. So the motive is that you can go through quickly and get a quick overview of what is needed.

Enough introduction, let’s get started! Oh, by the way, let’s introduce with Brendan Eich, the inventor of this magical JavaScript invents in 1995.

 

JS Using:

  • Internal: You can use it in <body> or in <head> tag or in both of an HTML page. 
  • External: You can use it via an external script file through the src attribute, it’s cannot contain <script> tag.

Note: By using the script at the bottom of the <body> tag improves the display speed.

 

Output Options:

  • innerHTML: writing into an HTML element
  • document.write(): writing into an HTML output
  • window.alert(): Writing into an alert box
  • console.log(): Writing into the browser console

Note: console.log() use for debugging purposes and document.write() use for testing purposes.

 

Syntax:

Set of rules for any programming language, which shows how programs constructed. Here are the followings for JavaScript language.

  • Values: Fixed, variables 
  • Identifiers: Identifiers are names, it can start with a letter,  dollar $ or by an underscore _
  • Operators: Arithmetic, Comparison, Bitwise, Logical, Assignment, and a few special operators.
  • Data Types: Primitive (string, number, boolean, undefined, null), Reference or Non-Primitive (Array, Object, Function) 
  • Comments: Line comments, Block comments.
  • Keywords: Thay are tokens that have special meaning in JavaScript.

 

Stay tuned! I will get it ready for you!


RD Circles_Coming Soon

Function:

In general, a function is a block of statements that performs a specific task. Similarly, a JavaScript function is a block of code, designed for a particular task.

Different ways to write a function:

There are five different ways (Normal function, Anonymous, Function() Contractor, Self-Invoking Functions, Arrow Functions) to write a function, thous are given below:

 

Normal Function:

function functionName(parameters) { // code to be executed }

 

Anonymous Function:

Function without a name

var x = function (a, b) {return a * b}

Note: Functions stored in variables do not need function names. They are always invoked by the variable name.

 

Function() Contractor:

It’s a built-in JavaScript function constructor.

var myFunction = new Function("a", "b", "return a * b") 

Note: Most of the time, you should avoid using the new keyword in JavaScript. You can write it in this way:

var myFunction = function (a, b) {return a * b}; var x = myFunction(4, 3);

 

Self-Invoking Functions:

A self-invoking expression is invoked (started) automatically, without being called.

(function () { var x = "Hello!!"; // I will invoke myself })();

Note: it’s an anonymous self-invoking function

 

Arrow Functions:

Arrow functions allow a short syntax for writing function expressions.

const a = (a, b) => a * b; 

Note:
Arrow functions do not have their own this. They are not well suited for defining object methods.
Using const is safer than using var, because a function expression is always constant value.
You can only omit the return keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
const a = (a, b) => { return a * b };


Object:

The most important, when I say the most important there is a meaning behind this, It is the big fish, it is the king, and it is almost everything in JavaScript.

Objects in JavaScript are extremely versatile. So we can do almost anything we want, like, we can pass a function as a parameter into another function.

An object, in object-oriented programming (OOP), is an abstract data type created by a developer. It can include multiple properties and methods and may even contain other objects.

In programming culture, we have a thing called object-oriented programming, a set of techniques that use objects (and related concepts) as the central principle of program organization. It means object-oriented programming has shaped the design of many programming languages, including JavaScript.

 

Now let see: why is it so important?

Dates, Maths, Regular expressions, Arrays, Functions these all are the object in JavaScript. Objects itself is an object!
Booleans, Numbers, and Strings can be an Object too by using the new keyword.
Even all kinds of values are objects except primitives (Booleans, Numbers, Strings)

What else: yes, the variables:
Variables are objects too, but the difference is objects can contain many values.

 

Objects have members called: properties and methods.
Rdcircles object member e1587320897181

Creating Object:

By Using the JavaScript Keyword new
In ECMAScript 5, an object can also be created with the function, I mean an object constructor Object.create().

var person = new Object();
person.firstName = "Rajon";
person.lastName = "Dey";
person.age = 25;
person.eyeColor = "Black";

Note: Both are doing the same! So, always try to avoid the new keyword for the sake of simplicity, readability, and execution speed.

 

Now, How do you display JavaScript Object?

There are a few ways for this, you can display it by name, by a loop, using Object.values(), and using JSON.stringify()

var person = {name:"Rajon", age:25, city:"Bangladesh"};

By name: person.name 
By Loop: var x, val = “ ”; for (x in person){ val += person[x] + “ ”; }
By Object.values(): Object.values(person); Note: Output will show as an array
By JSON.stringify(): JSON.stringify(person; Note: Output will show as an string

Object Properties

The fundamental part of a JavaScript Object is its Properties.

JavaScript objects are containers for named values called properties or methods. In other words, name:values pairs in JavaScript objects are called properties.

Object Properties Image

So, A JavaScript object is a collection of unordered properties, and it can be changed, added, and deleted.

 

Property accessors:

There are mainly two ways to access:
Dot notation: Object.property
Bracket notation: Object[‘property’]

One more way is via expression: Object[expression]
Note: Here expression as a property name

 

Adding and Deleting Properties:

By simply using dot syntax we can add a new property:

Object.propertyName = "propertyValue";

For deleting, there is a delete keyword used on Object property:

delete Object.propertyName; or delete Object["propertyName"];

Object Methods

A method is a function: stored as property because it performed an action.

Object properties can be both primitive values, other objects, and functions: so an object method is an object property that contains a function definition. In other words, Methods are nothing more than properties that hold function values.

Once you have created objects, you want them to be able to do something. This is where methods come in.

Object Method Image

A method, in object-oriented programming (OOP), is a procedure associated with a message (invoking) and an object.

A method, in class-based programming, methods are defined in a class, and objects are instances of a given class.

 

Built-in Methods:

A built-in Method means a built-in function that is built into an application and can be accessed by end-users. However, there are many objects which contain their default built-in methods for different actions, for example, toUpperCase() method, which is a default built-in method of string objects: the action of this method is to convert a text to uppercase.

Notes:

  • A method defines the behavior of the objects that are created from the class.
  • The association between method and class is called binding.
  • Methods are sometimes confused with functions, but they are distinct, so be aware of this.

Getters and Setters

These are the Accessors in the JavaScript Object. Now, what is the accessor?

We can access Object’s Properties by using the dot notation or the bracket notation. These are called accessor properties.

Getters and Setters, basically function, these are responsible for getting and setting a value.

 

Getter Ex:

var person = {
  name: "Rajon",
  get nam() {
    return this.name;
  } 
};
console.log( person.nam; );    // Rajon

 

Setter Ex:

var person = {
  name: "",
  set nam(nam) {
    return this.name = nam;
  }
};
person.nam = “Rajon”
console.log( person.name; );    // Rajon 

 

Getter: The get syntax binds an object property to a function that will be called when that property is looked up.
Setter: The set syntax binds an object property to a function to be called when there is an attempt to set that property.

 

Function VS Accessor

Nothing major accessor provides simpler syntax.

var person = {
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
}; person.fullName(); // Rajon Dey
var person = {
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
}; person.fullName; // Rajon Dey

Object Constructors?

Constructors, it constructs the value of data members of the class, that is why it is called Constructor. Constructors are like regular functions, but we use them with the keyword new.

 

Two types of constructors:

  • Built-in constructors.
  • Custom constructors.

In JS, there are nine built-in constructors are available, these are: Object(), Array(), String(), Number(), Boolean(), Date(), Function(), Error() and RegExp()

Whereas, custom constructors, which define properties and methods for its object.

However, a constructor is useful when you want to create multiple similar objects with the same properties and methods.

Example:

function Person(name, age) {
  this.name = name;
  this.age = '(' + age + ')';
}
var firstPerson = new Person("Smith", 20);
var secondPerson = new Person("Megh", 28);

See, we used the Person constructor with the new keyword, so it assigns the received parameters(values) to the name and age property of the current instance.

 

Instance:

Now, what does it instance mean by this instance, by meaning it is an example of a particular action and situation. Here, an “instance” is just a regular object. It’s actually nothing but called properties of the object. By this, you have a copy of that property’s value for each instance of the class.

Note:

  • It’s important to remember to use the new keyword before all constructors. If you accidentally forget new, you will be modifying the global object instead of the newly created object.
  • Constructor functions first letter with an upper-case, it’s not mandatory, it’s good practice. Even its distinguished constructor from regular functions.

Prototypes

By meaning, a prototype means the sample, model, or release of a product built to test a concept or process. 

Prototypes are the mechanism by which JavaScript objects get inherit features from one another. To provide inheritance: an object has its won prototype object, which acts as a template object.

Function prototype vs Object prototype:

A prototype is an object that is associated with every function and objects by default in JavaScript, where the function’s prototype property is accessible, modifiable, and the object’s prototype property (aka attribute) is not visible.

 

Prototype object

The prototype object is a special type of enumerable object(using iterating over properties)That means additional properties can be attached to it, which will be shared across all the instances of its constructor function. So, the prototype property is a particular type of enumerable object which cannot be iterate using for..in or foreach loop.

Example:

function Person() {
    this.name = 'Rajon';
    this.gender = 'M';
}
Person.prototype.age = 25;
var perObj1 = new Person();
alert(perObj1.age); // 25

 

Prototype Properties:

There are two properties for the prototype:

Constructor: Which is a function that is created object instance

__proto__: One invisible property.

Note: An object (instance) does not expose prototype property, instead you can access it using __proto__.

Example:

function Person() {
    this.name = 'Rajon';
    this.gender = 'M';
}

var firstObj = new Person();

console.log(typeof Person.prototype); // object
console.log(typeof firstObj.__proto__); // object

RDLearning Object prototypes1

Result:

RDLearning Object prototypes2 e1587572721625

RDLearning Object prototypes3

Prototype normally use for two reasons:

  1. To find properties and methods of an object
  2. To implement inheritance in JavaScript

Lastly, there are few methods also for prototype, we will check in the next chapters.

 

Note:

Everything in JavaScript can be extended using the base object as a prototype. One important note that prototypal inheritance makes JavaScript naturally forgiving and easily extendable. It’s basically possible for any developer to build on top of the core JavaScript library in their own code.

All JavaScript objects inherit properties and methods from a prototype.

Whenever a new function is created in javascript, Javascript engine by default adds a prototype property to it, this property is an object and we call it “prototype object”.


Class

In brief, what is class: Classes are very useful in programming. A class is a blueprint or template of an object, whereas an object is an instance of a class. You need to have a class before you can create an object. However, class is normally defined by class keyword.

JS Class

Javascript classes are nothing but just a new way of writing the constructor functions by utilizing the power of the prototype.

Example:

class Person{
   constructor(name, age, gender) {
       this.name = name;
       this.age = age;
       this.gender = gender;
   }

   getName() {
       return this.name;
   }
}
let car = new Person("Rajon", "25", "M");

Note: Constructor is a special function in the class declaration, which defines a function, that represents the class itself. When you new up a class instance, the constructor is automatically called.

 

Important facts regarding class:

If you don’t add a constructor to a class, a default empty constructor will be added automatically.
Code inside a class is always in strict mode, this helps to write error-free code.
Class declarations are not hoisted, so you can’t use a class before it is declared.
A class can not have more than 1 constructor function.


Variable

It’s something like a Container or a Box for storing data values. Here these are the keywords: var, let, and const, which create this container by leveling a name on it.
Ex. var r = 2;

 

Scope

For variables, you should know about the scope, which refers to the visibility of variables. In other words, it is the region of a computer program where the binding is valid. There are three kinds of scope available in JS:

  • Global Scope: Declaring outside of any function has Global Scope.
  • Function Scope: Declaring inside a function has Function Scope.
  • Block Scope: variables declared inside a block.

There where only two scopes, before ES2015, in JavaScript: Global Scope and Function Scope. So, it was an issue with the var keyword that it can not have Block Scope. That means variables declared inside a block {} can be accessed from outside the block.

Ex.

{
  var r = 2;
}// r can be used here 

 

To solve this problem, ES2015 introduced two new keywords: let and const in JavaScript. By these, now we can deal with Block Scope and constants variables in JavaScript.

Variables declared with the let keyword have Block Scope. That means variables declared inside a block {} can not be accessed from outside the block.

Ex.

{
  var r = 2;
}// r can not be used here 

 

const vs let

const exactly behave like let variables: the only difference is const cannot be reassigned.

Ex.

  • const PI = 3.141592653589793;
  • PI = 3.14 // This will give an error

 

ES6 Conventions:

There was a tweet of Reginald Braithwaite about ES6 Conventions:

  • Use const by default
  • Use let if you have to rebind a variable
  • Use var to signal untouched legacy code

 


Operator

Operator is all about performing some operation on single or multiple operands and getting a result.

Operators and Operands:

Operand 

Operator 

Operand 

100+

50

JS Operator by RD Circles

 

Bitwise operator:

Bitwise operators are used to changing individual bits in an operand. It works on 32 bits numbers. 

AND
OR
~NOT
^XOR
<<Zero fill left shift
>>Signed right shift

 

JS Special operators

Let’s introduce a few more special operators in JS for various purposes:

JS Special operators by RD Circles

 

Exponentiation: **

Exponentiation, introduced in ES2016, it raises the first operand to the power of the second operand, it works as same as Math.pow(). Such as a ** b produces the same result as Math.pow(a,b)

Ex. 

5**2;  // result 25 

Math.pow(5,2)  // result 25

 

Ternary operator: ( : ? )

It’s a conditional and special operator in JavaScript, which makes life easier!

Syntex: condition ? value if true : value if false


Data Type

In computer science, computer programming, a data type is an attribute of data that tells the compiler or interpreter that how the programmer intends to use the data. So, for operating variables, it is important to know something about the type.

However, there are two types of data divided into two groups:

JS Data Type by RD Circles.png

 

undefined vs null:

undefined and null are equal in value but different in type.

  • null === undefined     // false
  • null == undefined      // true
  • typeof undefined       // undefined
  • typeof null            // object

Note:

  • undefined: var person;    // Value is undefined, type is undefined
  • empty: var person = “”;    // Value is “”, the typeof is “string” 
  • null: var person = null;    // Value is null, but the type is an object

 

Boolean

Boolean use for all JavaScript comparisons and conditions value. It represents one out of two values: either true or false.

Boolean have only 2 methods and 2 properties available in JS

  • Property: constructor, prototype 
  • Method: toString(), valueOf()

String

JavaScript strings are used for storing and manipulating text. Within quotes, it can contain zero or more characters.

Escape sequences

An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly. Here are the following characters reserved in JavaScript:

JS Escape Sequences by RD Circles

String Methods and Properties:

Strings, take for example, “Rajon Dey” cannot have properties or methods, as it’s not an object. But in JavaScript, we still have methods and properties for our primitive values, because we know all primitive values treated as an object in JS when executing methods and properties.

There are a lot of builtin string methods, and 3 properties available in JS, you should play with all of them for your practical programming experience!

Ex. 

  • method: string.search()
  • properties: constructor, length, prototype

Number

JavaScript number is used to work with numerical values. In general, it displays numbers as base 10 decimals. However, you can use the toString() method to output numbers from base 2 to base 36.

  • Hexadecimal is base 16 
  • Decimal is base 10
  • Octal is base 8
  • Binary is base 2

 

Number Methods and Properties:

There are almost 10 methods, and 7 properties available in JS. You should play with all of them for your practical programming experience!

Ex.

Property:

  • constructor
  • MAX_VALUE
  • MIN_VALUE
  • NEGATIVE_INFINITY
  • NaN
  • POSITIVE_INFINITY
  • prototype

 

Method:

  • isFinite()
  • isInteger()
  • isNaN()
  • isSafeInteger()
  • toExponential(x)
  • toFixed(x)
  • toLocaleString()
  • toPrecision(x)
  • toString()
  • valueOf()

 

Note:

JavaScript uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.


Non-primitive Data

These data types, actually created by the programmer, not defined by the programming language. Because there have primitive values, so rest of them are non-primitive somewhat like this. However, this type has other names also: “reference variables” or “object references” as this reference the object data.

In JavaScript, directly or indirectly, all kinds of data types are the object. All primitives also can be an object. That is why the object is the most fundamental subject in JavaScript. However, array, function, and the object itself are the non-primitive data.

JavaScript Object by RD Circles

A symbol represents its type:

  • In JavaScript, arrays are written with square brackets [ ]
  • In JavaScript, objects are written with curly braces { }
  • In JavaScript, functions are written with parentheses ( )

Note:

  • In JavaScript, arrays use numbered indexes.
  • In JavaScript, objects use named indexes.

Array

An array is a data structure that contains a group of elements. Thus JavaScript arrays are used to store multiple values in a single variable. More specifically, Arrays are a special kind of objects, with numbered indexes.

JavaScript Array by RD Circles.png

Note: Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on.

There are lots of built-in array methods, and 3 properties available in JS, you should play with them for the practical programming experience!

Ex. 

Method: array.find()

Properties: constructor, length, prototype


Function

Function, it just relates an input to an output, which means it performs any specific task for the output. Similarly, a JavaScript function is a block of code, designed for a particular task. Moreover, it helps you to use the same code many times with different arguments, to produce different results.

JavaScript Function by RD Circles

arguments vs parameters

  • Parameter is variable
  • Argument is the actual value

Function return

When JavaScript gets a return statement, the function will stop executing. It often computes a return value, and this return value is “returned” back to the “caller”: so it works like this: stops executing, compute, and return.


Regular Expression

A regular expression, also called rational expression, is a sequence of characters that creates a search pattern. That is why It’s a potent tool for inspecting and processing strings. However, Regular expression is something that is terribly awkward, where the syntax is cryptic, and even JavaScript presents for them is clumsy, besides all these, it’s extremely useful in JavaScript!

While searching for any particular data in a text, we can use this search pattern to describe what exactly we are searching for. So usually, we can use this regular expression for text search and text replace operations.

Syntax: /pattern/modifiers;

Ex.: /RDCircles/i;

 

Pattern

Regular expressions have their own language to express these patterns, here are the most important Regular expression pattern given below:

/abc/finding a sequence of characters
/[abc]/finding a character from a set of characters
/[^abc]/finding a character which not in a set of characters
/[0-9]/finding a digit in a range of digits 
/x+/One or more occurrences of the pattern x
/x*/Zero or more occurrences
/x?/Zero or one occurrence
/x{2,4}/Two to four occurrences
/(abc)/finding a group
/a|b|c/finding any one of several patterns
/\d/finding a digit character
/\w/finding a alphanumeric character (“word character”)
/\s/finding a whitespace character
/./finding a character except newlines
/\b/A word boundary
/^/Start of input
/$/End of input

 

Modifiers or Option

Regular expressions can have options, which are written after the closing slash. 

JS Regular Expression-Modifier by RD Circles

 

Metacharacters

A number of common character groups have their own built-in shortcuts characters with a special meaning:

\d    finding a digit character
\wfinding an alphanumeric character (a word with a number)
\sfinding a whitespace character (space, tab, etc)
\Dfinding a character that is not a digit
\Wfinding a non-alphanumeric character
\Sfinding a non-whitespace character
.finding a character except for the newline