If anyone who is interested to have a good career as a JavaScript Programmer, then he/she needs to be strong with the following concepts. If you have mastered the concepts mentioned in this blog, then you have the skill to build world class JavaScript web applications. I am hoping that after reading these concepts your doubts will be cleared and you will become better programmer.
- OOP in JavaScript
- Difference between == and ===
- Know what ‘this‘ is
- console.log Commands
- Difference between if…else and switch…case
- Working with Strings
- Working with Arrays
- Regular Expression in JavaScript
- new Operator
- Semi-colon is not optional
1. OOP in JavaScript
Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
Object
Any entity that has state and behavior is known as an object. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Objects, better known as Classes in most OOP programming languages and Functions in JavaScript. Building applications with objects allows us to adopt some valuable techniques, namely, Inheritance (objects can inherit features from other objects), Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ), and Encapsulation (each object is responsible for specific tasks).
There are only two concepts Inheritance and Encapsulation which can be applied to OOP in JavaScript, particularly because, in JavaScript, objects can encapsulate functionalities and inherit methods and properties from other objects.
Encapsulation
It refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application. This allows us to abstract or localize specific set of functionalities on objects.
Inheritance
It refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages or a Function in JavaScript).
Both of these concepts, encapsulation and inheritance, are important because they allow us to build applications with reusable code and abstracted functionalities.
An instance is an implementation of a Function. In simple terms, it is a “child” of a Function or object. For example:
// Tree is a constructor function because we will use new keyword to invoke it.
function Tree (typeOfTree) {} // mangoTree is an instance of Tree. var mangoTree = new Tree ("banana");
In the above example, mangoTree is an object that was created from the Tree constructor function. We say that the mangoTree object is an instance of the Tree object. Tree is both an object and a function, because functions are objects in JavaScript. mangoTree can have its own methods and properties and inherit methods and properties from the Tree object as well.
2. Difference between Equal Operators == and ===
== Double equals. It is also known as loose equality. It will not compare the type, however it will typecast values being compared within the statement.
=== Triple equals. It is also known as strict equality will compare the type, but will not typecast the values meaning they are compared as without being transformed. The triple equals is faster and the recommended approach for comparing all kinds of values. This means both types need to be the same for the condition to be true.
Example for == (Double Equals) or (Loose Equality)
If x=5 is then,
In the above example, if the value of x is within single quotes which is a string has returned the value true because it is not comparing the type whether it is string or number.
Using the double equals is not recommended as it will not give the desired output.
Example for === (Triple Equals) or (Strict Equality)
If x=5 is then,
For strict equality, false is being returned because we are comparing a number to a string. Obviously they are two different distinct types and as mentioned above types will be compared and will return false value if they are different.
3. Know what ‘this’ keyword is…
The this reference holds the value of an object and it is usually used inside a function or a method, although it can be used outside a function in the global scope. This is used inside a function (let’s say function A) and it contains the value of the object that invokes function A. We need this to access methods and properties of the object that invokes function A, especially since we don’t always know the name of the invoking object, and sometimes there is no name to use to refer to the invoking object. Indeed, this is really just a shortcut reference for the invoking object.
For Example:-
var person = { firstName: "Rahul", lastName: "Kavita", fullName: function () console.log(this.firstName + " " + this.lastName); //we could have also written this: console.log(person.firstName + " " + person.lastName); } }
If we use person.firstName and person.lastName, as in the above example, our code becomes ambiguous. Consider that there could be another global variable (that we might or might not be aware of) with the name “person.” Then, references to person.firstName could attempt to access the firstName property from the person global variable, and this could lead in difficulty to debug errors. So we use the “this” keyword for precision; this keyword not only refers to the object but it also contains the value of the object.
4. Console Commands
The most commonly use console commands are console.log and possibly console.error but there are actually a few other console commands as per msdn which we can use.
a. console.log()
It is used to test the script in the console and also it will display the error if there will be any. In the browser, press F12. Console log window will be opened. It is used for debugging.
var user = new Object(); user.first = "Ashok"; user.last = "Sharma"; console.log(user.first, user.last); // Output: // Ashok Sharma
The following substitution patterns are supported:
%s – string
%i – integer
%d – integer
%f – float
%o – object
%b – binary
%x – hexadecimal
%e – exponent
b. console.clear()
Clears messages from the console window, including script-error messages, and also clears script that appears in the console window. Does not clear script that you entered into the console input prompt.
c. console.info()
Sends message to the console window. The message is prefaced by an information symbol.
d. console.warn()
Sends message to the console window, prefaced by a warning symbol. Objects that are passed by using the command are converted to a string value.
5. Difference between if and else and switch case
As per MDN, Javascript supports two conditional statements if…else and switch case. A conditional statement is a set of instructions that executes depending upon the condition is true or false
If…else statement will have following forms
- if statement
- if ….else statement
- if ….elseif statemen t
if statement
Statements inside if will be executed if the expression is true. If the expression is false then no statements will be executed. We will be using comparison operators to evaluate the expression.
Syntax:
if (expression){ statements will be executed only if the expression is true }
Example:
<html> <body> <script type="text/javascript"> var age = prompt('Enter your age plz'); if( age >=18 ){ alert("Qualifies for driving"); } </script> </body> </html>
Result:
Enter your age plz: 25
Qualifies for driving.
If we enter age greater than 18 then it will execute the statement otherwise will come out.
if ….else statement
It is the next form of control statements which allows to execute statements depending upon the expression is true or false.
Syntax:
if (expression){ statements will be executed only if the expression is true } else { statements will be executed only if the expression is false }
Example:
<html> <body> <script type="text/javascript"> var age = prompt('Enter ur age plz'); if( age >=18 ){ alert("Qualifies for driving"); } else{ alert(“Doesn’t qualify for driving”); } </script> </body> </html>
Result:
If you enter 25 in your age prompt then:
Qualifies for driving
But in case of 15:
Doesn’t qualify for driving
If age is greater than or equal to 18 then it will execute the if statement otherwise will execute the else statement.
if ….else if statement
This is more advanced form of if..else that will execute statements on the basis of given conditions. It is useful in the case of multiple conditions. In this case only the first logical condition which is true will be executed.This can also be known as nested if statements.
Syntax:
if (expression1){ statements will be executed only if the expression2 is true } else if (expression2){ statements will be executed only if the expression2 is true } else if (expression3){ statements will be executed only if the expression3 is true } else { statements will be executed only if the expression is false }
Example:
<html> <body> <script type="text/javascript"> var book = prompt('Enter book name'); if( book = ‘Kiterunner’ ){ alert("It comes under fiction category"); } else if( book = ‘Wasted in Engineering’ ){ alert("It comes under non fiction category"); } else if( book = ‘A history of India’ ){ alert("It comes under history category"); } else{ alert(‘Unknown category’); } </script> </body> </html>
Result:
It will display the result on the basis of the choices given. If we will enter Kiterunner in the prompt box, then ‘It comes under fiction category’ will be the output. If we will enter any bookname which is not mentioned, example ‘Madhushala’, then result will be ‘unknown category’. For comparison use == (equal operator). For comparison don’t use =. ‘=’ is used for assigning values not for comparing them.
Switch case
The main objective of switch case is to execute different statements given on the basis of expression given. Each case statement will be checked against the expression given until a match is found. If nothing founds default statement will be executed. Break is very important after each statement. If we will not give it then every statement will be executed.
Syntax:
switch (expression) { case condition 1: statement(s) break; case condition 2: statement(s) break; case condition n: statement(s) break; default: statement(s) }
Example:
<!DOCTYPE html> <html> <head> <title>Switch Case</title> </head> <body> <script type="text/javascript"> var time = new Date(); var myday = time.getDay(); //alert(myday); switch(myday){ case 0: alert('it is sunday'); break; case 1: alert('it is monday') break; case 2: alert('it is tuesday') break; case 3: alert('it is wednesday') break; case 4: alert('it is thursday') break; case 5: alert('it is friday') break; case 6: alert('it is saturday') break; default:break; } </script> </body> </html>
In the above example, new Date() function will display the current date and date with time zone. The getDay() function returns the weekday as a number between 0 and 6. (Sunday=0, Monday=1, Tuesday=2, Wednesday =3, Thursday=4, Friday=5, Saturday=6). Result will be current day and it will execute the case depending upon on which day it has been executed. For example. If we are executing it today, i.e. 21st April 2016. It will find the match with Case 4 and execute it. Result will be “it is Thursday”.
6. Working with Strings
In Javascript even if you don’t really work with strings or know the basic methods for working with strings, then go through with the below given methods:-
a. indexOf()
The index of method will return the first occurrence of a particular text in a string.
Example:
var a = "My name is Arun. My father's name is Ashok"; alert(a.indexOf('name'));
In the above example name is appearing twice. But it will take the position of the first time “name” and will return 3 .
Result: 3
b. lastIndexOf()
The index of method will return the first occurrence of a particular text in a string.
Example:
var a = "My name is Arun. My father's name is Ashok"; alert(a.lastIndexOf('name'));
In the above example name is appearing twice. But it will take the position of the last position of “name” and will return 29 .
Result: 29
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
c. toUpperCase()
It will convert the string in uppercase.
Example:
var a = "Live life to the fullest";
alert(a.toUpperCase());
Result: LIVE LIFE TO THE FULLEST
d. toLowerCase()
It will convert the string in uppercase.
Example: var a = “Live life to the fullest”;
alert(a.toLowerCase());
Result: live life to the fullest
e. length
It will return length of the string.
Example:
var a = "Live life to the fullest"; alert(a.length);
It will count total letters in a string and blank spaces too and return total value of it.
Result: 24
f. charAt()
It will return character for the given position.
Example:
var a = "Live life to the fullest"; alert(a.charAt(2));
Result: v
For Invalid values:
Example:
var a = "Live life to the fullest"; alert( a.charAt(26) );
Result: Null
g. substr()
Syntax: substr(Begin Index, no. of values)
Begin index will take the position of the character in a string and will display values depending upon the index value and number of values given.
Example:
var a = "Live life to the fullest"; alert(a.substr(2,6));
Result: ve lif
For Invalid values:
Example:
var a = "Live life to the fullest"; alert( a.substr(27,6) );
Result: Nothing
h. substring()
Syntax: substr(Begin Index, End Index)
Begin index will take the position of the character in a string and will display values depending upon the index value and number given.
Example:
var a = "Live life to the fullest"; alert(a.substr(2,6));
Result: ve lif
For Invalid values:
Example:
var a = "Live life to the fullest"; alert(a.substr(27,6));
Result: Nothing
i. Match()
It will match the value given with the string and return it.
Example:
var a = "Live life to the fullest"; alert(a.match(‘l’));
Result: l
For Invalid values:
Example:
var a = "Live life to the fullest"; alert(a.match(‘z’));
Result: Null
j. Replace()
It will replace a specified value with the given value in the string.
Example:
var a = "Live life to the fullest"; alert(a.replace(‘l’ , ‘m’));
Result: Mive mife to the fummest
Example:
var a = "Live life to the fullest"; alert(a.replace(‘o’ , ‘z’));
Result: Live life to the fullest
It will return the string as it is.
k. Search()
This method will search the sting for the given value and returns the position of the value.
Example:
var a = "Live life to the fullest"; alert(a.search(‘l’));
Result: 5, not 0 because javascript is case sensitive. If we will search L, then it will
return 0. Also it will include blank spaces while counting the position.
For Invalid values:
Example:
var a = "Live life to the fullest"; alert(a.search(‘q’));
Result: -1
7. Working with Arrays
JavaScript arrays are used to store multiple values in a single variable. They serve as a great way to store data, to keep track of states and using them as maps generally.
Array Syntax
var array-name = [item1, item2, ...]; var colors = ["Red", "Green", "Black"];
Methods of Array
1. pop
The pop() method removes the last value of an array permanently will return the remaining values.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.pop()); alert(mdArr);
Result: 5 and 5,6,7,8,9
2. push
The push() method adds the new value in the array at the end and will return the new set of array values.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.push(6,8,9)); alert(mdArr);
Result: 9 and 5,6,7,8,9,5,6,8,9
3. shift
The shift() method is just like pop method. The only difference is it will remove the first value from an array permanently and return the remaining values.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.shift()); alert(mdArr);
Result: 5 and 6,7,8,9,5
4. unshift
The unshift() method is the opposite of shift() method. The only difference is it will add the new values at the beginning of an array and return the new set of array values.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.unshift(3,2,1)); alert(mdArr);
Result: 9 and 3,2,1,5,6,7,8,9,5
5. indexOf()
It will display the index of a given array element. If a number is appearing twice in an array, then it will return the index of first occurrence of a given number.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.indexOf(5));
Result: 0
For invalid value:
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.lastIndexOf(10));
Result: -1
6. lastIndexOf()
It will display the index of a given array element. If a number is appearing twice in an array, then it will return the index of last occurrence of a given number.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.lastIndexOf(5));
Result: 5
For invalid value:
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.lastIndexOf(10));
Result: -1
7. join()
It will join all array elements into a string specified by a separator.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.join(‘’));
Result: 56785
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.join(‘ ’));
Result: 5 6 7 8 5
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.join(‘*’));
Result: 5*6*7*8*5
8. slice()
Syntax: slice(Begin Index, End Index)
Begin index will take the position of a given array element and will display values depending upon the End Index value given. Last index value will not 6be included.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.slice(2, 4));
Result: 7,8
It will take values from 2nd index i.e. 7 and will return values till 3rd index. 4th index value will not be included.
9. splice()
Syntax: slice(Begin Index, No.of values)
Begin index will take the position of a given array element and will display
values depending upon the value given for No.of values given.
Example:
var mdArr = [5,6,7,8,9,5]; alert(mdArr.slice(2, 4));
Result: 7,8,9,5
It will take values from the 2nd index i.e. 7 and will return upto 4 values.
8. Regular Expression in JavaScript
Regular expression is used to perform all types of text searches/replace operations on the basis of given modifiers.
Syntax:
/pattern/modifiers;
Different Types of Modifiers:
- i : Using this modifier will do case sensitive matching
- g : It will do global match which means it will find all the matches in a string rather than stopping after first match.
- m : It will do multiline matching.
Example:
var str = 'admec multimedia institute'; alert(str.search(/MULTIMEDIA/i));
Result: 6, As we have used search method it will search for the given value and return the position of the given value. Also as we have used ‘i’ as the modifier it will do case sensitive matching.
Example:
var str = 'admec multimedia institute'; var patt = /A/gi; alert(str.replace(patt, 'z'));
Result: zdmec multimediz institute, As we have used replace method and ‘g’ and ‘I’ modifier it will do case sensitive matching and replace all A with z.
Test() Method
It will search a string for a pattern and will return true or false value depending upon the search.
Example:
var str = 'admec multimedia institute3'; var patt = /[0-9]/gi; if(patt.test(str) == false) alert('valid name given'); else{ alert('invalid name given'); }
Result: Invalid name given, it will search for values between[0-9]. If it’s there in the string it will execute the else statement and will print ‘invalid name given’.
Know More : How to Use Regular Expression in JavaScript
9. New Operator in JavaScript
The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
Syntax
new constructor[([arguments])]
constructor– A function that specifies the type of the object instance.
arguments– A list of values that the constructor will be called with.
Creating a user-defined object requires two steps:
- Define the object type by writing a function.
- Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its name and properties. An object can have a property that is itself another object.
For example:
When the code new Foo(…) is executed, the following things happen:
- A new object is created, inheriting from Foo.prototype.
- The constructor function Foo is called with the specified arguments, and with this bound to the newly created object. new Foo is equivalent to new Foo(), i.e. if no argument list is specified, Foo is called without arguments.
- The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn’t explicitly return an object, the object created in step 1 is used instead. (Normally constructors don’t return a value, but they can choose to do so if they want to override the normal object creation process.)
You can always add a property to a previously defined object. For example, the statement car1.color = “black” adds a property color to car1, and assigns it a value of “black”. However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the definition of the Car object type.
You can add a shared property to a previously defined object type by using the Function.prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value null to all objects of type car, and then overwrites that value with the string “black” only in the instance object car1.
function Car() {} car1 = new Car(); console.log(car1.color); // undefined Car.prototype.color = null; console.log(car1.color); // null car1.color = "black"; console.log(car1.color); // black
10. Semi-Colon is not optional
Semi colons in javascript are mandatory. If they are not used then it will throw an error. Let’s have a look at the following example:-
function avg(c, d) { return (c + d) / 2 } console.log(avg(2, 3))
What will be printed on the console? It will be undefined!
In the above example Javascript will treat the above code as
function avg(c, d) { return; (c + d) / 2; } console.log(avg(2, 3));
So in order to run the code successfully it is required the right usage of semicolons are required. For example the above written can be written as :-
function avg(c, d) { return(c + d) / 2; } console.log(avg(2, 3));
The result in console would be 2.5.
There are plenty more things I could go on about. This post is covering the important things from my perspective. Please do not take this blog as the only 10 best features which every Javascript developers should know.
Javascript is a powerful scripting language required for building any kind of rich user experience on the web. The more you practice JavaScript, the more you will realize that how little you actually know about it. But having additional knowledge will help in avoiding mistakes that are common for beginner level developers and sometimes for advance level developers as well.
This is why it is always rightly said “Knowledge is a treasure but practice is the key to it”.
View Full Presentation on slideshare:
Form Validation in JavaScript
Form Validation in JavaScript from ADMEC Multimedia Institute