Home » Posts tagged 'javascript'

Tag 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

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

Loop Control Statement in JavaScript

The Break Statement

  • The break statement can be used to jump out of a loop even when the condition is true.
  • The break statement breaks the loop and continues executing all the code after the loop(if any):

OUTPUT

This time though, we want to stop execution of the loop when i become 3. To do so, we are inserting another conditional checking i, and if the test passes, we will break execution of the loop:

OUTPUT

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

OUTPUT

Loop (Iteration) Statements in JavaScript

Loop(Iteration) Statement

A loop describes the process in a software program/script that repeats the same set of instructions over and over until it receives the order to stop.

Loops offer a quick and easy way to execute something repeatedly. There are 4 types of loop in JavaScript:

  • for statment
  • for/in statement
  • while statment
  • do/while statement

for Statement

The for is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.

Example of for statement

For/in Statement

  • This statement loops through the properties of an object.
  • The block of code snippet inside the loop will be executed once for each of the properties.

While Statement

  • while is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.
  • Initialization of loop variable is mandatory before writing while loop.

Example of while statment

do-while Loop

  • It loops through a block of code once at first and then repeats the loop while the specified condition is true.
  • The main difference between do-while and while loop is that in do-while loop, the set of statements are executed at least once even if the condition isn’t satisfied whereas in while loop nothing is executed if the condition is false.

Example: of do while statement

Nested Loops

An important fact is that both break and continue affect the current loop.

So while working with the nested loops, things can get confusing very quickly.

Consider the following example below:

Note:

  • We have got 2 loops here. Each loop runs for 5 times i.e., 0–4.
  • The first loop will continue if i is even i.e., the only values of i that can ever be logged are 1 & 3 as 0, 2, and 4 will not pass the even criteria: if (i % 2 == 0).
  • Now, the inner lop breaks when j is 2. So, the values of j can only be 0 & 1.

So finally the printed output is:

Managed by MochaHost - Fast & Easy WordPress Hosting