Home » javascript

Category Archives: javascript

This Keyword in JavaScript

This keyword refers to an object, that object which is executing the current bit of JavaScript code.

JavaScript function while executing has a reference to its current execution any function, called this.

JavaScript function while executing has a reference to its current execution any function, called this.

with this keyword,It does not matter how and where function is declared or defined.

Example

function’s this keyword behaves differently in JavaScript compared to other language.

In most of cases, this is determined that by how avalue of function is called.

It cannot be set by assignment on time execution, and it will be different each time the function is called.

ES5 have the bind() method to set the value of a function’s this regardless of how it’s called, and ES2015 introduced arrow functions which don’t provide their own this binding.

Example

This keyword has some different values depending on its usage:

  • Within a method, this keyword refers to the owner object.
  • As Single, this keyword refers to the global object.
  • this keyword within a function refers to the global object.
  • Within a function, within strict mode, this keyword is undefined.
  • Creating an event, this keyword refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

In an object method, this refers to the “owner” of the method.

In the example on the top of this page, this refers to the person object.

The person object is the owner of the fullName method.

Example

OUTPUT

This in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

This in a Function (Default)

The owner of the function is the default binding for this.

Within function, this keyword refers to the Global object.

OUTPUT

Global Scope

If a function uses ‘this’ keyword, is called from the global scope then this will point to the window object

OUTPUT

Example: this keyword inside inner function

OUTPUT

Strict Mode in JavaScript

JAVACRIPT’s strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JAVACRIPT.

Strict mode is not just a subset: it intentionally has different semantics from all other normal code.

Some browsers does not support strict mode.

To run strict mode code with different behavior from browsers need to test for support for the relevant aspects of strict mode.

Strict mode code and non-strict mode code can be co existing, so scripts can opt into strict mode incrementally

Strict mode makes many changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.

The “use strict”; Syntax

For declaring strict mode the syntax was designed to be compatible with of JS.

Compiling a numeric literal (10 + 15;) or a string literal (“Ram Das”;) in a JS program has no side effects.

It will simply compiles to a non existing variable and it will dies.

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode

These are:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

Simplifying variable uses

Strict mode simplifies how variable names map to particular variable definitions in code.

This is critical to fully optimizing JS code.

JS makes this basic mapping of name to variable definition in the code impossible to perform until runtime.

Strict mode will removes most cases where it will happens, so the compiler can better optimize strict mode code.

First, strict mode prohibits with.

The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at run time, Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at run time.

Example

JavaScript allows strictness of code using “use strict”. Write “use strict” at the top of JavaScript code or in a function to run strict mode.

Example

Output

Defines that JavaScript code should be executed in “strict mode”.

“use strict” is to indicate, the code should be executed within “strict mode”.

Declaring Strict Mode

Strict mode is declared by adding “use strict”; to the beginning of a script or a function.

Example

Declared inside a function

Math Object in JavaScript

The JavaScript Math object used to perform mathematical tasks with numbers.Math is an object that has properties and methods.

Math has no constructor. All Math’s properties and methods are static.

To refer methods and properties use Math.propertName  and functions as Math.funcationName().

For example to access the constant pi use Math.PI

To call the sine function use Math.sin(valuex), where valuex is a argument. Constants are defined with the full precision of real numbers.

The math object provide properties and methods of constants and functions for mathematical.

Math’s properties and methods can be called by using Math as an object without creating it.

Syntax

Example

Math Properties (Constants)

Property Description
E It will return Euler’s number (approx. 2.718).
LN2 It will return tde natural logaritdm of 2 (approx. 0.693)
LN10 It will return tde natural logaritdm of 10 (approx. 2.302)
LOG2E It will return tde base-2 logaritdm of E (approx. 1.442)
LOG10E It will return tde base 10 logaritdm of E (approx. 0.434)
PI It will return constant value of PI (approx. 3.14)
SQRT1_2 It will return tde square root of 1/2 (approx. 0.707)
SQRT2 It will returnstde square root of 2 (approx. 1.414)

Math Object Methods

Mathod Description
abs(valuex) It will return the absolute value of valuex
acos(valuex) It will return the arccosine of valuex, in radians
asin(valuex) It will return the arcsine of valuex, in radians
atan(valuex) It will return the arctangent of valuex as a numeric value between -PI/2 and PI/2 radians
atan2(valuey, valuex) It will return the arctangent of the quotient of its arguments
ceil(valuex) It will return the value of valuex rounded up to its nearest integer
cos(valuex) It will return the cosine of valuex (valuex is in radians)
exp(valuex) It will return the value of Ex
floor(valuex) It will return the value of valuex rounded down to its nearest integer
log(valuex) It will return the natural logarithm (base E) of valuex
max(valuex,value y, valuez, …, valuen) It will return the number with the highest value
min(valuex,valuey, valuez, …, valuen) It will return the number with the lowest value
pow(valuex, valuey) It will return the value of valuex to the power of valuey
random() It will return a random number between 0 and 1
round(valuex) It will return the value of valuex rounded to its nearest integer
sin(valuex) It will return the sine of valuex (valuex is in radians)
sqrt(valuex) It will return the square root of valuex
tan(valuex) It will return the tangent of an angle

Global in JavaScript

Global scope is a Js function Scope.Scope determines the accessibility (visibility) of variables.Variables defined inside a function are not accessible (visible) from outside the function.A global variable is declared outside the function or declared with an object. It can be accessed from any function.

Declaring global variable within function

To declare global variables within a function, we need to use window object. For example:

Now this value can declared with in any function and can be access and used from any function.

For example:

EXAMPLE

OUTPUT

Internals of global variable

On outside a function,when a variable declare, that will add in window object. So it can be access through window object.

For example:

Global JavaScript Variables

If any variable declared outside a function, so that will becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it. 

OUTPUT

Automatically Global

If a value assign to a variable that has not been declared, it will automatically turn on GLOBAL variable.

This example will declare a global variable myName, the value is assigned inside a function.

OUTPUT

Global Variables in HTML

With JavaScript, the global scope is the complete
JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.

OUTPUT

Global Properties

Property Description
Infinity A numeric value that represents positive/negative infinity
NaN “Not-a-Number” value, It means there is nothing like value.
undefined This property indicates that a variable will not assigned a value.

Global Functions

Function Description
decodeURI() It will decodes a URI
decodeURIComponent() It will decodes a URI component
encodeURI() It will encode a URI
encodeURIComponent() It will encode a URI component
escape() It will use encodeURI() or encodeURIComponent() instead
eval() It willevaluates a string and executes it as if it was script code.
isFinite() It will determine whether a value is a finite, normal number
Number() It will convert an object’s value to a number
parseFloat() It will parse a string and returns a floating point number
parseInt() It will parse a string and returns an integer
String() It will convert an object’s value to a string
unescape() It will use decodeURI() or decodeURIComponent() instead

Try Catch and Finally in JavaScript

The try statement tests a block of code for errors.The catch statement handles the error.

The throw statement throws or creates custom errors.With finally statement the code will be executed, after try and catch, function will return a result.

Errors will happen, when executing a code, different errors can occur.

Error handling try and catch

In many time our scripts have errors. They are occurring because of programmer mistakes, an unexpected user input, or something else.

Normally, a script immediately stops in case of an error, printing it as an error massage.

But there is a syntax construct try, catch that allows to catching errors and, instead of stop the program, do something with programmer custom massage.

The try statement consists of a try block, which contains one or more statements. {} always be used in try block.

One catch clause, or a finally clause, must be after try block to handle the error.

This gives three blocks for the try statement:

try, catch

try, finally

try, catch, finally

try and catch

The try statement allows creating a block of code for errors while it is being executed.

The catch statement allows creating a block of code to be executed, if there is any error occurs in the try block.

Syntax

OUTPUT

OUTPUT

The try, catch, finally Statement

Try catch finally are so called exception handling statements.

An exception is an error that occurs at run time due to an error operation during execution.

Examples of exceptions include trying to reference an undefined variable, or calling a nonexistent method.

Examples of syntax errors of exceptions:

•        alert(“I am missing a closing part //syntax error

•        alert(xy) //exception occur “xy” isn’t defined yet

•        undefined function() //exception

Normally whenever runs an exception somewhere in code, it displays an error message to the user while aborting the execution of the remaining code.

At its simplest to use try/catch to try and run some code, and in the event of any exceptions,

User can catch programmer-generated and runtime exceptions, but cannot catch Js syntax errors.

The try block followed by exactly one catch block or one finally.

When an exception occurs in the statement written inside try block, the control transferred to catch block.

In catch block exception in caught in object declared in catch “err” and the catch block is executed.

The optional finally block executes after try/catch

If exception is thrown from try block then only catch block is executed.

Nested try/catch/finally statements

Try should never be defined just by itself, but always followed by catch or finally.

Within each clause, you can define additional try/catch/finally statements following the same rule.

Caught the exception in the inner try-block by adding a catch block

Example

OUTPUT

Re-throw the error

The throw Statement

throw statement to raise your built-in exceptions or customized exceptions. These exceptions can be captured and you can take an action.

The throw statement allows to create a custom error.

The exception can be a JS String, a Number, a Boolean or an Object:

throw “Too big”;    // throw a text

throw 500;          // throw a number

If programmer use throws together with try and catch, you can control program flow and generate custom error messages.

The finally Statement

The finally statement lets you execute code, after try and catch.

Functions in JavaScript

What is a Function?

  • A function is a block of code or a subprogram designed to perform a particular task.
  • Function is executed only when it is called. This is called invoking/calling a function. Thus it eliminates writing the same code again and again.
  • Values can be passed into functions and used within the function body.

Function always returns a value, if no return type is specified, the function will return undefined .

JavaScript Function Syntax

JavaScript supports 4 types of function invoking:

  1. Function having no arguments and no return value
  2. Function having arguments and no return value
  3. Function having return value and argument(s)
  4. Function having return value but no arguments

Function having no arguments and no return value

In JavaScript, if there’s no specified return type, the function will return undefined. Consider the following example:

R

Result

Function having arguments and no return value

Consider the following example:

Result

Here the ‘return’ statement is missing. But arguments are passed to the function and used in the block of code.

Function having return value and arguments

Result

Function having return value but no arguments

Result

Popup Box in JavaScript

JavaScript supports three types of dialog boxes:

  • Alert box
  • Confirmation box
  • Pop up box

Alert Box

An alert dialog box is mostly used to give a warning message to the users especially for validation purposes when a use inputs some wrong data, we can use an alert box to display a warning message.

The drawback of Alert box is only one button “OK” is available to select and proceed.

Syntax

The window.alert() method can be written without the window prefix.

Example

Confirmation Box

A confirmation box is used to take user’s consent on any particular situation.

It displays two buttons: OK and Cancel. It can be called as the improvised version of an alert box.

When the user clicks on OK, the window method confirm() returns true. When user clicks on the Cancel button, confirm() returns false. 

Syntax

The window.confirm() method can also be written without the ‘window’ prefix.

Example

Prompt Box

The prompt box is useful when we want to pop-up a text box for getting user input.

Thus, it gives you provision to interact with user. The user needs to fill the field and click OK.

This dialog box is displayed using a method called prompt() which takes two parameters:

  • A label that you want to display in the text box
  • A default string needs to be displayed in the text box

Prompt box has two buttons: OK and Cancel.

If the user clicks the OK button, the window method prompt() will return the entered value from the text box.

If the user clicks the Cancel button, the window method returns null.

Syntax

The window.prompt() method can also be written without the ‘window’ prefix.

Example

Classes and Objects in JavaScript

A class is a set or category of things having some property or attribute in common i.e., car is a class having similar properties such as color, engine, gear, model number etc.

The “class” construct allows us to define prototype-based classes.

Syntax for declaring a class:

Objects

Objects are the instance of classes i.e., Car is a class and Jaguar is an object of the Car class

Let’s consider a variable named person:

var person = “Sherlock Holms”;

Objects are also like variables but they can contain many values; like

this code assigns many values (Sherlock, Holms, male) to a variable named person:

var person = {name:”Sherlock”, title:”Holms”, gender:”male”};

The values are written as name:value pairs.

Object Definition

var person = {FirstName:”Sherlock”, lastName:”Holms”, age:50};

Spaces and line breaks are not important. An object definition can span multiple lines:

Object Properties

The name:values pairs in JavaScript objects are called properties:

Property Value
firstName John
lastName Doe
age 30

Accessing Object Properties

Object properties can be accessed in 2 ways:

  1. objectName.propertyName

or

2. objectName[“propertyName”]

Access Method 1

Output

Access Method 2

Regular Expression in JavaScript

What is a Regular Expression(RegEx)?

Regular expressions/sequence of characters are patterns used to match character combinations in strings.

A regEx can be a single character or a complicated pattern. Regular expressions can be used to perform text search and validation operations.

Special characters in regular expressions

Character Meaning
^ It Matches the beginning of an input e.g., /^A/ does not match the ‘A’ in “an A”, but matches the ‘A’ in “An E”
$ Matches the end of an input. If the multi line flag is set to true, it also matches immediately before a line break character e.g., /t$/ does not match the ‘t’ in “eater”, but matches it in “eat”
* Matches the preceding expression 0 or more times. Equivalent to {0,} e.g., /bo*/ matches ‘boooo’ in “A ghost booed” and ‘b’ in “A bird” but nothing in “A goat”
+ Matches the preceding expression 1 or more times. Equivalent to {1,} e.g., /a+/ matches the ‘a’ in “candy” and all the a’s in “caaaandy”, but nothing in “cndy”
? Matches the preceding expression 0 or 1 time e,g., /e?le?/ matches the ‘er’ in “anger”, ‘le’ in “angle” and the ‘l’ in “also”
. The decimal point matches any single character except the newline character e.g., /.n/ matches ‘an’ and ‘on’ in “nay, an apple is on the tree”, but not ‘nay’.
x(?=y) Matches ‘x’ only if it is followed by ‘y’ e.g., /Jack(?=Spat)/ matches ‘Jack’ only whn it is followed by ‘Spat’. /Jack(?=Spat|Fost)/ matches ‘Jack’ only if it is followed by ‘Spat’ or ‘Fost’; However, neither ‘Spat’ nor ‘Fost’ is part of the match results.
x(?!y) Matches ‘x’ only if it is not followed by ‘y’ e.g., /\d+(?!\.)/ matches a number only when it is not followed by a decimal point e.g., the regular expression /\d+(?!\.)/.exec(“3.141”) matches ‘141’ but not ‘3.141’
x|y Matches ‘x’ or ‘y'(when there’s no match for ‘x’)
{n} Matches exactly n occurrences of the preceding expression where N must be a positive integer. For example, /a{2}/ doesn’t match the ‘a’ in “candy,” but matches all the a’s in “caandy,” and the first two a’s in “caandy”
{n,} Matches at least n occurrences of the preceding expression e.g., /a{2,}/ matches “aa”, “aaa” and “aaaa” but not “a”
[xyz] This pattern matches any one of the characters in the brackets
[^xyz] It matches anything that is not enclosed within the brackets. Everything that works in the normal character set also works e.g., [^abc] is the same as [^a-c]. This initially match ‘r’ in “brisket” and ‘h’ in “chop”
[\b] Matches a backspace
/d Matches a digit character i.e., equivalent to [0-9] e.g., /\d/ matches ‘3’ in “B3 is the number”
/D Matches a non-digit character i.e., equivalent to [^0-9] e.g., /\D/ matches ‘B’ in “B2 is the number”
\s Matches a white space character including space, tab, form feed, line feed etc e.g., /\s\w*/ matches ‘ bar’ in “tool bar”
\S Matches a character other than white space e.g., /\S*/ matches ‘foo’ in “foo bar”
\t Matches a tab
\w Matches any alphanumeric character including underscore e.g., /\w/ matches ‘a’ in “ant,” ‘5’ in “$528,” and ‘2’ in “2D”
\W Matches any non-word character e.g., /\W/ or /[^A-Za-z0-9_]/ matches ‘%’ in “70%”
\n Where n is a positive integer, a back reference to the last substring matching the n characters in the regular expression
\xhh Matches two hexadecimal digits
\uhhh Matches four hexadecimal digits

Methods that uses regular expressions

Method Description
exec It is a RegExp method that executes a search for a match in a string. It returns an array of information or null for a mismatch
test A RegExp method that tests for a match in a string. It returns true or false
match A String method that executes a search for a match in a string. It returns an array of information or null on a mismatch
search A String method that tests for a match in a string. It returns the index of the match or -1 if the search fails
replace A String method that executes a search for a match in a string, and replaces the matched substring with a replacement substring
split A String method that uses a regular expression or a fixed string to break a string into an array of substrings.

Example

Program to check url and mail validity using regular expression

Switch Statement in JavaScript

The switch statement performs different actions based on different condition.

It can be called as the replacement of multiple nested if-else statements.

The JavaScript Switch Statement

  • The switch statement is used to select one of many code blocks to be executed.
  • Switch case is useful for menu based application.

Syntax

How Switch Statement works?

  • At first, the switch expression is evaluated once.
  • The value of the expression is compared with each of the case.
  • If there is a match, the associated block of code is executed i.e., only one case will be executed.
  • If break is not written after each of the code blocks, all the cases are executed after execution of the matched case.
  • The default portion is executed only when the user inputs a wrong value(other than the case values).

The getDay() method returns the weekday as a number within the range 0-6.
(Sunday=0, Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5, Saturday=6)

Example

Managed by MochaHost - Fast & Easy WordPress Hosting