SlideShare a Scribd company logo
Introduction to JavaScript
Lecture 4
Slides adapted from CSE 154: Web Programming
https://courses.cs.washington.edu/courses/cse154/22sp/calendar/index.html
Today’s Agenda
● Separation of Concerns
● JavaScript
So What is a Web Page Really?
CONTENT STRUCTURE STYLE BEHAVIOR
What we’ve learned so far
● How to write content for a webpage using HTML5
● How to add styles to a webpage using CSS and linking a CSS file to an HTML file
● How to inspect the HTML and CSS of web pages in the browser
● (...also Git, some web accessibility, and some design/development strategies
as budding web developers!)
JavaScript is to Java as ...
Grapefruit Grape
→
Carpet Car
→
Hamster Ham
→
Catfish Cat
→
Horse Horseradish
→
What is JavaScript?
● A lightweight "scripting" programming language
● Created in 1995 by Brendan Eich (original prototype was created in 10
days and called LiveScript)
● NOT related to Java other than name and some syntactic similarities...
● Used to define interactivity for web pages.
Terminology: Client-Side Scripting
Client-side script: Code that runs on the user's computer and does not need a server to run (just
a web browser!).
Client-side JavaScript runs as part of the browser's process to load HTML and CSS (e.g., from a
server response). This JavaScript usually manipulates the page or responds to user actions
through "event handlers."
Why JavaScript and not another language?
Popularity.
The early web browsers supported it as a lightweight and flexible way to add interactivity to
pages.
Microsoft created their own version, called JScript, but the open source browsers (notably Firefox
and Chromium) and Adobe (via Flash and ActionScript) put all their effort into JavaScript and
standardized it as ECMAScript.
Note: If you want to run anything other than JavaScript in the browser… it's Very Hard™. There's
a long list of languages that people have "transpilers" for -- basically converting one language to
JavaScript. These are often error-prone, and have potential performance problems.
JS: Adding Behavior to HTML/CSS
We can use write JavaScript functions to...
● Insert dynamic text into HTML (e.g., username)
● React to events (e.g., page load, user's mouse click)
● Get information about a user's computer (e.g., what browser they are using)
● Request additional data needed for the page (e.g., from an API; more on this
in a couple weeks)
Today: Following Along
As an interpreted programming language, JS is great to interact with a line at a time
(similar to Python, but very different than Java). Where do you start?
The easiest way to dive in is with the Chrome browser's Console tab in the same inspector
tool you've used to inspect your HTML/CSS.
Until we learn how to interact with the HTML DOM with JS, we recommend experimenting
with the following code examples using this console to get comfortable with the basic
syntax and behavior.
Our First JavaScript Statement: console.log
Used to output values to the browser console, most often used to debug JS
programs. You can think of this as System.out.println in Java or print in
Python.
console.log("message");
console.log("The answer is: " + 42);
The alert function
A JS function that pops up a dialog box with a message - not ideal in practice, but
sometimes a recommended debugging tool when first learning JS. Don't include
alert statements in any of your assignments.
alert("message");
alert("Your browser says hi!");
Comments (similar to Java)
Identical to Java's comment syntax
Recall: 3 comment syntaxes
● HTML: <!-- comment -->
● CSS/Java/JS: /* comment */
● Java/JS: // single comment
○ /* multi-line */
For functions and program files, we'll use JSDoc commenting with @param and @returns, which
is covered in the Code Quality Guide here.
// single-line comment
/**
* multi-line
* comment
*/
Variables
Variables are declared with the let keyword (case-sensitive). You may also see var used
instead of let - this is an older convention with weaker scope - DO NOT USE var
anywhere
CQG: Use camelCasing for variable (and function) names
// template
let name = expression;
// examples
let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";
“Types” in JavaScript
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, but usually this is poor practice
(why?)
● Note: Type conversion isn't always what you expect...
let level = 23; // Number
let accuracyRate = 0.99; // Number
let name = "Pikachu"; // String
let temps = [55, 60, 57.5]; // Array
A Note about Declaring Types in JavaScript
In a dynamically-typed language like JavaScript, you don't need to specify the type (just
use let or const) and you may change the type the variable refers to later in execution.
boolean isValid = "hello!"; // error in JavaScript. boolean keyword doesn't exist
If you've programmed in a statically-typed language like Java, you will recall that when
declaring variables, you must specify their type which must always stay the same.
let isValid = true; // no error
isValid = "hello!";
isValid = 1;
isValid = true;
In a dynamically-typed language like JavaScript, you don't need to specify the type (just
use let or const) and you may change the type the variable refers to later in execution.
Number Type
● Integers and real numbers are the same type (no int vs. double). All numbers in JS
are floating point numbers.
● Same operators: + - * / % ++ -- = += -= *= /= %= and similar precedence
to Java.
● Many operators auto-convert types: "2" * 3 is 6
● NaN ("Not a Number") is a return value from operations that have an undefined
numerical result (e.g. dividing a String by a Number).
Practice!
let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);
String type
Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase, toUpperCase
let nickName = "Sparky O'Sparkz"; // "Sparky O'Sparks"
let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
let len = nickName.length; // 15
let name = 'Pikachu'; // can use "" or ''
More about Strings
To access characters of a String s, use s[index] or s.charAt(index):
let count = 10; // 10
let stringedCount = "" + count; // "10"
let puppyCount = count + " puppies, yay!"; // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?"); // NaN
Escape sequences behave as in Java: ' " & n t 
To convert between Numbers and Strings:
let firstLetter = puppyCount[0]; // "1"
let fourthLetter = puppyCount.charAt(3); // "p"
let lastLetter = puppyCount.charAt(puppyCount.length - 1); // "!"
Common Bugs when Using Strings
While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases
that you should be aware of.
● Remember that length is a property (not a method, as it is in Java)
● Concatenation with +: 1 + 1 is 2, but "1" + 1 and 1 + "1" are both "11"!
Practice: repeat
Special Values: null and undefined.
undefined: declared but has not yet been assigned a value
null: exists, but was specifically assigned an empty value or null. Expresses intentional
a lack of identification.
A good motivating overview of null vs. undefined
Note: This takes some time to get used to, and remember this slide if you get confused
let foo = null;
let bar = 9;
let baz;
/* At this point in the code,
* foo is null
* bar is 9
* baz is undefined
*/
Arrays
let name = []; // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value; // store element
let types = ["Electric", "Water", "Fire"];
let pokemon = []; // []
pokemon[0] = "Pikachu"; // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]
Two ways to initialize an array
length property (grows as needed when elements are added)
Some Notes on Typing
As you write JS programs, you may run into some silent bugs resulting from odd typing behavior in JS.
Automatic type conversion, or coercion, is a common, often perplexing, source of JS bugs (even for
experienced JS programmers).
Why is this important to be aware of? You'll be writing programs which use variables and conditional
logic. Knowing what is considered truthy/false and how types are evaluated (at a high level) can make
you a much happier JS developer (some practice)
Examples of some "not-so-obvious" evaluations:
2 < 1 < 2;// true
0 + "1" + 2;// "012"
[] + [];// ""
"1" / null;// Infinity
[+!![]]+[[![]+!![]]];// "11"
This is worth 3 minutes of your viewing pleasure. (starting at 1:20)
Defining Functions
The above could be the contents of basics.js linked to our HTML page
Statements placed into functions can be evaluated in response to user events
// template
function name(params) {
statement;
statement;
...
statement;
}
// example
function myFunction() {
console.log("Hello!");
alert("Your browser says hi!");
}
JS Function vs. Java Method
function repeat(str, n) {
let result = str;
for (let i = 1; i < n; i++) {
result += str;
}
return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
public static String repeat(String str, int n) {
String result = str;
for (int i = 1; i < n; i++) {
result += str;
}
return result;
}
String repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
JS Function vs. Python Function
function repeat(str, n) {
let result = str;
for (let i = 1; i < n; i++) {
result += str;
}
return result;
}
let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
}
def repeat(str, n):
result = str;
for i in range(1, n):
result = result + str;
return result;
repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."
Why do we talk about these things
separately?
● Separation of Concerns: a concept from Software Engineering that every
part of a program should address a separate "concern".
● In web programming, we define those concerns as:
○ Content (words, images)
○ Structure/Meaning (HTML)
○ Style/Appearance (CSS)
○ Behavior
● What happens if we don't separate them?
● How do we improve this?

More Related Content

PPTX
Learning space presentation1 learn Java script
PPTX
Java script
PPTX
JavaScript_III.pptx
PPTX
WTA-MODULE-4.pptx
PPTX
Unit 3-Javascript.pptx
PDF
Basic JavaScript Tutorial
PDF
JavaScript Interview Questions PDF By ScholarHat
PPTX
Final Java-script.pptx
Learning space presentation1 learn Java script
Java script
JavaScript_III.pptx
WTA-MODULE-4.pptx
Unit 3-Javascript.pptx
Basic JavaScript Tutorial
JavaScript Interview Questions PDF By ScholarHat
Final Java-script.pptx

Similar to Introduction to JavaScript - Web Programming (20)

PPTX
Web programming
PPTX
IntroJavascript.pptx cjfjgjggkgutufjf7fjvit8t
PPTX
Journey To The Front End World - Part3 - The Machine
PPTX
Java script.pptx v
PPTX
Introduction to JAVA SCRIPT USING HTML and CSS
PPTX
HNDIT1022 Week 08, 09 10 Theory web .pptx
PPT
Java script final presentation
PPTX
Java script
PPTX
Java script
PPT
Javascript sivasoft
PDF
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
DOC
Basics java scripts
PPTX
WT Unit-3 PPT.pptx
PPTX
Java script basics
PPT
Introduction to JavaScript
PPTX
Java script
PDF
8.-Javascript-report powerpoint presentation
PPT
Introduction to Java Scripting
PDF
internet Chapter 4-JavascripPrepare a ppt of video compression techniques bas...
Web programming
IntroJavascript.pptx cjfjgjggkgutufjf7fjvit8t
Journey To The Front End World - Part3 - The Machine
Java script.pptx v
Introduction to JAVA SCRIPT USING HTML and CSS
HNDIT1022 Week 08, 09 10 Theory web .pptx
Java script final presentation
Java script
Java script
Javascript sivasoft
java-scriptcdvcx vnbm,azsdfghjkml;sxdfcgmndxfcgvhb nmfctgvbhjnm ,cfgvb nm,xc ...
Basics java scripts
WT Unit-3 PPT.pptx
Java script basics
Introduction to JavaScript
Java script
8.-Javascript-report powerpoint presentation
Introduction to Java Scripting
internet Chapter 4-JavascripPrepare a ppt of video compression techniques bas...
Ad

Recently uploaded (20)

PDF
Chad Ayach - A Versatile Aerospace Professional
PDF
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
PPT
High Data Link Control Protocol in Data Link Layer
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
PPTX
Security-Responsibilities-in-the-Cloud-Azure-Shared-Responsibility-Model.pptx
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Glazing at Facade, functions, types of glazing
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PPTX
Ship’s Structural Components.pptx 7.7 Mb
PPTX
Practice Questions on recent development part 1.pptx
PDF
July 2025: Top 10 Read Articles Advanced Information Technology
PDF
Introduction to Data Science: data science process
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
PPT
Ppt for engineering students application on field effect
PDF
flutter Launcher Icons, Splash Screens & Fonts
PPTX
Soil science - sampling procedures for soil science lab
Chad Ayach - A Versatile Aerospace Professional
Monitoring Global Terrestrial Surface Water Height using Remote Sensing - ARS...
High Data Link Control Protocol in Data Link Layer
Structs to JSON How Go Powers REST APIs.pdf
The-Looming-Shadow-How-AI-Poses-Dangers-to-Humanity.pptx
Security-Responsibilities-in-the-Cloud-Azure-Shared-Responsibility-Model.pptx
Strings in CPP - Strings in C++ are sequences of characters used to store and...
algorithms-16-00088-v2hghjjnjnhhhnnjhj.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Glazing at Facade, functions, types of glazing
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Ship’s Structural Components.pptx 7.7 Mb
Practice Questions on recent development part 1.pptx
July 2025: Top 10 Read Articles Advanced Information Technology
Introduction to Data Science: data science process
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
ANIMAL INTERVENTION WARNING SYSTEM (4).pptx
Ppt for engineering students application on field effect
flutter Launcher Icons, Splash Screens & Fonts
Soil science - sampling procedures for soil science lab
Ad

Introduction to JavaScript - Web Programming

  • 1. Introduction to JavaScript Lecture 4 Slides adapted from CSE 154: Web Programming https://courses.cs.washington.edu/courses/cse154/22sp/calendar/index.html
  • 2. Today’s Agenda ● Separation of Concerns ● JavaScript
  • 3. So What is a Web Page Really? CONTENT STRUCTURE STYLE BEHAVIOR
  • 4. What we’ve learned so far ● How to write content for a webpage using HTML5 ● How to add styles to a webpage using CSS and linking a CSS file to an HTML file ● How to inspect the HTML and CSS of web pages in the browser ● (...also Git, some web accessibility, and some design/development strategies as budding web developers!)
  • 5. JavaScript is to Java as ... Grapefruit Grape → Carpet Car → Hamster Ham → Catfish Cat → Horse Horseradish →
  • 6. What is JavaScript? ● A lightweight "scripting" programming language ● Created in 1995 by Brendan Eich (original prototype was created in 10 days and called LiveScript) ● NOT related to Java other than name and some syntactic similarities... ● Used to define interactivity for web pages.
  • 7. Terminology: Client-Side Scripting Client-side script: Code that runs on the user's computer and does not need a server to run (just a web browser!). Client-side JavaScript runs as part of the browser's process to load HTML and CSS (e.g., from a server response). This JavaScript usually manipulates the page or responds to user actions through "event handlers."
  • 8. Why JavaScript and not another language? Popularity. The early web browsers supported it as a lightweight and flexible way to add interactivity to pages. Microsoft created their own version, called JScript, but the open source browsers (notably Firefox and Chromium) and Adobe (via Flash and ActionScript) put all their effort into JavaScript and standardized it as ECMAScript. Note: If you want to run anything other than JavaScript in the browser… it's Very Hard™. There's a long list of languages that people have "transpilers" for -- basically converting one language to JavaScript. These are often error-prone, and have potential performance problems.
  • 9. JS: Adding Behavior to HTML/CSS We can use write JavaScript functions to... ● Insert dynamic text into HTML (e.g., username) ● React to events (e.g., page load, user's mouse click) ● Get information about a user's computer (e.g., what browser they are using) ● Request additional data needed for the page (e.g., from an API; more on this in a couple weeks)
  • 10. Today: Following Along As an interpreted programming language, JS is great to interact with a line at a time (similar to Python, but very different than Java). Where do you start? The easiest way to dive in is with the Chrome browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS. Until we learn how to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the basic syntax and behavior.
  • 11. Our First JavaScript Statement: console.log Used to output values to the browser console, most often used to debug JS programs. You can think of this as System.out.println in Java or print in Python. console.log("message"); console.log("The answer is: " + 42);
  • 12. The alert function A JS function that pops up a dialog box with a message - not ideal in practice, but sometimes a recommended debugging tool when first learning JS. Don't include alert statements in any of your assignments. alert("message"); alert("Your browser says hi!");
  • 13. Comments (similar to Java) Identical to Java's comment syntax Recall: 3 comment syntaxes ● HTML: <!-- comment --> ● CSS/Java/JS: /* comment */ ● Java/JS: // single comment ○ /* multi-line */ For functions and program files, we'll use JSDoc commenting with @param and @returns, which is covered in the Code Quality Guide here. // single-line comment /** * multi-line * comment */
  • 14. Variables Variables are declared with the let keyword (case-sensitive). You may also see var used instead of let - this is an older convention with weaker scope - DO NOT USE var anywhere CQG: Use camelCasing for variable (and function) names // template let name = expression; // examples let level = 23; let accuracyRate = 0.99; let name = "Pikachu";
  • 15. “Types” in JavaScript 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, but usually this is poor practice (why?) ● Note: Type conversion isn't always what you expect... let level = 23; // Number let accuracyRate = 0.99; // Number let name = "Pikachu"; // String let temps = [55, 60, 57.5]; // Array
  • 16. A Note about Declaring Types in JavaScript In a dynamically-typed language like JavaScript, you don't need to specify the type (just use let or const) and you may change the type the variable refers to later in execution. boolean isValid = "hello!"; // error in JavaScript. boolean keyword doesn't exist If you've programmed in a statically-typed language like Java, you will recall that when declaring variables, you must specify their type which must always stay the same. let isValid = true; // no error isValid = "hello!"; isValid = 1; isValid = true; In a dynamically-typed language like JavaScript, you don't need to specify the type (just use let or const) and you may change the type the variable refers to later in execution.
  • 17. Number Type ● Integers and real numbers are the same type (no int vs. double). All numbers in JS are floating point numbers. ● Same operators: + - * / % ++ -- = += -= *= /= %= and similar precedence to Java. ● Many operators auto-convert types: "2" * 3 is 6 ● NaN ("Not a Number") is a return value from operations that have an undefined numerical result (e.g. dividing a String by a Number). Practice! let enrollment = 99; let medianGrade = 2.8; let credits = 5 + 4 + (2 * 3);
  • 18. String type Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split, substring, toLowerCase, toUpperCase let nickName = "Sparky O'Sparkz"; // "Sparky O'Sparks" let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky" let len = nickName.length; // 15 let name = 'Pikachu'; // can use "" or ''
  • 19. More about Strings To access characters of a String s, use s[index] or s.charAt(index): let count = 10; // 10 let stringedCount = "" + count; // "10" let puppyCount = count + " puppies, yay!"; // "10 puppies, yay!" let magicNum = parseInt("42 is the answer"); // 42 let mystery = parseFloat("Am I a number?"); // NaN Escape sequences behave as in Java: ' " & n t To convert between Numbers and Strings: let firstLetter = puppyCount[0]; // "1" let fourthLetter = puppyCount.charAt(3); // "p" let lastLetter = puppyCount.charAt(puppyCount.length - 1); // "!"
  • 20. Common Bugs when Using Strings While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases that you should be aware of. ● Remember that length is a property (not a method, as it is in Java) ● Concatenation with +: 1 + 1 is 2, but "1" + 1 and 1 + "1" are both "11"! Practice: repeat
  • 21. Special Values: null and undefined. undefined: declared but has not yet been assigned a value null: exists, but was specifically assigned an empty value or null. Expresses intentional a lack of identification. A good motivating overview of null vs. undefined Note: This takes some time to get used to, and remember this slide if you get confused let foo = null; let bar = 9; let baz; /* At this point in the code, * foo is null * bar is 9 * baz is undefined */
  • 22. Arrays let name = []; // empty array let names = [value, value, ..., value]; // pre-filled names[index] = value; // store element let types = ["Electric", "Water", "Fire"]; let pokemon = []; // [] pokemon[0] = "Pikachu"; // ["Pikachu"] pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"] pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"] pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"] Two ways to initialize an array length property (grows as needed when elements are added)
  • 23. Some Notes on Typing As you write JS programs, you may run into some silent bugs resulting from odd typing behavior in JS. Automatic type conversion, or coercion, is a common, often perplexing, source of JS bugs (even for experienced JS programmers). Why is this important to be aware of? You'll be writing programs which use variables and conditional logic. Knowing what is considered truthy/false and how types are evaluated (at a high level) can make you a much happier JS developer (some practice) Examples of some "not-so-obvious" evaluations: 2 < 1 < 2;// true 0 + "1" + 2;// "012" [] + [];// "" "1" / null;// Infinity [+!![]]+[[![]+!![]]];// "11" This is worth 3 minutes of your viewing pleasure. (starting at 1:20)
  • 24. Defining Functions The above could be the contents of basics.js linked to our HTML page Statements placed into functions can be evaluated in response to user events // template function name(params) { statement; statement; ... statement; } // example function myFunction() { console.log("Hello!"); alert("Your browser says hi!"); }
  • 25. JS Function vs. Java Method function repeat(str, n) { let result = str; for (let i = 1; i < n; i++) { result += str; } return result; } let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..." public static String repeat(String str, int n) { String result = str; for (int i = 1; i < n; i++) { result += str; } return result; } String repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
  • 26. JS Function vs. Python Function function repeat(str, n) { let result = str; for (let i = 1; i < n; i++) { result += str; } return result; } let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..." } def repeat(str, n): result = str; for i in range(1, n): result = result + str; return result; repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."
  • 27. Why do we talk about these things separately? ● Separation of Concerns: a concept from Software Engineering that every part of a program should address a separate "concern". ● In web programming, we define those concerns as: ○ Content (words, images) ○ Structure/Meaning (HTML) ○ Style/Appearance (CSS) ○ Behavior ● What happens if we don't separate them? ● How do we improve this?