Prototyping and Wireframing: Wed Development

You might also like

You are on page 1of 113

PROTOTYPING AND

WIREFRAMING

Wed Development
Objectives

▰ At the end of the chapter, students are


expected to:
▻ Explain how prototyping and
wireframing works
▻ Explain the benefits of
prototyping
▻ Compare paper prototypes,
wireframes, and clickable
prototypes
2
Prototyping Mockups Wireframe

3
Prototyping Mockups Wireframe

4
Prototyping Mockups Wireframe

5
Prototype

Nothing brings you closer to the functionality of the final product than prototyping. While
wireframes sketch out the blueprint and mockups show the feel and texture of the design, it
is the prototype that brings to life the “experience” behind “user experience.” That beautiful
call-to-action may look great on the screen, but you won’t know if it works on end users
until the clickable prototype. Not only do prototypes help provide proof of concept, they
more importantly expose any usability flaws behind the wireframes and mockups.

6
5 Reasons Why You need to Prototype

While skipping prototyping might save some time during design, that surplus can be lost
many times over in development. If people try on jeans before buying them and test- drive
cars before signing the check, then it only makes sense to test your designs interactively
before they go into development. Interaction, after all, is how users access the design
solutions to their problems. While these vary depending on designers and their needs, some
universal benefits include:

• Communication and Collaboration


• Gauge feasibility while reducing waste
• Sell your idea
• Test usability earlier
• Set your design priorities 7
Communication and Collaboration

It’s one thing to discuss re-quirements documentation, but it’s a whole other level of imagi-
native collaboration when both parties can play with a prototype and explore limitations and
possibilities. Documentation can be misinterpreted, but experiences are shared.

8
Gauge feasibility while reducing waste

Wireframes, mockups, and requirement documents live in paper, not reality. Prototyp-ing
allows teams to experiment, giving them the freedom to fail cheaply while learning more.
Just take a look at how prototypes helped increase estimate accuracy by 50% while reducing
re-quests for clarification by 80%.

9
Sell your idea

Prototypes can be great for pitching if you’re working with skeptical clients.
Experiencing the real-life web-site or app proves your vision more than a wordy
description or mockup bogged down with notes.

10
Test usability earlier

By user-testing a prototype, you’re able to find problems and fix them earlier in the process,
saving your-self a huge hassle of dealing with them when they’re cemented in code. The
same case study cited above saw 25% reduction in post-release bugs thanks to prototyping.

11
Set your design priorities

We recommend prototyping early and often because prioritizing interaction design will keep
you grounded in reality when you make static design decisions. The visuals must fulfill the
experience, not the other way around.

12
When to start Prototyping: 3 Points of Convergence

There’s no green light that will magically blink when it’s time to start prototyping. How and
when to prototype is the subject of much debate in the design world, and various differing
theories and strategies have emerged.

 Sketching – Brainstorm by drawing quick and dirty sketches on paper.


 Wireframing – Start laying out the skeletal framework with boxes and rough shapes.
 Mockups – Inject detail into wireframes with colors, typogra-phies, photos,
and other visual design elements.
 Prototyping – Add interactivity to mockups by stitching screens together for basic
prototypes or adding animations/interactions for advanced prototypes.
• Development – Code in language of choice to turn the prototype into the final product
13
Wireframing and Prototyping

Some designers prefer to get to prototyping right away, and for good reason. This is a core
concept of Lean UX, devised by Jeff Gothelf, Director of UX at Neo Innovation Labs (you
can hear him describe it in this thorough webinar). Lean UX emphasizes prototypes as “the
fastest way between you and your code.”

14
Wireframing and Prototyping

Lean UX Concept Typical Questions

•Who are our users?


•What is the product used for?
•When is it used?
•What situations is it used in?
•What will be the most important functionality?
•What’s the biggest risk to product delivery?

15
Adavantages of a Lean UX

 Faster – Skipping and consolidating phases will get you to the end
product
faster, but possibly at the cost of quality.
 More efficient – The nature of the method is to avoid waste, so the work done will be
only the essentials – no time spent on “busy work.”
 Experience, not deliverables – Part of “trimming the fat” is min-imizing
documentation. Teams communicate better and faster, improving collaboration in
designing the experience. State the design vision, then iterate with that in mind.
16
Mockups & Prototype

Mockups are like a better-dressed wireframe. Neither require functionality, but mockups give you a
better idea of what the final product will look like, and at times suggest how it will func- tion. Usually
mockups are built from wireframes, but this is not always the case.

The main difference between building a prototype off a mockup instead of a wireframe is that
mockups automatically provide the baseline design for a mid- to high-fidelity prototype. Because
wireframes are so bare-bones, prototypes built from them are still low fidelity.

One of major strengths of JavaScript is that it does not require expensive development tools. You can
start with a simple text editor such as Notepad. Since it is an interpreted language inside the context
of a web browser, you do not even need to buy a compiler.
17
Traditional Prototyping Methods and Tools

Paper Prototypes

In the age of modern technology, it can sometimes be refreshing getting back to the tools we
used in kindergarten. Paper, scissors, glue, coloring utensils – what we once used to make
unicorn col-lages can now be co-opted for creating useful yet quick prototypes. Let’s
explore the benefits, disadvantages, and methods for paper prototyping.

18
Traditional Prototyping Methods and Tools

Advantages of Paper Prototyping - The benefits of paper prototyping are quite


straightforward: they’re cheap, fast to make, and easy to collaborate with. Shawn Medero,
UX Lead at the University of Washington, believes that starting on paper can be a
surprisingly helpful tactic as interfaces become more complex and development schedules
become shorter. Here’s a few reasons why:
 Rapid Iteration
 Low Budget
 Fun Collaboration
19
 Easy Documentation
Traditional Prototyping Methods and Tools

Disadvantages of Paper Prototyping - However, paper prototyping isn’t for everyone. Jake
Knapps, the designer behind Google Hangouts, claims that it is a “waste of time.” While we
think it has its time and place, these are some of its glaring disadvantages.
 They can generate false positives
 No gut reactions
 Can be slower than prototyping tools

20
Traditional Prototyping Methods and Tools

Process - Don’t let the scissors and the pretty colors fool you – paper proto-typing isn’t just
fun and games. Whether you’re creating one for your team, for usability testing, or for a
stakeholder presentation, your paper props should be both professional and functional.
 Sketch each screen
 Create user scenarios
 Rehearsal
 Presentation/Test

21
Digital Prototyping Methods and Tools

Asking What’s the best way to prototype? is like asking What’s the best way to make a
website? – there is no single “best” way. Each in-dividual prototype, like each individual
website, has its own styles, objectives, and strategies.

22
Digital Prototyping Methods and Tools

Presentation Software

For starters, there’s the traditional PowerPoint, a reliable business staple used for
presentations for over two decades. If you’re look-ing for a more modern alternative,
Keynote is rising in popularity. Interestingly enough, Google Ventures mentioned Keynote as
a secret weapon for their “design sprint” initiative.

23
Digital Prototyping Methods and Tools

Advantages of Presentation Software - Almost everyone has used presentation software


before, so they’re a quick way to start a simple prototype.
 Familiarity
 Basic element libraries
 Natural Linear Flow

24
Digital Prototyping Methods and Tools

Disadvantages of Presentation Software - Like we described in The Guide to


Wireframing, once you start playing around with advanced user flows and interactions,
you’ve basically hit the limit of presentation software.
 Non-stock element Libraries
 Limited collaboration
 Limited flow charting and user flows
Limited interactivity

25
Digital Prototyping Methods and Tools

Coded (HTML) Prototype

This uncertainty stems from some designers’ lack of comfort with coding: they either don’t
know how to do it, or don’t like doing it. When faced with the more fun and intuitive
method of using a prototyping tool or even sketching by hand, writing code can feel tedious.

26
Digital Prototyping Methods and Tools

• Platform agnostic– HTML prototypes work on any operating system, and


nobody needs outside software to use it.
• Modularity– HTML is component-based, which can help with productivity.
• Low cost (aside from time) – There’s many free HTML text edi-tors, but
you’ll need to spend some time learning the language before it’s helpful.
• Technical foundation for the product – Provided you’re creating production-ready
code (and not just throwaway for the sake of a quick prototype), you can end up
saving time in development.
27
Prototyping Software and Apps

Eager to dive straight into a computer program that’s an actual representation of your idea? The beauty
of prototyping software and apps is that it’s specifically designed for this purpose, so they provide the
perfect balance between functionality, learning curve, and ease-of-use. Both beginner and veteran
designers use special-ized tools like the ones below – beginners for the ease-of-use, and veterans for the
controls crafted to their particular needs.These tools vary in their capabilities, with some being better at-
tuned to certain situations than others, so it’s best to find the one best suited to your needs. To start on
your search, you can check out tools like UXPin, Invision, MockFlow, JustInMind, Axure, Omn-igraffle,
JustProto, Flinto, or Marvel.

28
Advantages of Prototyping Tools

• Speed

• Element Libraries

• Advance Flowcharting & user flows

• Built-in Collaboration

• Streamlined Presentation

29
Disadvantages of Prototyping Tools

• Lack of familiarity

• Limited Fidelity & Functionality

30
THANKS!Any questions?
You can find me at @
https://www.facebook.com/rjd.agustin &
rjdagustin@tsu.edu.ph
31
INTRODUCTION
TO JAVASCRIPT
Client Side Scripting

34
Why use client-side programming?
PHP already allows us to create dynamic web pages. Why also use client-
side scripting?
⦿ client-side scripting (JavaScript) benefits:
⌾ usability: can modify a page without having to post back to the
server (faster UI)
⌾ efficiency: can make small, quick changes to page without
waiting for server
⌾ event-driven: can respond to user actions like clicks and key
presses
35
Why use client-side programming?
⦿ server-side programming (PHP) benefits:
⌾ security: has access to server's private data; client can't see source
code
⌾ compatibility: not subject to browser compatibility issues
⌾ power: can write files, open connections to servers, connect to
databases, ...

36
What is JavaScript?
⦿ a lightweight programming language ("scripting language")
⌾ used to make web pages interactive
⌾ insert dynamic text into HTML (ex: username)
⌾ react to events (ex: page load user click)
⌾ get information about a user's computer (ex: browser type)
⌾ perform calculations on user's computer (ex: form validation)

37
What is JavaScript?
⦿ a web standard (but not supported identically by all browsers)
⦿ NOT related to Java other than by name and some syntactic similarities

38
JavaScript vs Java
⦿ interpreted, not compiled
⦿ more relaxed syntax and rules
⌾ fewer and "looser" data types
⌾ variables don't need to be declared
⌾ errors often silent (few exceptions)
⦿ key construct is the function rather than the class
⌾ "first-class" functions are used in many situations
⦿ contained within a web page and integrates with its HTML/CSS
content 39
JavaScript vs. PHP
⦿ similarities:
⌾ both are interpreted, not compiled
⌾ both are relaxed about syntax, rules, and types
⌾ both are case-sensitive
⌾ both have built-in regular expressions for powerful text processing

40
JavaScript vs. PHP
⦿ differences:
⌾ JS is more object-oriented: noun.verb(), less procedural:
verb(noun)
⌾ JS focuses on user interfaces and interacting with a document;
PHP is geared toward HTML output and file/form processing
⌾ JS code runs on the client's browser; PHP code runs on the web
server

41
Linking to a JavaScript file: script
<script src="filename"
type="text/javascript"></script>
HTML
⦿ script tag should be placed in HTML page's head
⦿ script code is stored in a separate .js file
⦿ JS code can be placed directly in the HTML file's body or head (like
CSS)
⌾ but this is bad style (should separate content, presentation, and
behavior

42
Event-driven Programming

43
Linking to a JavaScript file: script
alert(“Web Development RJDA Intro to
JavaScript"); JS

⦿ a JS command that pops up a dialog box with a message

44
Event-driven programming
⦿ you are used to programs start with a main method (or implicit main
like in PHP)
⦿ JavaScript programs instead wait for user actions called events and
respond to them
⦿ event-driven programming: writing programs driven by user events
⦿ Let's write a page with a clickable button that pops up a "Hello, World"
window...

45
JavaScript functions
function name() {
statement ;
statement ;
...
statement ;
} JS

function myFunction() {
alert("Hello!");
alert("How are you?");
} JS

⦿ the above could be the contents of example.js linked to our HTML


page
⦿ statements placed into functions can be evaluated in response to user
events
46
Event handlers
<element attributes onclick="function();">... HTML
<button onclick="myFunction();">Click me!</button>
HTML
⦿ JavaScript functions can be set as event handlers
⌾ when you interact with the element, the function will execute
⦿ onclick is just one of many event HTML attributes we'll use
⦿ but popping up an alert window is disruptive and annoying
⌾ A better user experience would be to have the message appear on
the page...
47
Document Object Model (DOM)
⦿ most JS code manipulates elements on an
HTML page
⦿ we can examine elements' state
⌾ e.g. see whether a box is checked
⦿ we can change state
⌾ e.g. insert some new text into a div
⦿ we can change styles
⌾ e.g. make a paragraph red

48
Document Object Model (DOM)

49
Accessing elements:
document.getElementById
var name = document.getElementById("id"); JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" /> HTML
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");

textbox.style.color = "red";

} JS 50
Accessing elements:
document.getElementById
⦿ document.getElementById returns the DOM object for an element with
a given id
⦿ can change the text inside most elements by setting the innerHTML
property
⦿ can change the text in form controls by setting the value property

51
Changing element style:
element.style
Attribute Property or style object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily

52
Preetify
function changeText() {
//grab or initialize text here

// font styles added by JS:


text.style.fontSize = "13pt";
text.style.fontFamily = "Comic Sans MS";
text.style.color = "red"; // or pink?
} JS

53
MORE JAVASCRIPT
SYNTAX
Variables
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
⦿ variables are declared with the var keyword (case sensitive)
⦿ types are not specified, but JS does have types ("loosely typed")
⌾ Number, Boolean, String, Array, Object,
Function, Null, Undefined
⌾ can find out a variable's type by calling typeof
55
Comments (same as Java)
// single-line comment
/* multi-line comment */ JS
⦿ identical to Java's comment syntax
⦿ recall: 4 comment syntaxes
⌾ HTML: <!-- comment -->
⌾ CSS/JS/PHP: /* comment */
⌾ Java/JS/PHP: // comment
⌾ PHP: # comment
56
Math object
var rand1to10 = Math.floor(Math.random() * 10 +
1);
var three = Math.floor(Math.PI); JS
⦿ methods: abs, ceil, cos, floor, log, max, min,
pow, random, round, sin, sqrt, tan
⦿ properties: E, PI

57
Special values: null and undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined JS
⦿ undefined : has not been declared, does not exist
⦿ null : exists, but was specifically assigned an empty or null value
⦿ Why does JavaScript have both?

58
Logical operators
⦿ > < >= <= && || ! == != === !==
⦿ most logical operators automatically convert types:
⌾ 5 < "7" is true
⌾ 42 == 42.0 is true
⌾ "5.0" == 5 is true

⦿ === and !== are strict equality tests; checks both type and value
⌾ "5.0" === 5 is false
59
if/else statement (same as Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
⦿ identical JS
structure to Java's if/else statement
⦿ JavaScript allows almost anything as a condition

60
for loop (same as Java)
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
} JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"
JS

61
while loops (same as Java)
while (condition) {
statements;
} JS
do {
statements;
} while (condition); JS
⦿ break and continue keywords also behave as in Java

62
Popup boxes
alert("message"); // message
confirm("message"); // returns true or
false
prompt("message"); // returns user input
string JS

63
Arrays
var name = []; // empty array
var name = [value, value, ..., value]; //
pre-filled
name[index]
var ducks = = value; //
["Huey", store element
"Dewey", "Louie"];
JS
var stooges = []; // stooges.length is 0
stooges[0] = "Larry"; // stooges.length is
1
stooges[1] = "Moe"; // stooges.length is 2
stooges[4] = "Curly"; // stooges.length is
5
stooges[4] = "Shemp"; // stooges.length is
5 JS 64
Array methods
var a = ["Stef", "Jason"]; // Stef, Jason
a.push("Brian"); // Stef, Jason, Brian
a.unshift("Kelly"); // Kelly, Stef,
Jason, Brian
a.pop(); // Kelly, Stef, Jason
a.shift(); // Stef, Jason
⦿ array serves as many data structures: list, queue, stack, ...
a.sort(); // Jason, Stef JS
⦿ methods: concat, join, pop, push, reverse, shift,
slice, sort, splice, toString, unshift
⌾ push and pop add / remove from back
⌾ unshift and shift add / remove from front
⌾ shift and pop return the element that is removed
65
String type
var s = "Connie Client";
var fName = s.substring(0, s.indexOf("
")); // "Connie"
var len = s.length; // 13
var s2 = 'Melvin Merchant'; JS
⦿ methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase, toUpperCase

⌾ charAt returns a one-letter String (there is no char type)


⦿ length property (not a method as in Java)
⦿ Strings can be specified with "" or ''
⦿ concatenation with + :

⌾ 1 + 1 is 2, but "1" + 1 is "11"

66
THANKS!
Any questions?
You can find me at:
⦿ facebook.com/rjd.agustin
⦿ rjdagustin@tsu.edu.ph

67
68
JS Variables, Types
and Functions
JavaScript Variables
⦿ 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.

70
JavaScript Variables
var <variable-name>;

var <variable-name> = <value>;


Syntax
Example:
var one = 1; // variable stores numeric value

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

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

JS

71
Declare Variables in a Single Line

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


comma.

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


JS

72
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.

one = 1;
two = 'two';
JS
⦿ 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.
73
White Spaces and Line Breaks
in JavaScript
⦿ JavaScript allows multiple white spaces and line breaks when you
declare a variable with var keyword.
var
one
=

1,
two
=
"two"

document.getElementById("p1").innerHTML = one;
document.getElementById("p2").innerHTML = two;
JS

74
White Spaces and Line Breaks
in JavaScript
⦿ Output from the provided code:

⦿ Please note from the code that semicolon is optional.

75
Loosely-typed Variables
⦿ Java has strongly typed variables that 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.

var one =1; // numeric value


one = 'one'; // string value
one= 1.1; // decimal value
one = true; // Boolean value
one = null; // null value
JS

76
Loosely-typed Variables
Points to Remember :
1. Variable stores a single data value that can be changed later.
2. Variables can be defined using var keyword. Variables defined
without var keyword become global variables.
3. Variables must be initialized before using.
4. Multiple variables can be defined in a single line. e.g. var one = 1,
two = 2, three = "three";
5. Variables in JavaScript are loosely-typed variables. It can store
value of any data type through out it's lifetime.

77
JavaScript Data Types

Java has strongly typed variables that means variable must be declared
with a particular data type, which tells what type of data the variable will
hold.

Primitive Data Types


1. String Non-primitive Data Type
2. Number 1. Object
3. Boolean 2. Date
4. Null 3. Array
5. Undefined
78
JavaScript Data Types

JavaScript is a dynamic or loosely-typed language because a variable can


hold value of any data type at any point of time.

var myVar = 100;


myVar = true;
myVar = null;
myVar = undefined;
myVar = “Javascript Data
Types";
alert(myVar); // Javascript
Data Types

JS

79
JavaScript - String

⦿ Java String is a primitive data type in JavaScript. A string is textual


content. It must be enclosed in single or double quotation marks.

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

var str1 = "Hello World";

var str2 = 'Hello World’;


JS

80
JavaScript - String

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

var str = 'Hello World';

document.getElementById("p1").innerHTML = str[0];
document.getElementById("p2").innerHTML = str[1];
document.getElementById("p3").innerHTML = str[2];
document.getElementById("p4").innerHTML = str[3];
document.getElementById("p5").innerHTML = str[4];
document.getElementById("p6").innerHTML = str.length

81
JavaScript - String

⦿ Since, string is character index, it can be accessed using for loop and
for-of loop.
var str = 'Hello World';
for(var i =0; i< str.length;i++)
document.getElementById("p1").innerHTML =
document.getElementById("p1").innerHTML + str[i];
for(var ch of str)
document.getElementById("p2").innerHTML =
document.getElementById("p2").innerHTML + ch;
JS

⦿ The code provided will output the word “Hello World” twice.

82
JavaScript – String

⦿ A string is immutable in JavaScript, it can be concatenated using plus


(+) operator in JavaScript.
var str = 'Hello ' + "World " + 'from ' + 'TutorialsTeacher ‘;
JS

⦿ JavaScript allows you to create a String object using the new


keyword, as shown below.
var str1 = new String();
str1 = 'Hello World’;
// or
var str2 = new String('Hello World’);
JS
83
JavaScript – 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
Position) starting from specified number index. Returns -1 if not
found.

84
JavaScript – String Methods

Method Description
lastIndexOf(SearchString, Returns the last occurrence index of specified
Position) SearchString, starting from specified 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.
replace(searchValue, Search specified string value and replace with specified
replaceValue) replace Value string and return new string. Regular
expression can also be used as searchValue.

85
JavaScript – String Methods

Method Description
slice(startNumber, Extracts a section of a string based on specified starting
endNumber) and ending index and returns a new string.
split(separatorString, Splits a String into an array of strings by separating the
limitNumber) string into substrings based on 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.

86
JavaScript – String Methods

Method Description
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.

87
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.

var int = 100;


var float = 100.5;
var hex = 0xfff;
var exponential = 2.56e3;
var octal = 030;
document.getElementById("p1").innerHTML = int;
document.getElementById("p2").innerHTML = float;
document.getElementById("p3").innerHTML = hex;
document.getElementById("p4").innerHTML = exponential;
document.getElementById("p5").innerHTML = octal;
JS
88
JavaScript – Number Methods
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'

89
JavaScript – Number Methods
Method Description
toPrecision(precisionNumber) Returns number as a string with specified total digits.

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'

90
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.

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");
}
JS
91
JavaScript – Boolean 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

92
JavaScript – 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.

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


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
JS

93
JavaScript – Date Formats

⦿ JavaScript supports ISO 8601 date format by default - YYYY-MM-


DDTHH:mm:ss.sssZ

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.
94
JavaScript – Date Format Conversion

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


date; 'Default format:'
date.toDateString();'Tue Feb 10 2015'
date.toLocaleDateString();'2/10/2015'
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’
JS

95
JavaScript – Array

⦿ An array is a special type of variable, which can store multiple values using
special syntax. Every value is associated with numeric index starting with 0.
The following figure illustrates how an array stores values.

96
JavaScript – Array

⦿ Array Initialization
An array in JavaScript can be defined and initialized in two ways, array
literal and Array constructor syntax.

⦿ Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma
and enclosed in square brackets.

var <array-name> = [element0, element1, element2,... elementN];

97
JavaScript – Array
⦿ Declare and initialize JS Array

var stringArray = ["one", "two", "three"];

var numericArray = [1, 2, 3, 4];

var decimalArray = [1.1, 1.2, 1.3];

var booleanArray = [true, false, false, true];

var mixedArray = [1, "two", "three", 4];

⦿ JavaScript array can store multiple element of different data types. It is not
required to store value of same data type in an array.
98
JavaScript – Array
⦿ Accessing Array Elements
An array elements (values) can be accessed using index (key). Specify an index in
square bracket with array name to access the element at particular index. Please
note that index of an array starts from zero in JavaScript.
var stringArray = new Array("one", "two", "three", "four");
document.getElementById("p1").innerHTML = stringArray[0];
document.getElementById("p2").innerHTML = stringArray[1];
document.getElementById("p3").innerHTML = stringArray[2];
document.getElementById("p4").innerHTML = stringArray[3];

var numericArray = [1, 2, 3, 4];


document.getElementById("p5").innerHTML = numericArray[0];
document.getElementById("p6").innerHTML = numericArray[1];
document.getElementById("p7").innerHTML = numericArray[2];
document.getElementById("p8").innerHTML = numericArray[3];
JS
99
JavaScript – Array

⦿ Array Properties
Array includes "length" property which returns number of elements in the array.
Use for loop to access all the elements of an array using length property.

var stringArray = new Array("one", "two", "three", "four");


for (var i = 0; i < stringArray.length ; i++)
{
stringArray[i];
}
JS

100
JavaScript – Array Methods

concat() pop()
every() push()
filter() reduce()
forEach() reverse()
indexOf() shift()
join() slice()
lastIndexOf() sort()
map() toString()

101
JavaScript – Null and Undefined

⦿ Null
You can assign null to a variable to denote that currently that variable does not
have any value but it will have later on. A null means absence of a value.

var myVar = null;

alert(myVar); // null
JS

In the above example, null is assigned to a variable myVar. It means we have


defined a variable but have not assigned any value yet, so value is absence.

102
JavaScript – Null and Undefined

⦿ Null
A null value evaluates to false in conditional expression. So you don't have to use
comparison operators like === or !== to check for null values.

var myVar = null;

if (myVar)
alert("myVar is not null');
else
alert("myVar is null" );
JS

103
JavaScript – Null and Undefined

⦿ Undefined

A variable or an object has an undefined value when no value is assigned before


using it. So you can say that undefined means lack of value or unknown value.

var myVar;
alert(myVar); // undefined

In the above example, we have not assigned any value to a variable named
'myVar'. A variable 'myVar' lacks a value. So it is undefined.

104
JavaScript – Null and Undefined
⦿ Undefined

You will get undefined value when you call a non-existent property or method of
an object.
function Sum(val1, val2)
{
var result = val1 + val2;
}
var result = Sum(5, 5);
alert(result);// undefined
JS

A function Sum does not return any result but still we try to assign its resulted
value to a variable. So in this case, result will be undefined. 105
JavaScript – Function

⦿ In JavaScript, a function allows you to define a block of code, give it a name


and then execute it as many times as you want.
⦿ A JavaScript function can be defined using function keyword.
SYNTAX:

//defining a function
function <function-name>()
{
// code to be executed
};

//calling a function
<function-name>();

106
JavaScript – Function
⦿ The following example shows how to define and call a function in JavaScript.

function ShowMessage() {
alert(“Javascript Function!");
}
ShowMessage();
JS

⦿ This will generate the output below:

107
JavaScript – Function Parameters
⦿ You can pass less or more arguments while calling a function. If you pass less
arguments then rest of the parameters will be undefined. If you pass more
arguments then additional arguments will be ignored.

function ShowMessage(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs", "Mr."); // display Hello


Steve Jobs
ShowMessage("Bill"); // display Hello Bill undefined
ShowMessage(); // display Hello undefined undefined

108
JavaScript – Argument Object
⦿ All the functions in JavaScript can use arguments object by default. An
arguments object includes value of each parameter.

⦿ The arguments object is an array like object. You can access its values using
index similar to array. However, it does not support array methods.

function ShowMessage(firstName, lastName) {


alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

109
JavaScript – Argument Object
⦿ An arguments object is still valid even if function does not include any
parameters.
function ShowMessage() {
alert("Hello " + arguments[0] + " " + arguments[1]);}
ShowMessage("Steve", "Jobs"); // display Hello Steve Jobs

⦿ An arguments object can be iterated using for loop.


function ShowMessage() {
for(var i = 0; i < arguments.length; i++){
alert(arguments[i]);
}
}
ShowMessage("Steve", "Jobs");

110
JavaScript – Return Value
⦿ A function can return zero or one value using return keyword.

function Sum(val1, val2) {


return val1 + val2;
};

var result = Sum(10,20); // returns 30

function Multiply(val1, val2) {


console.log( val1 * val2);
};

result = Multiply(10,20); // undefined

111
JavaScript – Return Value
⦿ A function can return zero or one value using return keyword.

function Sum(val1, val2) {


return val1 + val2;};
document.getElementById("p1").innerHTML = Sum(10,20);
function Multiply(val1, val2) {
console.log( val1 * val2);};
document.getElementById("p2").innerHTML = Multiply(10,20);

⦿ A function named Sum adds val1 & val2 and return it. So the calling code can
get the return value and assign it to a variable. The second function Multiply
does not return any value, so result variable will be undefined.
112
JavaScript – Nested Function
⦿ In JavaScript, a function can have one or more inner functions. These nested
functions are in the scope of outer function. Inner function can access
variables and parameters of outer function. However, outer function cannot
access variables defined inside inner functions.
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
return SayHello();
}
ShowMessage("Steve");
JS

113

You might also like