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.
Note: By using the script at the bottom of the <body> tag improves the display speed.
Note: console.log() use for debugging purposes and document.write() use for testing purposes.
Set of rules for any programming language, which shows how programs constructed. Here are the followings for JavaScript language.
Stay tuned! I will get it ready for you!
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:
function functionName(parameters) { // code to be executed }
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.
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);
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 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 };
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.
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.
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.
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
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.
So, A JavaScript object is a collection of unordered properties, and it can be changed, added, and deleted.
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
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"];
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.
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.
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:
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.
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
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.
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.
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:
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.
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
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
Result:
Prototype normally use for two reasons:
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”.
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.
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.
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.
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;
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:
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 exactly behave like let variables: the only difference is const cannot be reassigned.
Ex.
There was a tweet of Reginald Braithwaite about ES6 Conventions:
Operator is all about performing some operation on single or multiple operands and getting a result.
Operators and Operands:
Operand | Operator | Operand |
100 | + | 50 |
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 |
Let’s introduce a few more special operators in JS for various purposes:
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
It’s a conditional and special operator in JavaScript, which makes life easier!
Syntex: condition ? value if true : value if false
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:
undefined and null are equal in value but different in type.
Note:
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
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:
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.
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.
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:
Method:
Note:
JavaScript uses the + operator for both addition and concatenation.
Numbers are added. Strings are concatenated.
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.
A symbol represents its type:
Note:
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.
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, 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.
arguments vs parameters
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.
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;
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 |
Regular expressions can have options, which are written after the closing slash.
A number of common character groups have their own built-in shortcuts characters with a special meaning:
\d | finding a digit character |
\w | finding an alphanumeric character (a word with a number) |
\s | finding a whitespace character (space, tab, etc) |
\D | finding a character that is not a digit |
\W | finding a non-alphanumeric character |
\S | finding a non-whitespace character |
. | finding a character except for the newline |