Core fundamentals of JavaScript
Like any other programming language, JavaScript also has statements, expressions, operators, and specific syntax to write and run programs. We will go through the following topics in this section:
- Adding JavaScript to an HTML page
- Statements
- Literals and variables
- Data types
- Expressions and operators
Adding JavaScript to an HTML page
Every modern browser has a JavaScript engine that compiles your JavaScript defined on the page. JavaScript can be placed in the <head>
or <body>
sections of your HTML page. Any statement that is defined under <script></script>
tags will be considered a JavaScript statement and will be processed and understood by the browser's engine.
The following code snippet shows a simple HTML page containing the <script></script>
tags defined within the <head></head>
section:
When the page loads, it will show the pop-up message and a text as This is a simple text. The browser's JavaScript engine executes any script that is defined under the <script>
tag and runs the statements defined within this block. Any statement that is defined directly under the scripting tag is executed every time the page is loaded.
Similarly, we can also define the JavaScript within the <body>
section of the HTML page:
Tip
It is a good idea to place scripts at the bottom of the page because the compilation can slow down the page loading.
Normally, in every project, irrespective of the project size, separating the <script>
section from HTML makes the code look cleaner and easy to maintain. JavaScript file extensions are named .js
and you can also create these files separately in some scripts folder and reference them in our HTML page.
In Visual Studio, you can easily create a JavaScript file using the Add | JavaScript File option as shown in the following:
Once the file is created, we can directly write the JavaScript syntax without any <script></script>
tags. JavaScript files can be referenced in your HTML page using the src
attribute of <script></script>
tags. Here we referenced test.js
in the HTML page:
Placing the <script>
tag either in the <head>
or in the <body>
section depends on the page. If your page referencing some large JavaScript files takes a long time to load, it is better to define them at the end of the <body>
section. This is a better approach, so when the browser starts parsing your page, it is not stuck downloading your scripts and delaying the rendering. On the other hand, we can define JavaScript files in the <head>
section only if they do not impact the performance or page life cycle. Scripts defined at the bottom get parsed when the whole page loads. There are also a few attributes such as async
and defer
that we can use within the <script>
tag and most of the browsers support this.
The following is an example showing the use of async
in the <script>
tag:
Scripts defined with async
are executed asynchronously without blocking the browser to load the page. However, if multiple scripts are there, then each script will be executed asynchronously and at the same time. This may lead to the possibility of completing the second script before the first one gets completed and might throw some errors if one is dependent on the other. For example, when working with some client-side frameworks, such as Angular framework, JavaScript code that is using Angular components is dependent on AngularJS library, and in this case, if our custom JS files are loaded before the AngularJS library on which they are dependent, they will throw an exception.
To overcome this scenario, we can use defer
to execute scripts in a sequence. We can use defer
as follows:
The basic difference between async
and defer
is that async
downloads the file during HTML parsing and pauses the HTML parser to execute it until it is completely downloaded, whereas defer
downloads the file during the HTML parsing and executes it after the HTML parser is completed.
Statements are the collection of words, expressions, and operators to perform a specific task. Like other programming languages, statements in JavaScript could also be assigning a value to the variable, performing arithmetic operations, implementing conditional logic, iterating through collection, and so on.
For example:
However, you can use semicolons with the do while
loop:
Tip
If multiple statements are defined in the same line, they should be separated by a semicolon, otherwise they will be treated as a single statement. On different lines, a semicolon is not mandatory but a good practice to use.
There are two types of values in JavaScript: literals or fixed values and variables.
Literals could be number, string, or date objects.
For example:
Variables are used to store values. In JavaScript, we can define variables using the var
keyword. JavaScript is not a type-safe language and the type is identified when the value is assigned.
For example:
Every programming language has certain data types available to hold specific data. For example, in C#, we can use String
to hold string values, int
to hold 32-bit integer value, DateTime
to hold value in the date and time format, and so on. JavaScript does not provide strong data types such as C# and other programming languages, and it's a loosely typed language. As per the latest ECMA 6 standard, JavaScript provides six primitive data types and an object. All primitive data types are immutable, this means that assigning a new value will be allocated into a separate memory. Object is mutable and its values can be changed.
The primitive types are as follows:
- Boolean: This holds the logical value
true
or false
. - Null: This holds the
null
value. - Undefined: This is a variable that does not assign a value and has value as undefined.
- Number: This holds numeric values. The size of the
number
type is double-precision 64 bit in which the number (fraction) is stored from 0 to 51 bits, the exponent in 11 bits from 52 to 62, and sign in 1 bit 63. - String: This holds any kind of textual value.
Complex types are termed as object. In JavaScript, the object is formulated in a JSON format.
Array is used to store collections of data. You can simply define an array in JavaScript as shown in the following:
You can access them through the array index. The index starts from 0 till the number of items in the array.
We can access the array items as follows:
In order to get the total number of items in an array, you can use the length
property:
The following is a list of some of the most commonly used methods:
JavaScript Object Notation (JSON) is a lightweight, interchangeable format for defining objects in JavaScript. Any kind of object can be defined through JSON and it is used to build universal data structures. Whether it's a simple object, arrays, nested arrays, or complex object, each can handle in the JSON format.
The following code snippet shows the person
object that has three properties, namely name
, email
, and phone
:
We can access these object properties as follows:
The following code snippet shows the way of declaring arrays in JSON:
According to the preceding declaration of an array, it can be accessed as follows:
The JSON format easily handles nested arrays. Let's look at the complex objects containing an employee
object that contains the Experiences
array with the nested array to hold projects, and each project has a nested array to hold technologies used in each project:
In the preceding script, the array has an employee
object containing some properties such as ID, name, and date of joining, and then one experiences property that holds an array of experiences and each experience holds the projects that the employee did in a particular workplace.
Conversions in data types
As the data types in JavaScript are dynamic in nature and data type is determined based on the value assignment, JavaScript does not throw any exception on type conversion and deals in several ways as follows.
For example, the following is the JavaScript code snippet showing the assignment of different expressions.
First assign the string to the res
variable:
Then assign numeric to the same res
variable:
Finally, concatenate string 3
to the res
variable that holds the following numeric, but due to the higher precedence of numerical value, the resultant value becomes 5
:
So, no matter what was the type of the variable first assigned to it, it will change its type based on the assignment and dynamically handle the conversions.
Here are some of the important elements of JavaScript that are essential to learn before we start programming in JavaScript.
Constants in JavaScript can be defined with a const
keyword. Constants are the immutable values that are known at compile time, and values do not change throughout the life cycle of the program.
The following is the JavaScript code showing the assignment of a constant variable. When using const
, var
is not required and you can declare constant values with only the const
keyword:
Comments can be added with //
and /* */
. To comment a single line, you can use //
, otherwise /* */
for a block of code.
The following is the JavaScript code showing the way of commenting a single line or block of code:
JavaScript is a case-sensitive language and it follows the Pascal naming convention to define variables and methods.
For example, if the method name is doWork()
, it can only be accessed by calling it with the exact case, and calling either DoWork()
or Dowork()
will not work and throw exception.
JavaScript is based on a Unicode character set and follows the Unicode Standard.
Note
What is the Unicode Standard?
It is a worldwide coding standard that most languages use. C# and VB.NET follow the same Unicode Standard. It provides a unique number for every character, for example, A = 41
, a = 61
, and so on.
The current version of the Unicode Standard is Unicode 8.0.0 and the documentation can be located at http://www.unicode.org/versions/Unicode8.0.0/.
Expression can be recognized as the statement of code that assigns some value to the variable. Expressions are categorized into two types.
The first type of expression can be termed as simple expressions that assigns a value to the variable:
The preceding example denotes the simple expression of assigning numeric value 2
to an x
variable.
The second type of expression can be termed as any arithmetic or string operation to the values on the right and assigning them to any variable. These type of expressions perform the operation first before assigning value to the variable:
This is an example of the second type of expression that adds two numbers and assigns the resultant value to the x
variable. Same goes for the second statement that performs the string concatenation operation and assigns the Hello World
value to the x
variable.
Just like C# and other object-oriented languages, JavaScript has objects and there are certain ways to define classes, functions, and so on that we will study later in this chapter. Just like C#, in JavaScript, we can access the object and its properties through the this
keyword. Let's take a look at some examples showing the scope of the this
keyword in JavaScript.
The following is a customer
object that contains a few properties and the utilization of the this
keyword:
In the preceding example, we have defined a JavaScript object that contains three properties and a function. To access these properties, we can use the this
keyword just like C#. However, we can also access the properties using the customer
variable, as shown in the following:
The scope of the this
keyword is limited within the boundary of an object. Whereas, the customer
variable in the preceding example could be defined somewhere else on the page and may lead to an incorrect behavior. It is a better approach to use the this
keyword wherever possible and avoid using object variables directly.
All variables and functions defined directly under the <script>
tag are termed as global variables and functions. We can also access them through the this
keyword. In this case, this
will be referred as the global window object and not the child, that is, the customer
object we have used in the previous example:
Unlike this
, you can also refer the variables and functions through the window
keyword. The following code snippet will show the name of the window in the dialog box:
Let's take a look at the complete example, where we have global variables defined, as well as child objects, and the scope of this
will be determined based on the context of its call:
In this preceding example, we will get two JavaScript alert messages. The first alert will display Scott Watson, which is defined globally, and the second popup shows the customer name, e-mail address, and mobile number. Hence, we can use this
in two places, but the scope is determined based on the context from where it is calling from.
Sequence of code execution in JavaScript
When programming in JavaScript, we have to keep the sequence of defining things before they get called. Considering the preceding example, if we define the customer
object after the ShowMessage()
method, it will not be recognized and nothing will be displayed.
Using the this keyword on a calling method
Let's take a look at the sample HTML page that has a JavaScript function named Multiply
and takes two parameters: obj
and val
. This method will be called when the user enters any input into the textbox and it will pass the reference of the textbox control at the first parameter. This can be passed through the this
keyword:
The function statement and expression
The function statements are a way of defining methods in JavaScript. Each function has a signature, containing the name and parameters passed in. Functions can be declared in many ways in JavaScript. For example, the following is the sample GetPerson(id)
function that returns the person
object based on the ID passed as a parameter. This is the normal way of declaring function in JavaScript:
The function
return type is computed at runtime and not part of the function signature. Returning values is not mandatory and you can keep functions without returning any values.
On the other hand, anonymous functions do not have any name and they can either be passed as an argument to other functions or defined without a function name. The following are the examples of anonymous functions:
Another example of defining anonymous function and passing it as a parameter is as follows:
The function expression is equivalent to function, but the only difference is that it should not start with the function name.
Class statement and expression
With ECMAScript 6, we can create classes in JavaScript. Just like other programming languages, we can create a class using the class
keyword. With this, we can write cleaner code than developing functions that were represented as classes in the earlier version of ECMAScript.
Let's take a look at the Rectangle
class that calculates an area:
Each class should have one constructor and give an error if multiple constructors are specified. Class expression is another way of defining classes. Just like anonymous functions, we can define classes in a similar way.
Let's take a look at the example of the same class defined earlier:
The next chapter will cover more details about classes and the attributes and keywords available to structure them.
For any arithmetic expression, JavaScript uses the BODMAS rule. The precedence will be given to brackets then multiplication, division, addition, and subtraction. The grouping operator is used to give higher precedence to the expression if any of the member in the expression have higher precedence by default.
For example:
The resultant x
will be 7
as multiplication gets the higher precedence. However, what if we need to perform addition first?
We can use grouping operator as follows that gives the result 9
:
In the same way as C#, the new
keyword is used to instantiate any object in JavaScript. In order to create an instance of any user-defined or predefined type, use the new
keyword:
The
super
keyword is used to call methods of the parent object. In C#, we use the base
keyword to call the base class method or properties. In JavaScript, we can use it as follows:
Operators are the object used to manipulate values of an operand. For example, 1 + 2
results in 3
, where 1
and 2
are operands and +
is an operator. In JavaScript, we can use almost all the operators to concatenate strings, do arithmetic operations, and so on. In this section, let's see what type of operators we can use when writing programs in JavaScript language.
We will discuss the following operators in this section:
- Assignment operators
- Arithmetic operators
- Unary operators
- Comparison operators
- Logical operators
- Bitwise operators
- Bitwise shift operators
- The typeof operator
- The void operator
- The delete operator
- Miscellaneous operators
Assignment operator is represented as (=
) and the assignment is done from right to left.
For example, x=y
means that the value of y
is assigned to x
.
The following is a list of arithmetic operators you can use to perform addition, subtraction, division, and multiplication and use them with the assignment statements:
Unary operator works with only one operand. It can be used for increment, decrement, inversion, and so on:
Comparison operator is used to compare operands that returns a Boolean true
value if the comparison is true
. Operands can be of any data type, have an associativity from left to right, and perform dynamic conversion if they are of different types.
For example, if the value of x
is 2
and y
is "2"
. Here, y
denotes that it's a string, but in comparison, it will return true
:
Similar to C# or any programming language, JavaScript supports all these operators, such as equal (==
), not equal (!=
), greater than (>
), and less than(<
), but due to the dynamic type binding, it also provides two operators such as strict equal (===
) and strict not equal (!===
) to confirm if the type is also the same if the value is same and vice versa.
We will now have a look at strict operators. There are the following two types of strict operators:
- Strict equal operator
- Strict not equal operator
In the previous section, we discussed that JavaScript provides dynamic binding and if the value of two different data types, suppose number and string, are the same, it will return true
on comparison. For example, if x
is 1
and y
is "1"
, it will return true
. Now, what if we have to do the comparison work only if the type is also the same? Here comes the strict equal operator that does not only check the value, but also match the types of both the operands.
The strict equal operator can be represented as ===
.
For example, if x = 1
and y = "1"
and the comparison is done like (x===y
), it will return false
as x
represents number and y
represents string.
Strict not equal operator
Contrary to the strict equal operator, if we want to compare the values of two operands of same type, we can use the strict not equal operator.
The strict not equal operator can be represented as !===
.
If x = 1
and y = 2
and the comparison is done like (x!==y
), it will return true
. This is because the types are the same and the values are different.
Just like C#, JavaScript uses the same types of logical operators to handle logical conditions. Logical operators are used to handle multiple conditions in a logical statement.
Logical AND is represented as &&
and is used in two or more operands or conditions in statements.
For example, the following is the code snippet that shows the method that takes three parameters and the logic is defined that checks whether number1
is equal to number2
and the summation of number1
and number2
is equal to number3
to return true
:
Logical OR is represented as ||
and is used with two or more operands or logical conditions.
For example, the following is the code snippet that shows the method that takes three parameters, and if any of the numbers is equal to the value 10
, it will return true
:
Logical NOT is represented as !
and used with conditions that return a Boolean value. For example, if any logical condition returns true
, this operator will make it false
. It can be used as follows. In the code snippet, if number1
, number2
, and number3
are equal to 10
, the method will return false
. If they are different, the return value will be true
:
Bitwise operators consider each number or operand as binary (a combination of 0
and 1
). Every number has specific binary corresponding to it. For example, number 1
binary is represented as 0001
and 5
represented as 0101
.
Bitwise operators work on 32-bit numbers and any numeric operand is first converted into a 32-bit number and then converted back to JavaScript number.
Bitwise operators perform their operations in binary and return the result as numbers.
For example, x
is 1
and y
is 9
.
1
represented as 0001
.
9
represented as 1001
.
Bitwise AND is represented as &
and the following is the comparison of each bit of operand 1
and 9
. If both value on each bit is 1
, the result will be 1
, otherwise 0
:
In the JavaScript code, we can use it as follows:
Finally, the resultant value will be 0001
, which is equal to 1
.
Bitwise OR is represented as |
and the following is how the bit OR will be operated:
The following code snippet shows the usage in JavaScript:
Finally, the resultant value will be 1001
, which is equal to 9
.
Bitwise NOT is represented as ~
and it works on a single operand and inverse each bit of the binary.
For example, if the number 9
is represented as 1001
, it will be converted to a 32-bit number and then bitwise NOT will make it 11111111111111111111111111110110
, which is equal to -10
.
The following is the code snippet:
Bitwise XOR is represented as ^
and it works with two or more operands.
The following table shows how the bitwise XOR is operated:
The following code snippet shows the usage in JavaScript:
Finally, the resultant value will be 1000
, which is equal to 8
.
There are three kinds of bitwise shift operators, as follows:
- Bitwise left shift operator
- Bitwise right shift operator
It is represented as <<
and is used to shift a bit from the right side to the binary value of any number.
For example, number 9
is represented as 01001
, and if we use bitwise left, the resultant value will be 10010
, which shifted one bit from the right.
The following code snippet shows the usage in JavaScript:
Finally, the resultant value will be 10010
, which is equal to 18
.
It is represented as >>
and is used to shift a bit from the left side to the binary value of any number.
For example, number 9
is represented as 1001
, using bitwise right will give the resultant value as 0100
.
The following code snippet shows the usage in JavaScript:
Finally, the resultant value will be 0100
, which is equal to 4
.
This is used to check whether the type of the variable is an object, undefined, number, and so on. In JavaScript, we can use this as follows:
Here is the list of possible values returned by the typeof
operator:
The void
operator prevents an expression to return any value. It is essential in conditions where you need to evaluate the expression but don't need the return value in the program.
You can write any expression or statement inside the void
method.
For example, the following code snippet shows the simple example of using a void
operator to display alert message when the link is clicked. Here, the alert
expression is evaluated once the user clicks on the link:
When the page runs and the user clicks on the link, it will display an alert message box as shown in the following:
Moreover, passing 0
as an expression within the void
method will do nothing:
Another example here is using void
to add two numbers and returning undefined
for the assigned operand:
A
delete
operator is used to delete objects and its properties, but not the local variables. The following example shows the way you can use the delete
operator in JavaScript:
Calling country.id
will return undefined
, as this was already deleted in the preceding statement. On the other hand, if we delete the country
object, it would not delete and display the country ID as 1
:
Here are few other operators that are available in JavaScript.
Conditional operator is represented as (?:
):
It works as cross-selector to evaluate expressions. If the first expression is true
, the second expression will be executed, otherwise the third will be executed.
The following is the code snippet for using conditional operator to evaluate expression. There is a compareValues()
function that takes two parameters, and an alert will be displayed stating whether both the parameters are equal or not equal:
The spread operator is represented as (…
). It is used where you expect multiple arguments to be passed in for a function call.
For example, if your function is taking five parameters, you can either pass those values one by one as the parameter value when calling that method or keep them in an array and pass that array through the spread operator.
The following code snippet shows the actual example of using this in JavaScript:
Browser Object Models in JavaScript
JavaScript provides some predefined global objects that you can use to manipulate the DOM, close browsers, and so on. The following are the browser objects we can use to perform different operations:
- Window
- Navigator
- Screen
- History
- Location
Window object refers to the open window in a browser. If in the HTML markup, some iframes are defined, a separate window object will created. Through the window object, we can access the following objects:
- All global variables
- All global functions
- The DOM
The following shows an example of accessing the DOM from the window object and accessing the textbox control.
window.document
returns the document object and we can use its properties and methods for a specific reason:
The window
object itself contains many methods and few of them are as follows:
This object provides the information about the browser. It is beneficial when you need to run specific scripts based on the browser version or do something specific to the browser. Let's look into the methods it exposes.
The properties are described as follows:
appCodeName
: This returns the code name of the browserappName
: This returns the name of the browserappVersion
: This returns the version of the browsercookieEnabled
: This determines whether cookies are enabled in the browsergeoLocation
: This gets the location of the user accessing the pagelanguage
: This returns the language of the browseronline
: This determines whether the browser is onlineplatform
: This returns the platform that the browser has compiledproduct
: This returns the engine name of the browseruserAgent
: This returns the user agent header sent by the browser to the server
The example code is as follows:
The output is shown as follows:
Through the screen object, you can get information about the user's screen. This is helpful to know from which screen the user is viewing the content. If it's a mobile browser or standard desktop screen, you can get the size and other information and modify the content as required.
The properties are described as follows:
availHeight
: This returns the height of the screenavailWidth
: This returns the width of the screencolorDepth
: This returns the bit depth of the color palette for displaying imagesheight
: This returns the total height of the screenpixelDepth
: This returns the color resolution (in bits per pixel) of the screenwidth
: This returns the total width of the screen
The example code is as follows:
The output is shown as follows:
This contains the URLs that the user visited. You can access it through the window.history
object.
You can use this object to navigate to the recently visited links.
The methods are described as follows:
Window.history.back()
: This loads the previous URLWindow.history.forward()
: This loads the recent URL in the history listWindow.history.go()
: This loads a specific URL available in the history list
The location object gives you information about the current URL. Just like history, it can also be accessed through window.location
. There are a few methods and properties you can use to perform specific operations.
The properties are described as follows:
window.location.host
: This returns the hostname and port number of the URLwindow.location.hostname
: This returns only the hostname of the URLwindow.location.href
: This provides the complete URLwindow.location.origin
: This returns the hostname, port number, and protocol of the URLwindow.location.pathname
: This returns the pathname of the URLwindow.location.port
: This returns only the port number of the URLwindow.location.protocol
: This returns the protocol of the URL, for example, HTTP or HTTPSwindow.location.search
: This returns the query string of the URL
The methods are described as follows:
window.location.assign()
: This loads a new document.window.location.reload()
: This reloads the current URL.window.location.replace()
: This can be used to replace the current URL with the new one. Replace does not refresh the page, it can only change the URL.