0% found this document useful (0 votes)
6 views

Module-1

The document provides an introduction to JavaScript, highlighting its role as a client-side scripting language that enhances web page interactivity and usability. It covers the differences between JavaScript and Java, the history of JavaScript, and fundamental concepts such as data types, functions, and arrays. Additionally, it discusses various programming constructs, including variable declarations, function expressions, and string manipulation methods.

Uploaded by

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

Module-1

The document provides an introduction to JavaScript, highlighting its role as a client-side scripting language that enhances web page interactivity and usability. It covers the differences between JavaScript and Java, the history of JavaScript, and fundamental concepts such as data types, functions, and arrays. Additionally, it discusses various programming constructs, including variable declarations, function expressions, and string manipulation methods.

Uploaded by

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

1 Intro to Javascript

CS380
Web Application
2

CS380
Client Side Scripting
3

CS380
Why use client-side
4
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
CS380
Why use client-side
5
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, ...

CS380
What is Javascript?
6

 a lightweight programming language


("scripting language")
 used to make web pages interactive
 insert dynamic text into HTML (ex: user
name)
 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)
CS380
What is Javascript?
7

 a web standard (but not supported


identically by all browsers)
 NOT related to Java other than by name
and some syntactic similarities

CS380
Javascript vs Java
8

 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
CS380
integrates with its HTML/CSS content
Javascript vs Java
9

+ =

CS380
History of JavaScript
10

 1995 – Created by Brendan Eich at


Netscape. Initially called Mocha, then
LiveScript, and finally JavaScript.
 1997 – Standardized as ECMAScript (ES1)

to ensure consistency across browsers.


 2005 – AJAX made JavaScript more

powerful, enabling dynamic web


applications like Google Maps and Gmail.
 2009 – Node.js allowed JavaScript to run

on servers.
 Today – JavaScript powers web, mobile,
CS380
Linking to a JavaScript file:
11
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

CS380
Data Types in JavaScript
12

 JavaScript has two main categories of


data types:
1. Primitive Data Types (Stored by value)
2. Non-Primitive (Reference) Data Types
(Stored by reference)

CS380
Primitive Data Types
13

CS380
Non-Primitive (Reference)
14
Data Types

CS380
Example Usage of Different
15
Data Types
 // Primitive Types
 var name = "Alice"; // String
 var age = 30; // Number
 var bigNum = 123n; // BigInt
 var isStudent = true; // Boolean
 var x; // Undefined
 var y = null; // Null
 var id = Symbol('id');// Symbol

CS380
Example Usage of Different
16
Data Types
 // Non-Primitive Types
 var person = { name: "Alice", age:
30 }; // Object
 var numbers = [1, 2, 3, 4]; //
Array
 function sayHello() { //
Function
 console.log("Hello!");
 }
CS380
Var, let, const
17

CS380
var
18
 var x = 10;
 function test() {
 var x = 20; // Function-scoped (separate from global x)
 if (true) {
 var x = 30; // ✅ Not block-scoped, overwrites function `x`
 console.log("Inside if block:", x); // 30
 }
 console.log("Inside function, after if block:", x); // 30 (Value
changed due to `var`)
 }
 test();
 console.log("Global scope:", x); // 10 (Unchanged, as function has
its own x)
CS380
let
19
 let x = 10;
 function test() {
 let x = 20; // Function-scoped (separate from global x)
 if (true) {
 let x = 30; // Block-scoped (exists only inside this if block)
 console.log("Inside if block:", x); // 30
 }
 console.log("Inside function, after if block:", x); // 20
(Unchanged, as if block had its own x)
 }
 test();
 console.log("Global scope:", x); // 10 (Unchanged, as function has
its own x)
CS380
const
20

 const PI = 3.14159; // Declaring a


constant variable
 console.log("Value of PI:", PI);

 // PI = 3.14; // ❌ This will cause an error


because 'const' values cannot be
reassigned.

CS380
Arrays
21

 An array in JavaScript is object (special


variable) that can hold multiple values
in a single variable.
 It allows storing and manipulating lists of
data efficiently.
 Key Features of Arrays:
 ✅ Stores multiple values in a single variable
✅ Allows different data types (numbers, strings,
objects, etc.)
✅ Has built-in methods for adding, removing, and
sorting elements
CS380
✅ Index-based access (0-based index)
example
22

 let fruits = ["Apple", "Banana",


"Cherry"];
 console.log(fruits);
 // Output: ["Apple", "Banana", "Cherry"]

CS380
Using Cosntructor
23

 let arr1 = new Array(); // Creates an


empty array
 let arr2 = new Array(5); // Creates an
array with 5 empty slots
 let arr3 = new Array(10, 20, 30); //
Creates an array with values
 console.log(arr1, arr2, arr3);

CS380
Array functions
24

CS380
Array functions
25

CS380
Functions
26

 A function in JavaScript is a reusable


block of code that performs a specific
task.
 Functions help organize and simplify
code.
 function greet() {
 console.log("Hello, World!");
 }
 greet(); // Calls the function

CS380
Function with Parameters
27

 function add(a, b) {
 var r = a + b;
console.log(r); // 8

 }

CS380
Function with Parameters &
28
return type
 function add(a, b) {
 return a + b;
 }
 console.log(add(6,2)); // 8

CS380
Return multiple values
29

 function getValues() {
 return 10, 20, 30; // Only 30 is
returned (last value)
 }

 console.log(getValues()); // Output: 30

CS380
Return multiple values
30

 function getCoordinates() {
 return [10, 20]; // Returning multiple
values as an array
 }

 const [x, y] = getCoordinates();


 console.log(x, y); // Output: 10 20

CS380
Functions with same names
31

 function add() {
 a=20; b=30;
 console.log(a+b);
 }
 function add() {
 city = "bangalore";
 console.log(city);
 }
 add();
CS380
Function Expression
32
(Anonymous Function)
 const greet = function() {
 console.log("Hello!");
 };
 greet();

CS380
Arrow fucntions
33

 Arrow functions provide a shorter syntax


for writing functions in JavaScript.
 They use => (arrow) instead of the
function keyword.
 They do not have their own this context.

CS380
34

 // Regular function
 function add(a, b) {
 return a + b;
 }

 // Arrow function (shorter version)


 const add = (a, b) => a + b;

 console.log(add(5, 3)); // Output: 8


CS380
35

 const square = num => {


 let result = num * num;
 return result;
 };
 console.log(square(6)); // Output: 36

CS380
callback function
36

 A callback function is a function


passed as an argument to another
function and executed later.
 🔹 Why use callbacks?
• Handles asynchronous tasks like fetching
data.
• Allows custom behavior to be passed to
functions.

CS380
callback function
37

 function greet(name, x) {
 console.log("Hello, " + name);
 x(); // Executing the callback function
 }

 function sayGoodbye() { //callback fucntion


 console.log("Goodbye!");
 }

 greet("Umesh", sayGoodbye);
CS380
higher-order function
38

 A higher-order function (HOF) is a


function that:
✔ Takes a function as an argument
(callback) OR
✔ Returns a function
 🔹 Why use higher-order functions?
• Makes code more reusable and
modular
• Allows for functional programming
techniques
CS380
HOF
39

 function greet(name, x) {//Higher order


function
 console.log("Hello, " + name);
 x(); // Executing the callback function
 }

 function sayGoodbye() { //callback fucntion


 console.log("Goodbye!");
 }

 greet("Umesh", sayGoodbye);
CS380
HOF returning a fucntion
40

 function greet(name) {
 console.log("Hello, " + name);

 // Returning a function (instead of executing it


immediately)
 return function sayGoodbye() {
 console.log("Goodbye, " + name + "!");
 };
 }
 // Using the HOF
 const farewell = greet(“ISE"); // "Hello, ISE"
 farewell(); // "Goodbye, ISE!"
CS380
Strings
41

 A string is a sequence of characters


enclosed in quotes.
 immutable
 In JavaScript, strings can be written
using:
 ✔ Single quotes → 'Hello'
 ✔ Double quotes → "Hello"
 ✔ Template literals (ES6) → `Hello`

CS380
Example
42

 let str1 = 'Hello';


 let str2 = "JavaScript";
 let str3 = `Welcome, ${str2}!`; //
Template literal (String Interpolation)

 console.log(str3); // Output: Welcome,


JavaScript!

 ${} (Template Literals / String


Interpolation) is a feature of ES6 that
CS380
Difference Between string
43
and String
 let str1 = "Hello"; // Primitive string
 let str2 = new String("Hello"); // String
object

 console.log(str1 == str2); // true


(values are the same)
 console.log(str1 === str2); // false
(different types: string vs object)
 ✔ == compares values, so "Hello" == new
String("Hello") is true.
CS380
 ✔ === checks both value & type, so it returns
Difference Between string
44
and String

CS380
String Properties
45

 let text = "JavaScript";


 console.log(text.length); // Output: 10

CS380
Common String Methods
46

CS380
Changing Case
47

 console.log("hello".toUpperCase()); // Output:
"HELLO"
 console.log("WORLD".toLowerCase()); // Output:
"world"

CS380
Finding a Character or Word
48

 let text = "JavaScript is fun";


 console.log(text.indexOf("Script")); // Output: 4
 console.log(text.lastIndexOf("is")); // Output: 11
 console.log(text.includes("fun")); // Output: true
 console.log(text.startsWith("Java")); // Output:
true
 console.log(text.endsWith("fun")); // Output:
true

CS380
Extracting Part of a String
49

 let str = "JavaScript";


 console.log(str.slice(0, 4)); // Output:
"Java"
 console.log(str.substring(4, 10)); //
Output: "Script"

CS380
Replacing Text
50

 let text = "JavaScript is awesome!";


 console.log(text.replace("awesome",
"great")); // Output: "JavaScript is great!"
 console.log(text.replaceAll("a", "@")); //
Output: "J@v@Script is @wesome!"

CS380
Splitting a String
51

 let names = "Umesh,John,Mike";


 console.log(names.split(",")); // Output:
["Umesh", "John", "Mike"]

CS380
Removing Extra Spaces
52

 let text = " Hello World! ";


 console.log(text.trim()); // Output: "Hello
World!"
 console.log(text.trimStart()); // Output:
"Hello World! "
 console.log(text.trimEnd()); // Output: "
Hello World!"

CS380
Repeating a String
53

 console.log("Hello ".repeat(3)); // Output:


"Hello Hello Hello "

CS380
Getting a Character from a
54
String
 let str = "JavaScript";
 console.log(str.charAt(2)); // Output: "v"
 console.log(str[2]); // Output: "v"

CS380
Concatenating Strings
55

 let first = "Hello";


 let second = "World";
 console.log(first.concat(" ", second)); //
Output: "Hello World"

CS380
Escape Characters
56

 Escape characters are special sequences


used in JavaScript strings to represent
characters that are difficult or impossible
to type directly.
 They begin with a backslash (\).

CS380
Escape Characters
57

CS380
Example
58

 let str1 = 'It\'s a beautiful day'; // Using \' for


single quote
 let str2 = "He said, \"Hello!\""; // Using \" for
double quotes
 let str3 = "C:\\Users\\Umesh"; // Using \\ for
backslash
 let str4 = "Hello\nWorld"; // Newline
 let str5 = "Hello\tWorld"; // Tab

 console.log(str1);
 console.log(str2);
CS380
 console.log(str3);
Example
59

 let name = "Umesh";


 let message = `Hello, ${name}!
 Welcome to JavaScript.`;

 console.log(message);

CS380
Lab Pgm 2
60

 Read a string from the user, Find its


length. Extract the word "JavaScript"
using substring() or slice(). Replace one
word with another word and log the new
string. Write a function isPalindrome(str)
that checks if a given string is a
palindrome (reads the same backward)

CS380
Objects
61

 An object is a collection of key-value


pairs.
 They store multiple values in a
structured way.
 Keys (also called properties) are
strings, and values can be any data
type (numbers, strings, arrays, etc.).

CS380
Creating an Object
62

 Objects can be created using:


 Object Literals
 new Object() Syntax
 Constructor Functions

CS380
1. Object Literal
63

 let person = {
 name: “Sukesh",
 age: 18,
 profession: “Student",
 greet: function() {
 console.log("Hello, my name is
" + this.name);
 }
 };
CS
Accessing Object Properties
64

 Dot Notation: objectName.propertyName


 Bracket Notation:
objectName["propertyName"]
 Example:

 console.log(person.age); // Output:
18
 console.log(person[" profession "]); //
Output: student
CS380
Adding and Modifying
65
Properties
 person.city = "Bangalore"; // Adding new
property
 person.age = 18; // Modifying existing
property

 console.log(person.city); // "Bangalore"
 console.log(person.age); // 18

CS380
Deleting Properties
66

 delete person.profession;
 console.log(person.profession); //
undefined

CS380
Using this Keyword
67

 Refers to the current object.


 Example:
 let student = {
 name: "Pari",
 greet: function() {
 console.log("Hello, " + this.name);
 }
 };
 student.greet(); // Output: Hello, Pari
CS380
Nested Objects
68

 Objects inside objects.


 Example:

 let employee = {

 name: "Anil",
 address: {
 city: "Mumbai",
 country: "India"
 }
 };
CS380
 console.log(employee.address.city); //
2. Using new Object()
69
Syntax
 Creates an empty object first, then adds
properties.
 Example:

 let student = new Object();

 student.name = "Pari";

 student.age = 8;

 student.study = function() {

 console.log(this.name + " is
studying.");
 };
CS380
3. Using Constructor
70
Function
 Define a function and use this to assign
properties.
 Use new to create objects from it.

 Example:

 function Person(name, age) {

 this.name = name;
 this.age = age;
 this.greet = function() {
 console.log("Hello, " + this.name);
CS380
 };
71

 let person1 = new Person("Sukesh", 10);


 let person2 = new Person("Pari", 8);

 console.log(person1.name); // Output:
Sukesh
 person2.greet(); // Output: Hello, Pari

CS380
When to use what?
72

CS380
Array of Objects
73

 1. Using Object Literals Inside an Array


 Define multiple objects inside an array.

 let students = [

 { name: "Sukesh", age: 10 },


 { name: "Pari", age: 8 },
 { name: "Aarav", age: 12 }
 ];

 console.log(students[0].name); //

Output: Sukesh
CS380
 console.log(students[1].age); // Output:
2. Using Constructor
74
Function
 Create multiple objects using a function.
 function Student(name, age) {

 this.name = name;
 this.age = age;
 }

 let students = [

 new Student("Sukesh", 10),


 new Student("Pari", 8),
 new Student("Aarav", 12)
CS380
 ];
3. Using new Object() Inside
75
an Array
 Create objects dynamically and push
them into an array.
 let students = [ ];
 let student1 = new Object();
 student1.name = "Sukesh";
 student1.age = 10;
 let student2 = new Object();
 student2.name = "Pari";
 student2.age = 8;
CS380
76

 students.push(student1, student2);

 console.log(students[0].name); //
Output: Sukesh

CS380
Iterating on students
77
objects
 let students = [
 { name: "Sukesh", age: 10 },
 { name: "Pari", age: 8 },
 { name: "Aarav", age: 12 }
 ];

 for (let i = 0; i < students.length; i++) {


 console.log(students[i].name + " is "
+ students[i].age + " years old.");
CS380
 }
Decision Statements
78

 JavaScript provides decision-making


statements to execute different code
blocks based on conditions.
 1. if Statement
 Executes a block of code if the condition
is true.

 if (condition) {
 // Code to execute if condition is true
 }
CS380
Example:
79

 let age = 18;


 if (age >= 18) {
 console.log("You are eligible to vote.");
 }

CS380
2. if...else Statement
80

 Executes one block if the condition is true, otherwise


executes another block.
 if (condition) {
 // Code if condition is true
 } else {
 // Code if condition is false
 }
 let num = 10;
 if (num % 2 === 0) {
 console.log("Even number");
 } else {
 console.log("Odd number");
 }
CS380
3. if...else if...else
Statement
81

 Used when there are multiple conditions.


 if (condition1) {
 // Code if condition1 is true
 } else if (condition2) {
 // Code if condition2 is true
 } else {
 // Code if none of the conditions are
true
 }
CS380
example
82

 let marks = 85;


 if (marks >= 90) {
 console.log("Grade: A");
 } else if (marks >= 75) {
 console.log("Grade: B");
 } else {
 console.log("Grade: C");
 }

CS380
4. Ternary Operator (Shorter if-
83
else)
 A shorthand for if...else statements.

 Syntax:
 condition ? "true statement" : "false
statement";

 Example:
 let x = 5;

 let result = (x > 0) ? "Positive" :

"Negative";
CS380
5. switch Statement
84

 Used when multiple values need to be checked.

 Syntax:
 switch (expression) {
 case value1:
 // Code for case 1
 break;
 case value2:
 // Code for case 2
 break;
 default:
 // Code if no cases match
CS380
 }
Example:
85

 let day = 2;
 switch (day) {

 case 1:
 console.log("Monday");
 break;
 case 2:
 console.log("Tuesday");
 break;
 default:
 console.log("Invalid day");
 }
CS380
Looping Statements in
86
JavaScript
 Loops in JavaScript are used to execute a
block of code repeatedly based on a
condition.
 1. for Loop

 Used when the number of iterations is

known.
 for (initialization; condition;

increment/decrement) {
 // Code to execute
 }
CS380

2. while Loop
87

 Used when the number of iterations is


not fixed; runs while the condition is
true.
 while (condition) {
 // Code to execute
 }
 Example:
 let i = 1;

 while (i <= 5) {

 console.log("Number: " + i);


CS380
 i++;
3. do...while Loop
88

 Executes the code at least once, then repeats


while the condition is true.
 Syntax:
 do {
 // Code to execute
 } while (condition);
 Example:
 let i = 1;
 do {
 console.log("Value: " + i);
 i++;
 } while (i <= 5);
CS380
4. for...in Loop
89

 Used to iterate over object properties.


 Syntax:
 for (let key in object) {
 // Code to execute
 }

 Example:

 let student = { name: "John", age: 20, course:

"JavaScript" };
 for (let key in student) {

 console.log(key + ": " + student[key]);


 }
CS380
5. for...of Loop
90

 Used to iterate over iterable objects like


arrays or strings.
 Syntax:
 for (let variable of iterable) {

 // Code to execute
 }

 Example:

 let colors = ["Red", "Green", "Blue"];

 for (let color of colors) {

 console.log(color);
 }
CS380
91

CS380
92

CS380
Using forEach() (More
93
Readable)
 students.forEach(student => {
 console.log(student.name + " is " +
student.age + " years old.");
 });

CS380
Using for...of Loop
94

 let students = [
 { name: "Sukesh", age: 10 },
 { name: "Pari", age: 8 },
 { name: "Aarav", age: 12 }
 ];

 for (let student of students) {


 console.log(student.name + " is " +
student.age + " years old.");
CS380
 }
95

CS380
Event-driven programming
96

 split breaks apart a string into an array


using a delimiter
 can also be used with regular expressions
(seen later)
 join merges an array into a single string,
placing a delimiter between them
CS380
A JavaScript statement:
97
alert
alert("IE6 detected. Suck-mode enabled.");
JS

 a JS command that pops up a dialog box


with a message
CS380
Event-driven programming
98

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


CS380
Buttons
99
<button>Click me!</button> HTML

 button's text appears inside tag; can


also contain images
 To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event
(e.g. mouse 1. click) of interest
2. write a JavaScript function to run when
the event occurs
3. attach the function to the event on the
CS380 control
JavaScript functions
10
0
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


CS380
Event handlers
10
1
<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


CS380
Document Object Model
10
(DOM)
2
 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
DOM element objects
10
3
Accessing elements:
10
document.getElementById
4
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

CS380
Accessing elements:
10
document.getElementById
5
 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

CS380
Changing element style:
10
element.style
6

Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380
Preetify
10
7
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

CS380
108 More Javascript Syntax

CS380
Variables
10
9
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
CS380
typeof
Number type
11
0
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS

 integers and real numbers are the same


type (no int vs. double)
 same operators: + - * / % ++ -- = += -=
*= /= %=
 similar precedence to Java
 many operators auto-convert types: "2"
* 3 is 6
CS380
Comments (same as Java)
11
1
// 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

CS380
Math object
11
2
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

CS380
Special values: null and
11
undefined
3
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 of these?
CS380
Logical operators
11
4

 > < >= <= && || ! == != === !==


 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
CS380
if/else statement (same as
11
Java)
5
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
 identical structure to Java's if/else
statement
 JavaScript allows almost anything as a
condition

CS380
Boolean type
11
6
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
 any value can be used as a Boolean
 "falsey" values: 0, 0.0, NaN, "", null, and
undefined
 "truthy" values: anything else
 converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
CS380
 var boolValue = !!(otherValue);
for loop (same as Java)
11
7
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

CS380
while loops (same as Java)
11
8
while (condition) {
statements;
} JS

do {
statements;
} while (condition);
JS

 break and continue keywords also


behave as in Java

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

CS380
Arrays
12
0
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS

var ducks = ["Huey", "Dewey", "Louie"];


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

CS380
Array methods
12
1
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
a.sort(); // Jason, Stef
JS
 array serves as many data structures: list,
queue, stack, ...
 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
String type
12
2
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 ''

More about String
12
3
 escape sequences behave as in Java: \' \"
\& \n \t \\
 converting between numbers and
var Strings:
count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS

 accessing the letters of a String:


var firstLetter = s[0]; // fails in IE
var firstLetter = s.charAt(0); // does work in IE
var lastLetter = s.charAt(s.length - 1);
JS
CS380
Splitting strings: split and
12
join
4
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
JS

 split breaks apart a string into an array


using a delimiter
 can also be used with regular expressions
(seen later)
 join merges an array into a single string,
placing a delimiter between them

You might also like