[go: up one dir, main page]

0% found this document useful (0 votes)
14K views36 pages

Javascript (CodeAcademy) - Предавања v.2

1. JavaScript is a client-side scripting language that is executed in web browsers to make web pages interactive. It allows interaction with HTML elements using the DOM API. 2. JavaScript was created in 1995 by Brendan Eich at Netscape to enable scripting capabilities for web pages in Netscape Navigator browsers without using Java. 3. JavaScript code can be embedded directly in HTML using <script> tags or linked via external .js files and is interpreted and executed by JavaScript engines inside web browsers.

Uploaded by

Nikola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14K views36 pages

Javascript (CodeAcademy) - Предавања v.2

1. JavaScript is a client-side scripting language that is executed in web browsers to make web pages interactive. It allows interaction with HTML elements using the DOM API. 2. JavaScript was created in 1995 by Brendan Eich at Netscape to enable scripting capabilities for web pages in Netscape Navigator browsers without using Java. 3. JavaScript code can be embedded directly in HTML using <script> tags or linked via external .js files and is interpreted and executed by JavaScript engines inside web browsers.

Uploaded by

Nikola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

JAVASCRIPT

What is Javascript
JavaScript is a loosely-typed client side scripting language that executes in the user's web browser. A web page
without JavaScript is unimaginable today. There are many open source application development frameworks based on
JavaScript.

JavaScript is a loosely-typed client side scripting language that executes in the user's browser. JavaScript
interact with html elements (DOM elements) in order to make interactive web user interface.

JavaScript implements ECMAScript standards, which includes core features based on ECMA-262
specification as well as other features which are not based on ECMAScript standards.

JavaScript can be used in various activities like data validation, display popup messages, handling different events of
DOM elements, modifying style of DOM elements etc. The following sample form uses JavaScript to validate data and
change color of form.

Javascript History
In early 1995, Brendan Eich from Netscape, took charge of design and implementation of a new language for
non-java programmers to give access of newly added Java support in Netscape navigator.

Eich eventually decided that a loosely-typed scripting language suited the environment and audience, web
designers and developers who needed to be able to tie into page elements (such as forms, or frames, or
images) without a bytecode compiler or knowledge of object-oriented software design. The dynamic nature
of the language led to it being named "LiveScript" but was quickly renamed to "JavaScript"

Javascript Engine
JavaScript engine in the browser interprets, compiles and executes JavaScript code which is in a web page. It
does memory management, JIT compilation, type system etc. Each browser includes different JavaScript
engines.

Browser JavaScript Engine


Internet Explorer v9.0+ Chakra
Chrome V8
FireFox JagerMonkey
Opera v 14+ V8
Safari JavaScriptCore (Nitro)

1
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Comparison with Server-side Languages


JavaScript is different when compared to server side languages like Java and C#.

The following table lists the differences.

C# Java JavaScript
Strongly-Typed Strongly-Typed Loosely-Typed
Static Static Dynamic
Classical Inheritance Classical Inheritance Prototypal
Classes Classes Functions
Constructors Constructors Functions
Methods Methods Functions

Advantages of Javascript
1. JavaScript is easy to learn.
2. It executes on client's browser, so eliminates server side processing.
3. It executes on any OS.
4. JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc.
5. Performance of web page increases due to client side execution.
6. JavaScript code can be minified to decrease loading time from server.
7. Many JavaScript based application frameworks are available in the market to create Single page web
applications e.g. ExtJS, AngularJS, KnockoutJS etc.

Setting the Environment for Javascript


In order to work with JavaScript, you need to install the following tools:

1. Browser
2. Editor

Browser
You can install any browser as per your preference e.g. Internet Explorer, Chrome, FireFox, Safari, Opera etc.
JavaScript works on any web browser on any OS.

Editor
You can write JavaScript code using a simple editor like Notepad. However, you can also install any open source
or licensed IDE in order to get IntelliSense support for JavaScript and syntax error/warning highlighter e.g.

2
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Visual Studio, Aptana, Eclipse etc. Prefer an editor which has built-in features of IntelliSense support and
syntax error highlighter for speedy development.

Online Editor
You can also use online editor to learn JavaScript e.g. plnkr.co, jsfiddle.net or jsbin.com.

Script Tag
Any type of client-side script can be written inside <script> tag in html. The script tag identifies a block of script
code in the html page. It also loads a script file with src attribute.

The JavaScript code can also be embedded in <script> tag as shown below.

Example: <script> tag

<script>

//write JavaScript here..

</script>

Html 4.x requires type attribute in script tag. The type attribute is used to identify the language of script code
embedded within script tag. This is specified as MIME type e.g. text/javascript, text/ecmascript, text/vbscript
etc. So, for the JavaScript code, specify type="text/javascript" in the script tag in html 4.x page.

Example: Script tag in HTML 4.x:

<script type="text/javascript">

//write JavaScript here..

</script>

Html 5 page does not require type attribute in the <script> tag, because in HTML 5 the default script language
is JavaScript

Script File
If you don't want to write JavaScript between script tag in a web page then you can also write JavaScript code
in a separate file with .js extension and include it in a web page using <script> tag and reference the file via
src attribute.

<script src="/PathToScriptFile.js"></script>

3
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

The script tag can appear any number of times in the <head> or <body> tag.

Script Tag into <head> Tag


You can include script tag into head tag as shown below.

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>

</head>
<body>
<h1> JavaScript Tutorials</h1>

<p>This is JavaScript sample.</p>

</body>

// 1ST Approach
<script>
//write JavaScript code here.
</script>

// 2nd Approach
<script src="/PathToScriptFile.js"></<script> @* External JavaScript file *@

</html>

The browser loads all the scripts in head tag before loading and rendering body html. It is recommended to include scripts before
ending body tag if scripts are not required while window is loading.

Script at the end of <body>


Scripts can also be added at the end of body tag. This way you can be sure that all the web page resources are
loaded and it is safe to interact with DOM.

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JavaScript Demo</title>

</head>
<body>
<h1> JavaScript Tutorials</h1>
<p>This is JavaScript sample.</p>

<!--Some HTML here.. -->

4
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

<script>
//write JavaScript code here..

</script>
<script src="/PathToScriptFile.js"></<script> @* External JavaScript file *@
</body>
</html>

Character Set
JavaScript uses the Unicode character set and so allows almost all characters, punctuations, and symbols.

Case Sensitive
JavaScript is a case sensitive scripting language. It means functions, variables and keywords are case sensitive.

For example, VAR is different from var, John is not equal to john.

String
String is a text in JavaScript. A text content must be enclosed in double or single quotation marks.

Example: string
<script>

"Hello World" //JavaScript string in double quotes

'Hello World' //JavaScript string in single quotes

</script>

Number
JavaScript allows you to work with any kind of numbers like integer, float, hexadecimal etc. Number
must NOT be wrapped in quotation marks.

Integer: 1000

Float: 10.2

Boolean
As in other languages, JavaScript also includes true or false as a boolean value.

5
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Semicolon
JavaScript statements are separated by a semicolon. However, it is not mandatory to end every statement
with a semicolon but it is recommended.

For example, JavaScript considers three different statements for following:

one = 1; two=2; three=3;

White space
JavaScript ignores multiple spaces and tabs.

The following statements are same.

Example: JavaScript ignores whitespaces


var one =1;
var one = 1;
var one = 1;

Comments
A comment is a single or multiple lines, which give some information about the current program. Comments
are not for execution.

Write comment after double slashes // or write multiple lines of comments between/* and */

Example: code comment


var one =1; // this is a single line comment

/* this
is multi line
comment*/

var two = 2;
var three = 3;

Keywords
Keywords are reserved words in JavaScript, which cannot be used as variable names or function names.

The following table lists some of the keywords used in JavaScript.

Keywords

var function if

else do while

for switch break

continue return try

6
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Keywords

catch finally debugger

case class this

default false true

in instanceOf typeOf

new null throw

void width delete

Display Popup Message Box


JavaScript provides different built-in functions to display popup messages for different purposes e.g. to display
a simple message or display a message and take user's confirmation on it or display a popup to take a user's
input value.

Alert Box
Use alert() function to display a popup message to the user. This popup will have OK button to close the popup.

Example: Alert Box


alert("This is alert box!"); // display string message

alert(100); // display number

alert(true); // display boolean

The alert function can display message of any data type e.g. string, number, boolean etc. There is no need to
convert a message to string type.

Confirm Box
Sometimes you need to take the user's confirmation to proceed. For example, you want to take user's
confirmation before saving updated data or deleting existing data. In this scenario, use JavaScript built-in
function confirm(). The confirm() function displays a popup message to the user with two
buttons, OK and Cancel. You can check which button the user has clicked and proceed accordingly.

The following example demonstrates how to display a confirm box and then checks which button the user has
clicked.

Example: Confirm Box


var userPreference;

if (confirm("Do you want to save changes?") == true) {


userPreference = "Data saved successfully!";
} else {
userPreference = "Save Cancelled!";
}

7
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Prompt Box
Sometimes you may need to take the user's input to do further actions in a web page. For example, you want
to calculate EMI based on users' preferred tenure of loan. For this kind of scenario, use JavaScript built-in
function prompt().

Prompt function takes two string parameters. First parameter is the message to be displayed and second
parameter is the default value which will be in input text when the message is displayed.Syntax:

prompt([string message], [string defaultValue]);

Example: prompt Box


var tenure = prompt("Please enter preferred tenure in years", "15");

if (tenure != null) {
alert("You have entered " + tenure + " years" );
}

As you can see in the above example, we have specified a message as first parameter and default value "15"
as second parameter. The prompt function returns a user entered value. If user has not entered anything then
it returns null. So it is recommended to check null before proceeding.

Note: The alert, confirm and prompt functions are global functions. So it can be called using window object
like window.alert(), window.confirm() and window.prompt().

Javascript | Variable
Variable means anything that can vary. JavaScript includes variables which hold the data value and it can be
changed anytime.

JavaScript uses reserved keyword var to declare a variable. A variable must have a unique name. You can
assign a value to a variable using equal to (=) operator when you declare it or before using it.

Syntax:
var <variable-name>;

var <variable-name> = <value>;

Example: Variable Declaration & Initialization

var one = 1; // variable stores numeric value

var two = 'two'; // variable stores string value

var three; // declared a variable without assigning a value

8
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

In the above example, we have declared three variables using var keyword: one, two and three. We have
assigned values to variables one and two at the same time when we declared it, whereas variable three is
declared but does not hold any value yet, so it's value will be 'undefined'.

Declare Variables in a Single Line


Multiple variables can also be declared in a single line separated by comma.

Example: Multiple Variables in a Single Line


var one = 1, two = 'two', three;
var one, two;

Declare a Variable without var Keyword


JavaScript allows variable declaration without var keyword. You must assign a value when you declare a variable
without var keyword.

Example: Variable without var Keyword


one = 1;

two = 'two';

Note: It is Not Recommended to declare a variable without var keyword. It can accidently overwrite an existing global
variable.

Scope of the variables declared without var keyword become global irrespective of where it is declared. Global
variables can be accessed from anywhere in the web page.

White Spaces and Line Breaks in JavaScript


JavaScript allows multiple white spaces and line breaks when you declare a variable with var keyword.

Example: Whitespace and Line Breaks

var
one
=

1,
two
=
"two"

Loosely-typed Variables
C# or Java has strongly typed variables. It means variable must be declared with a particular data type, which
tells what type of data the variable will hold.

JavaScript variables are loosely-typed which means it does not require a data type to be declared. You can
assign any type of literal values to a variable e.g. string, integer, float, boolean etc..
9
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Example: Loosely Typed Variables

var one =1; // numeric value

one = 'one'; // string value

one= 1.1; // decimal value

one = true; // Boolean value

one = null; // null value

Javascript | Operators
JavaScript includes operators as in other languages. An operator performs some operation on single or
multiple operands (data value) and produces a result. For example 1 + 2, where + sign is an operator and 1 is
left operand and 2 is right operand. + operator adds two numeric values and produces a result which is 3 in
this case.yntax:

<Left operand> operator <right operand>

<Left operand> operator

Javascript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators

Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.

Operator Description

+ Adds two numeric operands.

- Subtract right operand from left operand

10
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Operator Description

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators perform different tasks on operands.

Example: Arithmetic Operator


var x = 5, y = 10, z = 15;

x + y; //returns 15

y - x; //returns 5

x * y; //returns 50

y / x; //returns 2

x % 2; //returns 1

x++; //returns 6

x--; //returns 4

+ operator performs concatenation operation when one of the operands is of string type.

The following example shows how + operator performs operation on operands of different data types.

Example: + operator
var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; // "5Hello "

b + c; // "Hello World!"

a + d; // 15

11
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Comparison Operators
JavaScript language includes operators that compare two operands and return Boolean value true or false.

Operators Description

== Compares the equality of two operands without considering type.

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> Checks whether left side value is greater than right side value. If yes then returns true otherwise false.

< Checks whether left operand is less than right operand. If yes then returns true otherwise false.

>= Checks whether left operand is greater than or equal to right operand. If yes then returns true otherwise false.

<= Checks whether left operand is less than or equal to right operand. If yes then returns true otherwise false.

The following example demonstrates how comparison operators perform different tasks.

Example: Comparison Operators


var a = 5, b = 10, c = "5";
var x = a;

a == c; // returns true

a === c; // returns false

a == x; // returns true

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns false

a <= b; // returns true

a >= c; // returns true

a <= c; // returns true

12
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Logical Operators
Logical operators are used to combine two or more conditions. JavaScript includes following logical operators.

Operator Description

&& && is known as AND operator. It checks whether two operands are non-zero (0, false, undefined, null or "" are
considered as zero), if yes then returns 1 otherwise 0.

|| || is known as OR operator. It checks whether any one of the two operands is non-zero (0, false, undefined, null
or "" is considered as zero).

! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)

Example: Logical Operators


var a = 5, b = 10;

(a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false

(a < b) || (a == b); // returns true

!(a < b); // returns false

!(a > b); // returns true

Assignment Operators
JavaScript includes assignment operators to assign values to variables with less key strokes.

Assignment
operators Description

= Assigns right operand value to left operand.

+= Sums up left and right operand values and assign the result to the left operand.

-= Subtract right operand value from left operand value and assign the result to the
left operand.

*= Multiply left and right operand values and assign the result to the left operand.

/= Divide left operand value by right operand value and assign the result to the left
operand.

%= Get the modulus of left operand divide by right operand and assign resulted
modulus to the left operand.

13
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Example: Assignment operators


var x = 5, y = 10, z = 15;

x = y; //x would be 10

x += 1; //x would be 6

x -= 1; //x would be 4

x *= 5; //x would be 25

x /= 5; //x would be 1

x %= 2; //x would be 1

Ternary Operator
JavaScript includes special operator called ternary operator :? that assigns a value to a variable based on some
condition. This is like short form of if-else condition.Syntax:

<condition> ? <value1> : <value2>;

Ternary operator starts with conditional expression followed by ? operator. Second part ( after ? and before :
operator) will be executed if condition turns out to be true. If condition becomes false then third part (after :)
will be executed.

Example: Ternary operator


var a = 10, b = 5;

var c = a > b? a : b; // value of c would be 10


var d = a > b? b : a; // value of d would be 5

Points to Remember:

1. JavaScript includes operators that perform some operation on single or multiple operands (data value) and
produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators, Comparison operators, Logical
operators, Assignment operators, Conditional operators.
3. Ternary operator ?: is a conditional operator.

14
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Javascript | Data Types


JavaScript includes data types similar to other programming languages like Java or C#. Data type indicates
characteristics of data. It tells the compiler whether the data value is numeric, alphabetic, date etc., so that it
can perform the appropriate operation.

JavaScript includes primitive and non-primitive data types as per latest ECMAScript 5.1.

Primitive Data Types

1. String
2. Number
3. Boolean
4. Null
5. Undefined

Non-primitive Data Type

1. Object
2. Date
3. Array

JavaScript is a dynamic or loosely-typed language because a variable can hold value of any data type at any
point of time.

Example: Loosely-typed JavaScript

var myVar = 100;


myVar = true;
myVar = null;
myVar = undefined;
myVar = "Steve";

alert(myVar); // Steve

In the above example, myVar will hold last assigned value to it that is string "Steve".

15
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Javascript - String
String is a primitive data type in JavaScript. A string is textual content. It must be enclosed in single or double
quotation marks.

Example: String literal


"Hello World"

'Hello World'

String value can be assigned to a variable using equal to (=) operator.

Example: String literal assigned to a variable


var str1 = "Hello World";

var str2 = 'Hello World';

A string can also be treated like zero index based character array.

Example: String as array


var str = 'Hello World';

str[0] // H
str[1] // e
str[2] // l
str[3] // l
str[4] // o

str.length // 11

Since, string is character index, it can be accessed using for loop and for-of loop.

Example: Iterate String


var str = 'Hello World';

for(var i =0; i< str.length; i++)


console.log(str[i]);

for(var ch of str)
console.log(ch);

16
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Concatenation
A string is immutable in JavaScript, it can be concatenated using plus (+) operator in JavaScript.

Example: String concatenation


var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ';

Include quotation marks inside string


Use quotation marks inside string value that does not match the quotation marks surrounding the string value.
For example, use single quotation marks if the whole string is enclosed with double quotation marks and visa-
versa.

Example: Quotes in string


var str1 = "This is 'simple' string";

var str2 = 'This is "simple" string';

If you want to include same quotes in a string value as surrounding quotes then use backward slash (\) before
quotation mark inside string value.

Example: Quotes in string


var str1 = "This is \"simple\" string";

var str2 = 'This is \'simple\' string';

String object
Above, we assigned a string literal to a variable. JavaScript allows you to create a String object using
the new keyword, as shown below.

Example: String object


var str1 = new String();
str1 = 'Hello World';

// or

var str2 = new String('Hello World');

In the above example, JavaScript returns String object instead of primitive string type. It is recommended to
use primitive string instead of String object.

17
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Caution:
Be careful while working with String object because comparison of string objects using == operator compares
String objects and not the values. Consider the following example.

Example: String object comparison


var str1 = new String('Hello World');
var str2 = new String('Hello World');
var str3 = 'Hello World';
var str4 = str1;

str1 == str2; // false - because str1 and str2 are two different objects
str1 == str3; // true
str1 === str4; // true

typeof(str1); // object
typeof(str3); //string

Javascript | String Methods & Properties


JavaScript string (primitive or String object) includes default properties and methods which you can use for
different purposes.

String Properties
Property Description

length Returns the length of the string.

String Methods
Method Description

charAt(position) Returns the character at the specified position (in Number).

charCodeAt(position) Returns a number indicating the Unicode value of the character at the given position (in
Number).

concat([string,,]) Joins specified string literal values (specify multiple strings separated by comma) and
returns a new string.

indexOf(SearchString, Returns the index of first occurrence of specified String starting from specified number
Position) index. Returns -1 if not found.

lastIndexOf(SearchString, Returns the last occurrence index of specified SearchString, starting from specified
Position) position. Returns -1 if not found.

localeCompare(string,position) Compares two strings in the current locale.

match(RegExp) Search a string for a match using specified regular expression. Returns a matching array.

18
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Method Description

replace(searchValue, Search specified string value and replace with specified replace Value string and return
replaceValue) new string. Regular expression can also be used as searchValue.

search(RegExp) Search for a match based on specified regular expression.

slice(startNumber, Extracts a section of a string based on specified starting and ending index and returns a
endNumber) new string.

split(separatorString, Splits a String into an array of strings by separating the string into substrings based on
limitNumber) specified separator. Regular expression can also be used as separator.

substr(start, length) Returns the characters in a string from specified starting position through the specified
number of characters (length).

substring(start, end) Returns the characters in a string between start and end indexes.

toLocaleLowerCase() Converts a string to lower case according to current locale.

toLocaleUpperCase() Converts a sting to upper case according to current locale.

toLowerCase() Returns lower case string value.

toString() Returns the value of String object.

toUpperCase() Returns upper case string value.

valueOf() Returns the primitive value of the specified string object.

String Methods for HTML


The following string methods convert the string as a HTML wrapper element.

Method Description

anchor() Creates an HTML anchor <a>element around string value.

big() Wraps string in <big> element.

blink() Wraps a string in <blink> tag.

bold() Wraps string in <b> tag to make it bold in HTML.

fixed() Wraps a string in <tt> tag.

fontcolor() Wraps a string in a <font color="color"> tag.

fontsize() Wraps a string in a <font size="size"> tag.

italics() Wraps a string in <i> tag.

link() Wraps a string in <a>tag where href attribute value is set to specified string.

19
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Method Description

small() Wraps a string in a <small>tag.

strike() Wraps a string in a <strike> tag.

sub() Wraps a string in a <sub>tag

sup() Wraps a string in a <sup>tag

Javascript - Number
The Number is a primitive data type in JavaScript. Number type represents integer, float, hexadecimal, octal
or exponential value. First character in a Number type must be an integer value and it must not be enclosed
in quotation marks.

Example: Number in JavaScript


var int = 100;
var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;

Number object
JavaScript also provides Number object which can be used with new keyword.

var hex = new Number(0xfff);

Caution: Be careful while working with the Number object because comparison of Number objects using ==
operator compares Number objects and not the values. Consider the following example.

Example: Number Object Comparison


var num1 = new Number(100);
var num2 = new Number(100);

var num3 = 100;

num1 == num2; // false - because num1 and num2 are two different objects
num1 == num3; // true
num1 === num3;//false

typeof(num1); // object
typeof(num3); //number

20
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Number Properties
The Number type includes some default properties. JavaScript treats primitive values as object, so all the
properties and methods are applicable to both primitive number values and number objects.

The following table lists all the properties of Number type.

Property Description

MAX_VALUE Returns the maximum number value supported in JavaScript

MIN_VALUE Returns the smallest number value supported in JavaScript

NEGATIVE_INFINITY Returns negative infinity (-Infinity)

NaN Represents a value that is not a number.

POSITIVE_INFINITY Represents positive infinity (Infinity).

Example: Number properties


alert(' Max Value: ' + Number.MAX_VALUE +
'\n Min Value:' + Number.MIN_VALUE +
'\n Negative Infinity:' + Number.NEGATIVE_INFINITY +
'\n Positive Infinity:' + Number.POSITIVE_INFINITY +
'\n NaN:' + Number.NaN
);

Number Methods
The following table lists all the methods of Number type

Method Description

toExponential(fractionDigits) Returns exponential value as a string.

Example:
var num = 100; Num.toExponential(2); // returns '1.00e+2'

toFixed(fractionDigits) Returns string of decimal value of a number based on specified fractionDigits.

Example:
var num = 100; Num.toFixed(2); // returns '100.00'

toLocaleString() Returns a number as a string value according to a browser's locale settings.

Example:
var num = 100; Num.toLocaleString(); // returns '100'

toPrecision(precisionNumber) Returns number as a string with specified total digits.

21
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Method Description

Example:
var num = 100; Num.toPrecision(4); // returns '100.0'

toString() Returns the string representation of the number value.

Example:
var num = 100; Num.toString(); // returns '100'

valueOf() Returns the value of Number object.

Example: var num = new Number(100); Num.valueOf(); // returns '100'

Javascript Boolean
Boolean is a primitive data type in JavaScript. Boolean can have only two values, true or false. It is useful in
controlling program flow using conditional statements like if..else, switch, while, do..while.

Example: Boolean
var YES = true;

var NO = false;

The following example demonstrates how a Boolean value controls the program flow using if condition.

Example: Boolean
var YES = true;
var NO = false;

if(YES)
{
alert("This code block will be executed");
}

if(NO)
{
alert("This code block will not be executed");
}

Any type of comparison will return a Boolean result.

Example: Boolean

alert(1 > 2); // false

alert(10< 9); // false

alert(5 == 5); // true


22
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Boolean object
JavaScript includes Boolean object to represent true or false. It can be initialized using new keyword.

Example: Boolean object


var bool = new Boolean(true);

alert(bool); // true

JavaScript treats empty string (""), 0, undefined and null as false. Everything else is true.

Example: Boolean
var bool1 = new Boolean(""); // false

var bool2 = new Boolean(0); // false

var bool3 = new Boolean(undefined); // false

var bool4 = new Boolean(null); // false

var bool5 = new Boolean(NaN); // false

var bool6 = new Boolean("some text"); // true

var bool7 = new Boolean(1); // true

Boolean Methods
Primitive or Boolean object includes following methods.

Method Description

toLocaleString() Returns string of boolean value in local browser environment.

Example: var result = (1 > 2); result.toLocaleString(); // returns "false"

toString() Returns a string of Boolean.

Example: var result = (1 > 2); result.toString(); // returns "false"

valueOf() Returns the value of the Boolean object.

Example: var result = (1 > 2); result.valueOf(); // returns false

23
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Javascript | Object
Object is a non-primitive data type in JavaScript. It is like any other variable, the only difference is that an
object holds multiple values in terms of properties and methods. Properties can hold values of primitive data
types and methods are functions.

JavaScript objects and JSON objects are different.


In other programming languages like Java or C#, you need a class to create an object of it. In JavaScript, an
object is a standalone entity because there is no class in JavaScript. However, you can achieve class like
functionality using functions. We will learn how to treat a function as a class in the advance JavaScript section.

Let's learn how to create an object in JavaScript.

In JavaScript, an object can be created in two ways:

1. Object literal
2. Object constructor

Object Literal
The object literal is a simple way of creating an object using { } brackets. You can include key-value pair in { },
where key would be property or method name and value will be value of property of any data type or a
function. Use comma (,) to separate multiple key-value pairs.

var <object-name> = { key1: value1, key2: value2,... keyN: valueN};

The following example creates an object using object literal syntax.

Example: Create Object using Object Literal Syntax


var emptyObject = {}; // object with no properties or methods

var person = { firstName: "John" }; // object with single property

// object with single method


var message = {
showMessage: function (val) {
alert(val);
}
};

24
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

// object with properties & method


var person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

You must specify key-value pair in object for properties or methods. Only property or method name without
value is not valid. The following syntax is invalid.

Example: Wrong Syntax


var person = { firstName };

var person = { firstName: };

Access Javascript Object Properties & Methods


You can get or set values of an object's properties using dot notation or bracket. However, you can call an
object's method only using dot notation.

Example: Access JS Object


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

person.firstName; // returns James


person.lastName; // returns Bond

person["firstName"];// returns James


person["lastName"];// returns Bond

person.getFullName();

Note: An object's methods can be called using () operator e.g. person.getFullName(). Without (), it will return function
definition.

25
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Object Constructor
The second way to create an object is with Object Constructor using new keyword. You can attach properties
and methods using dot notation. Optionally, you can also create properties using [ ] brackets and specifying
property name as string.

Example: Object Constructor


var person = new Object();

// Attach properties and methods to person object


person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

// access properties & methods


person.firstName; // James
person.lastName; // Bond
person.getFullName(); // James Bond

Remove Property from an Object


The delete operator deletes a property from an object:

Example

var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};

delete person.age; // or delete person["age"];

// Before deletion: person.age = 50, after deletion, person.age = undefined

26
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Undefined Property or Method


JavaScript will return 'undefined' if you try to access properties or call methods that do not exist.

If you are not sure whether an object has a particular property or not, then use hasOwnProperty() method
before accessing properties.

Example: hasOwnProperty()
var person = new Object();

person.firstName; // returns undefined

Example 2:
if(person.hasOwnProperty("firstName")){
person.firstName;
}

Example 3:
If (person.firstName != undefined) {

person.firstName; // this code will never execute if firstname is undefined

Access Object Keys.


Use for..in loop to get the list of all properties and methods of an object.

Example: Access Object Keys


var person = new Object();

person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

foreach(var item in person){


alert(item); // gets all the keys (properties) from the object
};

27
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Pass by Reference
Object in JavaScript passes by reference from one function to another.

Example: JS Object Passes by Reference


function changeFirstName(per)
{
per.firstName = "Steve";
}

var person = { firstName : "Bill" };


person.firstName = Bill;

changeFirstName(person)
person.firstName; // returns Steve

If, two objects point to the same object then the change made in one object will reflect in another object.

Example: Object Reference


var person = { firstName : "John" };
var anotherPerson = person;
anotherPerson.firstName = "Bill";
person.firstName; //returns Bill

Nested JavaScript Objects


You can assign another object as a property of an object.

Example: Nested JS Objects


var person = {
firstName: "James",
lastName: "Bond",
age: 25,
address: {
id: 1,
country:"UK",
city: {
neighbourhood: Karpos
}
}
};

person.address.country; // returns "UK"


person.address.city.neighbourhood; // returns "Karpos"
var city = person.address.city;

28
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Points to Remember :
1. JavaScript object is a standalone entity that holds multiple values in terms of properties and methods.
2. Object property stores a literal value and method represents function.
3. An object can be created using object literal or object constructor syntax.
4. Object literal:
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};

5. Object constructor:
var person = new Object();

person.firstName = "James";
person["lastName"] = "Bond";
person.age = 25;
person.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};

6. Object properties and methods can be accessed using dot notation or [ ] bracket.
7. An object is passed by reference from one function to another.
8. An object can include another object as a property.

29
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Javascript - Date
JavaScript provides Date object to work with date & time including days, months, years, hours, minutes,
seconds and milliseconds.

The following example shows how to display current date and time using Date object in JavaScript.

Example: Current Local Date

Date(); //current date

//or

var currentDate = new Date(); //current date

As you can see in the above example, we can display current date and time either by calling Date as function
or creating an object with new keyword.

In order to work with date other than current date and time, we must create a date object by specifying
different parameters in the Date constructor.Syntax:

var dt = new Date();

var dt = new Date(milliseconds);

var dt = new Date('date string');

var dt = new Date(year, month[date, hour, minute, second, millisecond]);

As per the above syntax, the following parameters can be specified in Date constructor.

• No Parameter: Date object will be set to current date & time if no parameter is specified in the constructor.
• Milliseconds: Milliseconds can be specified as numeric parameter. The date object will calculate date & time by
adding specified numeric milliseconds from mid night of 1/1/1970
• Date string: String parameter will be treated as a date and will be parsed using Date.parse method.

Overload of Date constructor includes following seven numeric parameters.

• year: Numeric value to represent year of a date.


• month: Numeric value to represent month of a date. Starts with 0 for January till 11 for December
• date: Numeric value to represent day of a date (optional).
• hour: Numeric value to represent hour of a day (optional).
• minute: Numeric value to represent minute of a time segment (optional).
• second: Numeric value to represent second of a time segment (optional).
• millisecond: Numeric value to represent millisecond of a time segment(optional). Specify numeric milliseconds
in the constructor to get the date and time elapsed from 1/1/1970.

In the following example, date object is created by passing milliseconds in Date constructor. So date will be
calculated based on milliseconds elapsed from 1/1/1970.
30
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Example: Create Date by Specifying Milliseconds


var date1 = new Date(0); // Thu Jan 01 1970 05:30:00

var date2 = new Date(1000); // Thu Jan 01 1970 05:30:01

var date3 = new Date(5000); // Thu Jan 01 1970 05:30:05

Specify any valid date as a string to create new date object for the specified date. The following example shows
various formats of date string which you can specify in a Date constructor.

Example: Create Date by Specifying Date String


var date1 = new Date("3 march 2015");

var date2 = new Date("3 February, 2015");

var date3 = new Date("3rd February, 2015"); // invalid date

var date4 = new Date("2015 3 February");

var date5 = new Date("3 2015 February ");

var date6 = new Date("February 3 2015");

var date7 = new Date("February 2015 3");

var date8 = new Date("2 3 2015");

var date9 = new Date("3 march 2015 20:21:44");

You can use any valid separator in date string to differentiate date segments.

Example: Create Date using Different Date Separator


var date1 = new Date("February 2015-3");

var date2 = new Date("February-2015-3");

var date3 = new Date("February-2015-3");

var date4 = new Date("February,2015-3");

var date5 = new Date("February,2015,3");

var date6 = new Date("February*2015,3");

var date7 = new Date("February$2015$3");

var date8 = new Date("3-2-2015"); // MM-dd-YYYY

var date9 = new Date("3/2/2015"); // MM-dd-YYYY

31
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Specify seven numeric values to create a date object with specified year, month and optionally date, hours,
minutes, seconds and milliseconds.

Example: Date
var dt = new Date(2014, 2, 3, 10, 30, 50, 800); // Mon Feb 03 2014 10:30:50

Date Methods
The JavaScript Date object includes various methods to operate on it. Use different methods to get different
segments of date like day, year, month, hour, seconds or milliseconds in either local time or UTC time.

Example: Date Methods


Example 1 : var date = new Date('4-1-2015');

Example 2:
date.getDay();// returns 3

date.getYear();// returns 115, no of years after 1900

date.getFullYear();// returns 2015

date.getMonth();// returns 3, starting 0 with jan

date.getUTCDate();// returns 31

Date Formats
JavaScript supports ISO 8601 date format by default - YYYY-MM-DDTHH:mm:ss.sssZ

Example: ISO Date Format


var dt = new Date('2015-02-10T10:12:50.5000z');

Convert Date Format


Use different Date methods to convert a date from one format to another format e.g. to Universal Time, GMT
or local time format.

For example, use ToUTCString(), ToGMTString(), ToLocalDateString(), ToTimeString() methods to convert date
into respective formats.

Example: Date Conversion in Different Formats


var date = new Date('2015-02-10T10:12:50.500z');

date; 'Default format:'

date.toDateString();'Tue Feb 10 2015'

date.toLocaleDateString();'2/10/2015'

32
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

date.toGMTString(); 'GMT format'

date.toISOString(); '2015-02-10T10:12:50.500Z'

date.toLocaleString();'Local date Format '

date.toLocaleTimeString(); 'Locale time format '

date.toString('YYYY-MM-dd'); 'Tue Feb 10 2015 15:42:50'

date.toTimeString(); '15:42:50'

date.toUTCString(); 'UTC format '

To get date string in formats other than the ones listed above, you need to manually form the date string using
different Date methods. The following example converts date string to DD-MM-YYYY format.

Example: Get Date Segments


var date = new Date('4-1-2015'); // M-D-YYYY

var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();

var dateString = (d <= 9 ? '0' + d : d) + '-' + (m <= 9 ? '0' + m : m) + '-' + y;

Note: Use third party JavaScript Date library like datejs.com or momentjs.com, if you want to work with Dates
extensively.

Parse Date
Use Date.parse() method to convert valid date string into milliseconds since midnight of 1/1/1970.

Example: Date.parse()
Date.parse("5/2/2015"); // 1430505000000

var date = new Date(Date.parse("5/2/2015")); // Sat May 02 2015 00:00:00

Compare Dates
Use comparison operators to compare two date objects.

Example: Date Comparison


var date1 = new Date('4-1-2015');
var date2 = new Date('4-2-2015');

if (date1 > date2)


alert(date1 + ' is greater than ' + date2);
else if (date1 < date2) {
alert(date1 + ' is less than ' + date2);
}

33
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

Points to Remember :

Get current date using Date() or new Date().

Date object can be created using new keyword. e.g. var date = new Date();

Date can be created by specifying milliseconds, date string or year and month in Date constructor.

Date can be created by specifying date string in different formats using different separators.

Date methods are used to perform different tasks on date objects

Date Methods Reference


The following table lists all the get methods of Date object.

Method Description

getDate() Returns numeric day (1 - 31) of the specified date.

getDay() Returns the day of the week (0 - 6) for the specified date.

getFullYear() Returns four digit year of the specified date.

getHours() Returns the hour (0 - 23) in the specified date.

getMilliseconds() Returns the milliseconds (0 - 999) in the specified date.

getMinutes() Returns the minutes (0 - 59) in the specified date.

getMonth() Returns the month (0 - 11) in the specified date.

getSeconds() Returns the seconds (0 - 59) in the specified date.

getTime() Returns the milliseconds as number since January 1, 1970, 00:00:00 UTC.

getTimezoneOffset() Returns the time zone offset in minutes for the current locale.

getUTCDate() Returns the day (1 - 31) of the month of the specified date as per UTC time zone.

getUTCDay() Returns the day (0 - 6) of the week of the specified date as per UTC timezone.

getUTCFullYear() Returns the four digits year of the specified date as per UTC time zone.

getUTCHours() Returns the hours (0 - 23) of the specified date as per UTC time zone.

getUTCMilliseconds() Returns the milliseconds (0 - 999) of the specified date as per UTC time zone.

getUTCMinutes() Returns the minutes (0 - 59) of the specified date as per UTC time zone.

getUTCMonth() Returns the month (0 - 11) of the specified date as per UTC time zone.

getUTCSeconds() Returns the seconds (0 - 59) of the specified date as per UTC time zone.

getYear() Returns the no of years of the specified date since 1990. This method is Deprecated

34
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

The following table lists all the set methods of Date object.

Method Description

setDate() Sets the day as number in the date object.

setFullYear() Sets the four digit full year as number in the date object. Optionally set month and date.

setHours() Sets the hours as number in the date object. Optionally set minutes, seconds and milliseconds.

setMilliseconds() Sets the milliseconds as number in the date object.

setMinutes() Sets the minutes as number in the date object. Optionally set seconds & milliseconds.

setMonth() Sets the month as number in the date object. Optionally set date.

setSeconds() Sets the seconds as number in the date object. Optionally set milliseconds.

setTime() Sets the time as number in the Date object since January 1, 1970, 00:00:00 UTC.

setUTCDate() Sets the day in the date object as per UTC time zone.

setUTCFullYear() Sets the full year in the date object as per UTC time zone

setUTCHours() Sets the hour in the date object as per UTC time zone

setUTCMilliseconds() Sets the milliseconds in the date object as per UTC time zone

setUTCMinutes() Sets the minutes in the date object as per UTC time zone

setUTCMonth() Sets the month in the date object as per UTC time zone

setUTCSeconds() Sets the seconds in the date object as per UTC time zone

setYear() Sets the year in the date object. This method is Deprecated

Returns the date segment from the specified date, excludes time.

toGMTString() Returns a date string in GMT time zone.

toLocaleDateString() Returns the date segment of the specified date using the current locale.

toLocaleFormat() Returns a date string in default format.

toLocaleString() Returns a date string using a current locale format.

toLocaleTimeString() Returns the time segment of the specified Date as a string.

toString() Returns a string for the specified Date object.

toTimeString() Returns the time segment as a string from the specified date object.

toUTCString() Returns a string as per UTC time zone.

valueOf() Returns the primitive value of a Date object.

35
JAVASCRIPT, CODE ACADEMY 2020 JORGOS LAMBRINIDIS

36

You might also like