top of page

JavaScript Tutorial- Part 2

Updated: Mar 23, 2021

JavaScript Comments


JavaScript comments is used to explain JavaScript code, and to make it more readable.

JavaScript comments is also used to prevent execution, when testing alternative code.


Single Line Comments

  • Single line comments starts with //.

  • Any text after // till the end of the line will be ignored by JavaScript (that is will not be executed).

Example:

Multi-line Comments

  • Multi-line comments start with /* and end with */.

  • Any text between /* and */ will be ignored by JavaScript.

Example:

Using Comments to Prevent Execution

  • Using comments to prevent execution of code is suitable for code testing.

  • Adding // in front of a code line changes the code lines from an executable line to a comment.

Example:

JavaScript Variables

  • JavaScript variables are containers for storing data values.

  • Data are placed in these containers and then referred by simply naming the container.

  • Before using a variable in a JavaScript program, it is declared with the var keyword.

Example:

In the above example:

  • a stores the value 10

  • b stores the value 2

  • c stores the value 20

Note:- JavaScript variables are containers for storing data values.


JavaScript Identifiers

  • All JavaScript variables must be identified with unique names.

  • These unique names are called identifiers.

  • Identifiers can be short names (like a and b) or more descriptive names (name, age, totalPrice).


The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.Names must begin with a letter Names can also begin with ( $ ) and ( _ ).

  • Names are case sensitive (a and A are different variables).

  • Reserved words (like JavaScript keywords) cannot be used as names.

Note:- JavaScript identifiers are case-sensitive.


The Assignment Operator

  • In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

  • The "equal to" operator is written like (==) in JavaScript.


JavaScript Data Types

  • JavaScript can handle many types of data.

  • Strings are written inside double or single quotes. Numbers are written without quotes.

  • Text values are called text strings.

  • If a number is written in quotes, it will be treated as a text string.

Example:


Declaring (Creating) JavaScript Variables


Creating a variable in JavaScript is called "declaring" a variable.

In JavaScript variable is declared with var keyword:

var name;

After the declaration, the variable has no value (technically it has the value of undefined).

The equal sign is used to assign the value to the variable:

name = "Mukesh";

Value can also be assigned to the variable when it is declared:

var name = "Mukesh";

Example:

Declaring variables at the beginning of the script is preffered.


One Statement, Many Variables

  • Many variables can be declared in one statement.

  • The statement is started with var and separated with comma.

Example:

A declaration can also be span in multiple lines.


Undefined Value

  • In JavaScript, variables are usually declared without a value. The value can be anything and will be provided later, like user input.

  • A variable declared without a value will have the undefined value.

Example:


Re-Declaring JavaScript Variables


If a JavaScript variable is re-defined, it will not lose its value.


Example:

JavaScript Operators

  • An operator is capable of manipulating a certain value or operand.

  • Operators are used to perform specific mathematical and logical computations on operands.

There are various operators supported by JavaScript:

  • Arithmetic Operators

  • Comparison Operators

  • Logical Operators

  • Assignment Operators

  • Ternary Operators

  • typeof Operator

Example:


JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

  • + Addition

  • - Subtraction

  • * Multiplication

  • ** Exponentiation (ES2016)

  • / Division

  • % Modulus (Division Remainder)

  • ++ Increment

  • -- Decrement


JavaScript Assignment Operators


Assignment operators assign values to JavaScript variables.


Operator Example Same As

  • = x = y x = y

  • += x += y x = x + y

  • -= x -= y x = x - y

  • *= x *= y x = x * y

  • /= x /= y x = x / y

  • %= x %= y x = x % y

  • **= x **= y x = x ** y


JavaScript String Operators


The + operator is also used to add (concatenate) strings.


Example:

When used on strings, the + operator is called the concatenation operator.


Adding Strings and Numbers


Adding two numbers, will return the sum, but adding a number and a string will return a string:


Example:

If a number and a string is added, the result will be a string!


JavaScript Comparison Operators


Operator Description

  • == equal to

  • === equal value and equal type

  • != not equal

  • !== not equal value or not equal type

  • > greater than

  • < less than

  • >= greater than or equal to

  • <= less than or equal to

  • ? ternary operator


JavaScript Logical Operators


Operator Description

  • && logical and

  • || logical or

  • ! logical not


JavaScript Type Operators


Operator Description

  • typeof Returns the type of a variable

  • instanceof Returns true if an object is an instance of an object type


JavaScript Functions

  • A function is a set of statements that take inputs, perform some specific computation and produces output.

  • A JavaScript function is executed when "something" invokes it (calls it).

Example:


JavaScript Function Syntax

  • A JavaScript function is defined with the function keyword, followed by a functionName, followed by parentheses ().

  • The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

  • The code to be executed, by the function, is placed inside curly brackets: {}

Syntax:

function functionName(parameter1, parameter2) { // code to be executed }
  • Function parameters are listed inside the parentheses () in the function definition.

  • Function arguments are the values received by the function when it is invoked.

  • Inside the function, the arguments (the parameters) behave as local variables.


Function Invocation

  • JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”.

  • The code inside a function is executed when the function is invoked.


Function Return

  • The return statement begins with the keyword return separated by the value which we want to return from it.

  • When JavaScript reaches a return statement, the function will stop executing.

  • If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

  • Functions often compute a return value. The return value is "returned" back to the "caller".

Example:


Functions Used as Variable Values


Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.


Example:


Local Variables

  • Local variables are variables that are defined within functions.

  • They have local scope, which means that they can only be accessed from within the function.

Example:

  • Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

  • Local variables are created when a function starts, and deleted when the function is completed.


JavaScript Objects

  • As we know, JavaScript variables are containers for data values.

  • JavaScript primitive data-types(Number, String, Boolean, null, undefined and symbol) stores a single value depending on their types.

  • Objects are variables too. But objects can contain many values.

  • The values are written as name:value pairs (name and value separated by a colon).

  • JavaScript objects are containers for named values called properties or methods.

Example:


Object Definition


You define (and create) a JavaScript object with an object literal.

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


Example:


Object Properties


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

Property Property Value

  • first NameJohn

  • last NameDoe

  • age 50

  • eyeColor blue


Accessing Object Properties


Object properties can be accessed in two ways:

objectName.propertyName

or

objectName["propertyName"]


Example:


Object Methods

  • Objects can also have methods.

  • Methods are actions that can be performed on objects.

  • Methods are stored in properties as function definitions.


Property PropertyValue

  • firstName John

  • lastName Doe

  • age 50

  • eyeColor blue

  • fullName function() {return this.firstName + " " + this.lastName;}

Note:-

  • A method is a function stored as a property.

  • In a function definition, this refers to the "owner" of the function.


Accessing Object Methods

  • An object method is a function definition, stored as a property value.

  • An object method can be accessed with the following syntax.

objectName.methodName()


Example:

If a method is accessed without the () parentheses, it will return the function definition:


Do Not Declare Strings, Numbers, and Booleans as Objects!


When a JavaScript variable is declared with the keyword "new", the variable is created as an object:

var x = new String();         // Declares x as a String object var y = new Number();    // Declares y as a Number object var z = new Boolean();    // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.


JavaScript Events


HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.


HTML Events


An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  • An HTML web page has finished loading

  • An HTML input field was changed

  • An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.


HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.


With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:


Example:

In the example above, the JavaScript code changes the content of the element with id="demo".


Common HTML Events


Here is a list of some common HTML events:


Event Description

  • onchange An HTML element has been changed

  • onclick The user clicks an HTML element

  • onmouseover The user moves the mouse over an HTML element

  • onmouseout The user moves the mouse away from an HTML element

  • onkeydown The user pushes a keyboard key

  • onload The browser has finished loading the page


What can JavaScript Do?


Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

  • Things that should be done every time a page loads

  • Things that should be done when the page is closed

  • Action that should be performed when a user clicks a button

  • Content that should be verified when a user inputs data


Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly

  • HTML event attributes can call JavaScript functions

  • You can assign your own event handler functions to HTML elements

  • You can prevent events from being sent or being handled


JavaScript Strings

  • JavaScript strings are used for storing and manipulating text.

  • A JavaScript string is zero or more characters written inside quotes.

  • Single or double quotes can be used.

  • Quotes can be used inside a string, as long as they don't match the quotes surrounding the string.

Example:

String Length

  • To find the length of a string, use the built-in length property.

  • The length property returns the length of a string.

Example:


Escape Character


The backslash (\) escape character turns special characters into string characters:


Code Result Description

  • \' ' Single quote

  • \" " Double quote

  • \\ \ Backslash

The sequence \"  inserts a double quote in a string:


Example:

Six other escape sequences are valid in JavaScript:


Code Result

  • \b Backspace

  • \f Form Feed

  • \n New Line

  • \r Carriage Return

  • \t Horizontal Tabulator

  • \v Vertical Tabulator

Note:- The 6 escape characters above were originally designed to control typewriters, teletypes, and fax machines. They do not make any sense in HTML.



bottom of page